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

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.162! raeburn     4: # $Id: loncommon.pm,v 1.1075.2.161 2021/12/30 15:29:57 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.1075.2.135  raeburn    74: use HTTP::Request;
1.657     raeburn    75: use DateTime::TimeZone;
1.1075.2.102  raeburn    76: use DateTime::Locale;
1.1075.2.94  raeburn    77: use Encode();
1.1075.2.14  raeburn    78: use Authen::Captcha;
                     79: use Captcha::reCAPTCHA;
1.1075.2.107  raeburn    80: use JSON::DWIW;
                     81: use LWP::UserAgent;
1.1075.2.64  raeburn    82: use Crypt::DES;
                     83: use DynaLoader; # for Crypt::DES version
1.1075.2.128  raeburn    84: use File::Copy();
                     85: use File::Path();
1.117     www        86: 
1.517     raeburn    87: # ---------------------------------------------- Designs
                     88: use vars qw(%defaultdesign);
                     89: 
1.22      www        90: my $readit;
                     91: 
1.517     raeburn    92: 
1.157     matthew    93: ##
                     94: ## Global Variables
                     95: ##
1.46      matthew    96: 
1.643     foxr       97: 
                     98: # ----------------------------------------------- SSI with retries:
                     99: #
                    100: 
                    101: =pod
                    102: 
1.648     raeburn   103: =head1 Server Side include with retries:
1.643     foxr      104: 
                    105: =over 4
                    106: 
1.648     raeburn   107: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      108: 
                    109: Performs an ssi with some number of retries.  Retries continue either
                    110: until the result is ok or until the retry count supplied by the
                    111: caller is exhausted.  
                    112: 
                    113: Inputs:
1.648     raeburn   114: 
                    115: =over 4
                    116: 
1.643     foxr      117: resource   - Identifies the resource to insert.
1.648     raeburn   118: 
1.643     foxr      119: retries    - Count of the number of retries allowed.
1.648     raeburn   120: 
1.643     foxr      121: form       - Hash that identifies the rendering options.
                    122: 
1.648     raeburn   123: =back
                    124: 
                    125: Returns:
                    126: 
                    127: =over 4
                    128: 
1.643     foxr      129: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   130: 
1.643     foxr      131: response   - The response from the last attempt (which may or may not have been successful.
                    132: 
1.648     raeburn   133: =back
                    134: 
                    135: =back
                    136: 
1.643     foxr      137: =cut
                    138: 
                    139: sub ssi_with_retries {
                    140:     my ($resource, $retries, %form) = @_;
                    141: 
                    142: 
                    143:     my $ok = 0;			# True if we got a good response.
                    144:     my $content;
                    145:     my $response;
                    146: 
                    147:     # Try to get the ssi done. within the retries count:
                    148: 
                    149:     do {
                    150: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    151: 	$ok      = $response->is_success;
1.650     www       152:         if (!$ok) {
                    153:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    154:         }
1.643     foxr      155: 	$retries--;
                    156:     } while (!$ok && ($retries > 0));
                    157: 
                    158:     if (!$ok) {
                    159: 	$content = '';		# On error return an empty content.
                    160:     }
                    161:     return ($content, $response);
                    162: 
                    163: }
                    164: 
                    165: 
                    166: 
1.20      www       167: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  168: my %language;
1.124     www       169: my %supported_language;
1.1048    foxr      170: my %latex_language;		# For choosing hyphenation in <transl..>
                    171: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  172: my %cprtag;
1.192     taceyjo1  173: my %scprtag;
1.351     www       174: my %fe; my %fd; my %fm;
1.41      ng        175: my %category_extensions;
1.12      harris41  176: 
1.46      matthew   177: # ---------------------------------------------- Thesaurus variables
1.144     matthew   178: #
                    179: # %Keywords:
                    180: #      A hash used by &keyword to determine if a word is considered a keyword.
                    181: # $thesaurus_db_file 
                    182: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   183: 
                    184: my %Keywords;
                    185: my $thesaurus_db_file;
                    186: 
1.144     matthew   187: #
                    188: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    189: # thesaurus.tab, and filecategories.tab.
                    190: #
1.18      www       191: BEGIN {
1.46      matthew   192:     # Variable initialization
                    193:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    194:     #
1.22      www       195:     unless ($readit) {
1.12      harris41  196: # ------------------------------------------------------------------- languages
                    197:     {
1.158     raeburn   198:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    199:                                    '/language.tab';
1.1075.2.128  raeburn   200:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  201:             while (my $line = <$fh>) {
                    202:                 next if ($line=~/^\#/);
                    203:                 chomp($line);
1.1048    foxr      204:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   205:                 $language{$key}=$val.' - '.$enc;
                    206:                 if ($sup) {
                    207:                     $supported_language{$key}=$sup;
                    208:                 }
1.1048    foxr      209: 		if ($latex) {
                    210: 		    $latex_language_bykey{$key} = $latex;
                    211: 		    $latex_language{$two} = $latex;
                    212: 		}
1.158     raeburn   213:             }
                    214:             close($fh);
                    215:         }
1.12      harris41  216:     }
                    217: # ------------------------------------------------------------------ copyrights
                    218:     {
1.158     raeburn   219:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    220:                                   '/copyright.tab';
1.1075.2.128  raeburn   221:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  222:             while (my $line = <$fh>) {
                    223:                 next if ($line=~/^\#/);
                    224:                 chomp($line);
                    225:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   226:                 $cprtag{$key}=$val;
                    227:             }
                    228:             close($fh);
                    229:         }
1.12      harris41  230:     }
1.351     www       231: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  232:     {
                    233:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    234:                                   '/source_copyright.tab';
1.1075.2.128  raeburn   235:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  236:             while (my $line = <$fh>) {
                    237:                 next if ($line =~ /^\#/);
                    238:                 chomp($line);
                    239:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  240:                 $scprtag{$key}=$val;
                    241:             }
                    242:             close($fh);
                    243:         }
                    244:     }
1.63      www       245: 
1.517     raeburn   246: # -------------------------------------------------------------- default domain designs
1.63      www       247:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   248:     my $designfile = $designdir.'/default.tab';
1.1075.2.128  raeburn   249:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   250:         while (my $line = <$fh>) {
                    251:             next if ($line =~ /^\#/);
                    252:             chomp($line);
                    253:             my ($key,$val)=(split(/\=/,$line));
                    254:             if ($val) { $defaultdesign{$key}=$val; }
                    255:         }
                    256:         close($fh);
1.63      www       257:     }
                    258: 
1.15      harris41  259: # ------------------------------------------------------------- file categories
                    260:     {
1.158     raeburn   261:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    262:                                   '/filecategories.tab';
1.1075.2.128  raeburn   263:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  264: 	    while (my $line = <$fh>) {
                    265: 		next if ($line =~ /^\#/);
                    266: 		chomp($line);
                    267:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1075.2.119  raeburn   268:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   269:             }
                    270:             close($fh);
                    271:         }
                    272: 
1.15      harris41  273:     }
1.12      harris41  274: # ------------------------------------------------------------------ file types
                    275:     {
1.158     raeburn   276:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    277:                '/filetypes.tab';
1.1075.2.128  raeburn   278:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  279:             while (my $line = <$fh>) {
                    280: 		next if ($line =~ /^\#/);
                    281: 		chomp($line);
                    282:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   283:                 if ($descr ne '') {
                    284:                     $fe{$ending}=lc($emb);
                    285:                     $fd{$ending}=$descr;
1.351     www       286:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   287:                 }
                    288:             }
                    289:             close($fh);
                    290:         }
1.12      harris41  291:     }
1.22      www       292:     &Apache::lonnet::logthis(
1.705     tempelho  293:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       294:     $readit=1;
1.46      matthew   295:     }  # end of unless($readit) 
1.32      matthew   296:     
                    297: }
1.112     bowersj2  298: 
1.42      matthew   299: ###############################################################
                    300: ##           HTML and Javascript Helper Functions            ##
                    301: ###############################################################
                    302: 
                    303: =pod 
                    304: 
1.112     bowersj2  305: =head1 HTML and Javascript Functions
1.42      matthew   306: 
1.112     bowersj2  307: =over 4
                    308: 
1.648     raeburn   309: =item * &browser_and_searcher_javascript()
1.112     bowersj2  310: 
                    311: X<browsing, javascript>X<searching, javascript>Returns a string
                    312: containing javascript with two functions, C<openbrowser> and
                    313: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    314: tags.
1.42      matthew   315: 
1.648     raeburn   316: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   317: 
                    318: inputs: formname, elementname, only, omit
                    319: 
                    320: formname and elementname indicate the name of the html form and name of
                    321: the element that the results of the browsing selection are to be placed in. 
                    322: 
                    323: Specifying 'only' will restrict the browser to displaying only files
1.185     www       324: with the given extension.  Can be a comma separated list.
1.42      matthew   325: 
                    326: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       327: with the given extension.  Can be a comma separated list.
1.42      matthew   328: 
1.648     raeburn   329: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   330: 
                    331: Inputs: formname, elementname
                    332: 
                    333: formname and elementname specify the name of the html form and the name
                    334: of the element the selection from the search results will be placed in.
1.542     raeburn   335: 
1.42      matthew   336: =cut
                    337: 
                    338: sub browser_and_searcher_javascript {
1.199     albertel  339:     my ($mode)=@_;
                    340:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  341:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   342:     return <<END;
1.219     albertel  343: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   344:     var editbrowser = null;
1.135     albertel  345:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       346:         var url = '$resurl/?';
1.42      matthew   347:         if (editbrowser == null) {
                    348:             url += 'launch=1&';
                    349:         }
                    350:         url += 'catalogmode=interactive&';
1.199     albertel  351:         url += 'mode=$mode&';
1.611     albertel  352:         url += 'inhibitmenu=yes&';
1.42      matthew   353:         url += 'form=' + formname + '&';
                    354:         if (only != null) {
                    355:             url += 'only=' + only + '&';
1.217     albertel  356:         } else {
                    357:             url += 'only=&';
                    358: 	}
1.42      matthew   359:         if (omit != null) {
                    360:             url += 'omit=' + omit + '&';
1.217     albertel  361:         } else {
                    362:             url += 'omit=&';
                    363: 	}
1.135     albertel  364:         if (titleelement != null) {
                    365:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  366:         } else {
                    367: 	    url += 'titleelement=&';
                    368: 	}
1.42      matthew   369:         url += 'element=' + elementname + '';
                    370:         var title = 'Browser';
1.435     albertel  371:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   372:         options += ',width=700,height=600';
                    373:         editbrowser = open(url,title,options,'1');
                    374:         editbrowser.focus();
                    375:     }
                    376:     var editsearcher;
1.135     albertel  377:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   378:         var url = '/adm/searchcat?';
                    379:         if (editsearcher == null) {
                    380:             url += 'launch=1&';
                    381:         }
                    382:         url += 'catalogmode=interactive&';
1.199     albertel  383:         url += 'mode=$mode&';
1.42      matthew   384:         url += 'form=' + formname + '&';
1.135     albertel  385:         if (titleelement != null) {
                    386:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  387:         } else {
                    388: 	    url += 'titleelement=&';
                    389: 	}
1.42      matthew   390:         url += 'element=' + elementname + '';
                    391:         var title = 'Search';
1.435     albertel  392:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   393:         options += ',width=700,height=600';
                    394:         editsearcher = open(url,title,options,'1');
                    395:         editsearcher.focus();
                    396:     }
1.219     albertel  397: // END LON-CAPA Internal -->
1.42      matthew   398: END
1.170     www       399: }
                    400: 
                    401: sub lastresurl {
1.258     albertel  402:     if ($env{'environment.lastresurl'}) {
                    403: 	return $env{'environment.lastresurl'}
1.170     www       404:     } else {
                    405: 	return '/res';
                    406:     }
                    407: }
                    408: 
                    409: sub storeresurl {
                    410:     my $resurl=&Apache::lonnet::clutter(shift);
                    411:     unless ($resurl=~/^\/res/) { return 0; }
                    412:     $resurl=~s/\/$//;
                    413:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   414:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       415:     return 1;
1.42      matthew   416: }
                    417: 
1.74      www       418: sub studentbrowser_javascript {
1.111     www       419:    unless (
1.258     albertel  420:             (($env{'request.course.id'}) && 
1.302     albertel  421:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    422: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    423: 					  '/'.$env{'request.course.sec'})
                    424: 	      ))
1.258     albertel  425:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       426:           ) { return ''; }  
1.74      www       427:    return (<<'ENDSTDBRW');
1.776     bisitz    428: <script type="text/javascript" language="Javascript">
1.824     bisitz    429: // <![CDATA[
1.74      www       430:     var stdeditbrowser;
1.1075.2.143  raeburn   431:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
1.74      www       432:         var url = '/adm/pickstudent?';
                    433:         var filter;
1.558     albertel  434: 	if (!ignorefilter) {
                    435: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    436: 	}
1.74      www       437:         if (filter != null) {
                    438:            if (filter != '') {
                    439:                url += 'filter='+filter+'&';
                    440: 	   }
                    441:         }
                    442:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       443:                                     '&udomelement='+udom+
                    444:                                     '&clicker='+clicker;
1.111     www       445: 	if (roleflag) { url+="&roles=1"; }
1.1075.2.143  raeburn   446:         if (courseadv == 'condition') {
                    447:             if (document.getElementById('courseadv')) {
                    448:                 courseadv = document.getElementById('courseadv').value;
                    449:             }
                    450:         }
                    451:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       452:         var title = 'Student_Browser';
1.74      www       453:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    454:         options += ',width=700,height=600';
                    455:         stdeditbrowser = open(url,title,options,'1');
                    456:         stdeditbrowser.focus();
                    457:     }
1.824     bisitz    458: // ]]>
1.74      www       459: </script>
                    460: ENDSTDBRW
                    461: }
1.42      matthew   462: 
1.1003    www       463: sub resourcebrowser_javascript {
                    464:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       465:    return (<<'ENDRESBRW');
1.1003    www       466: <script type="text/javascript" language="Javascript">
                    467: // <![CDATA[
                    468:     var reseditbrowser;
1.1004    www       469:     function openresbrowser(formname,reslink) {
1.1005    www       470:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       471:         var title = 'Resource_Browser';
                    472:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       473:         options += ',width=700,height=500';
1.1004    www       474:         reseditbrowser = open(url,title,options,'1');
                    475:         reseditbrowser.focus();
1.1003    www       476:     }
                    477: // ]]>
                    478: </script>
1.1004    www       479: ENDRESBRW
1.1003    www       480: }
                    481: 
1.74      www       482: sub selectstudent_link {
1.1075.2.143  raeburn   483:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       484:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    485:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    486:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  487:    if ($env{'request.course.id'}) {  
1.302     albertel  488:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    489: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    490: 					'/'.$env{'request.course.sec'})) {
1.111     www       491: 	   return '';
                    492:        }
1.999     www       493:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1075.2.143  raeburn   494:        if ($courseadv eq 'only') {
                    495:            $callargs .= ",'',1,'$courseadv'";
                    496:        } elsif ($courseadv eq 'none') {
                    497:            $callargs .= ",'','','$courseadv'";
                    498:        } elsif ($courseadv eq 'condition') {
                    499:            $callargs .= ",'','','$courseadv'";
1.793     raeburn   500:        }
                    501:        return '<span class="LC_nobreak">'.
                    502:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    503:               &mt('Select User').'</a></span>';
1.74      www       504:    }
1.258     albertel  505:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       506:        $callargs .= ",'',1"; 
1.793     raeburn   507:        return '<span class="LC_nobreak">'.
                    508:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    509:               &mt('Select User').'</a></span>';
1.111     www       510:    }
                    511:    return '';
1.91      www       512: }
                    513: 
1.1004    www       514: sub selectresource_link {
                    515:    my ($form,$reslink,$arg)=@_;
                    516:    
                    517:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    518:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    519:    unless ($env{'request.course.id'}) { return $arg; }
                    520:    return '<span class="LC_nobreak">'.
                    521:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    522:               $arg.'</a></span>';
                    523: }
                    524: 
                    525: 
                    526: 
1.653     raeburn   527: sub authorbrowser_javascript {
                    528:     return <<"ENDAUTHORBRW";
1.776     bisitz    529: <script type="text/javascript" language="JavaScript">
1.824     bisitz    530: // <![CDATA[
1.653     raeburn   531: var stdeditbrowser;
                    532: 
                    533: function openauthorbrowser(formname,udom) {
                    534:     var url = '/adm/pickauthor?';
                    535:     url += 'form='+formname+'&roledom='+udom;
                    536:     var title = 'Author_Browser';
                    537:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    538:     options += ',width=700,height=600';
                    539:     stdeditbrowser = open(url,title,options,'1');
                    540:     stdeditbrowser.focus();
                    541: }
                    542: 
1.824     bisitz    543: // ]]>
1.653     raeburn   544: </script>
                    545: ENDAUTHORBRW
                    546: }
                    547: 
1.91      www       548: sub coursebrowser_javascript {
1.1075.2.31  raeburn   549:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   550:         $credits_element,$instcode) = @_;
1.932     raeburn   551:     my $wintitle = 'Course_Browser';
1.931     raeburn   552:     if ($crstype eq 'Community') {
1.932     raeburn   553:         $wintitle = 'Community_Browser';
1.909     raeburn   554:     }
1.876     raeburn   555:     my $id_functions = &javascript_index_functions();
                    556:     my $output = '
1.776     bisitz    557: <script type="text/javascript" language="JavaScript">
1.824     bisitz    558: // <![CDATA[
1.468     raeburn   559:     var stdeditbrowser;'."\n";
1.876     raeburn   560: 
                    561:     $output .= <<"ENDSTDBRW";
1.909     raeburn   562:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       563:         var url = '/adm/pickcourse?';
1.895     raeburn   564:         var formid = getFormIdByName(formname);
1.876     raeburn   565:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  566:         if (domainfilter != null) {
                    567:            if (domainfilter != '') {
                    568:                url += 'domainfilter='+domainfilter+'&';
                    569: 	   }
                    570:         }
1.91      www       571:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  572: 	                            '&cdomelement='+udom+
                    573:                                     '&cnameelement='+desc;
1.468     raeburn   574:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   575:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   576:                 url += '&roleelement='+extra_element;
                    577:                 if (domainfilter == null || domainfilter == '') {
                    578:                     url += '&domainfilter='+extra_element;
                    579:                 }
1.234     raeburn   580:             }
1.468     raeburn   581:             else {
                    582:                 if (formname == 'portform') {
                    583:                     url += '&setroles='+extra_element;
1.800     raeburn   584:                 } else {
                    585:                     if (formname == 'rules') {
                    586:                         url += '&fixeddom='+extra_element; 
                    587:                     }
1.468     raeburn   588:                 }
                    589:             }     
1.230     raeburn   590:         }
1.909     raeburn   591:         if (type != null && type != '') {
                    592:             url += '&type='+type;
                    593:         }
                    594:         if (type_elem != null && type_elem != '') {
                    595:             url += '&typeelement='+type_elem;
                    596:         }
1.872     raeburn   597:         if (formname == 'ccrs') {
                    598:             var ownername = document.forms[formid].ccuname.value;
                    599:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   600:             url += '&cloner='+ownername+':'+ownerdom;
                    601:             if (type == 'Course') {
                    602:                 url += '&crscode='+document.forms[formid].crscode.value;
                    603:             }
1.1075.2.95  raeburn   604:         }
                    605:         if (formname == 'requestcrs') {
                    606:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   607:         }
1.293     raeburn   608:         if (multflag !=null && multflag != '') {
                    609:             url += '&multiple='+multflag;
                    610:         }
1.909     raeburn   611:         var title = '$wintitle';
1.91      www       612:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    613:         options += ',width=700,height=600';
                    614:         stdeditbrowser = open(url,title,options,'1');
                    615:         stdeditbrowser.focus();
                    616:     }
1.876     raeburn   617: $id_functions
                    618: ENDSTDBRW
1.1075.2.31  raeburn   619:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    620:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    621:                                       $credits_element);
1.876     raeburn   622:     }
                    623:     $output .= '
                    624: // ]]>
                    625: </script>';
                    626:     return $output;
                    627: }
                    628: 
                    629: sub javascript_index_functions {
                    630:     return <<"ENDJS";
                    631: 
                    632: function getFormIdByName(formname) {
                    633:     for (var i=0;i<document.forms.length;i++) {
                    634:         if (document.forms[i].name == formname) {
                    635:             return i;
                    636:         }
                    637:     }
                    638:     return -1;
                    639: }
                    640: 
                    641: function getIndexByName(formid,item) {
                    642:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    643:         if (document.forms[formid].elements[i].name == item) {
                    644:             return i;
                    645:         }
                    646:     }
                    647:     return -1;
                    648: }
1.468     raeburn   649: 
1.876     raeburn   650: function getDomainFromSelectbox(formname,udom) {
                    651:     var userdom;
                    652:     var formid = getFormIdByName(formname);
                    653:     if (formid > -1) {
                    654:         var domid = getIndexByName(formid,udom);
                    655:         if (domid > -1) {
                    656:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    657:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    658:             }
                    659:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    660:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   661:             }
                    662:         }
                    663:     }
1.876     raeburn   664:     return userdom;
                    665: }
                    666: 
                    667: ENDJS
1.468     raeburn   668: 
1.876     raeburn   669: }
                    670: 
1.1017    raeburn   671: sub javascript_array_indexof {
1.1018    raeburn   672:     return <<ENDJS;
1.1017    raeburn   673: <script type="text/javascript" language="JavaScript">
                    674: // <![CDATA[
                    675: 
                    676: if (!Array.prototype.indexOf) {
                    677:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    678:         "use strict";
                    679:         if (this === void 0 || this === null) {
                    680:             throw new TypeError();
                    681:         }
                    682:         var t = Object(this);
                    683:         var len = t.length >>> 0;
                    684:         if (len === 0) {
                    685:             return -1;
                    686:         }
                    687:         var n = 0;
                    688:         if (arguments.length > 0) {
                    689:             n = Number(arguments[1]);
                    690:             if (n !== n) { // shortcut for verifying if it's NaN
                    691:                 n = 0;
                    692:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    693:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    694:             }
                    695:         }
                    696:         if (n >= len) {
                    697:             return -1;
                    698:         }
                    699:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    700:         for (; k < len; k++) {
                    701:             if (k in t && t[k] === searchElement) {
                    702:                 return k;
                    703:             }
                    704:         }
                    705:         return -1;
                    706:     }
                    707: }
                    708: 
                    709: // ]]>
                    710: </script>
                    711: 
                    712: ENDJS
                    713: 
                    714: }
                    715: 
1.876     raeburn   716: sub userbrowser_javascript {
                    717:     my $id_functions = &javascript_index_functions();
                    718:     return <<"ENDUSERBRW";
                    719: 
1.888     raeburn   720: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   721:     var url = '/adm/pickuser?';
                    722:     var userdom = getDomainFromSelectbox(formname,udom);
                    723:     if (userdom != null) {
                    724:        if (userdom != '') {
                    725:            url += 'srchdom='+userdom+'&';
                    726:        }
                    727:     }
                    728:     url += 'form=' + formname + '&unameelement='+uname+
                    729:                                 '&udomelement='+udom+
                    730:                                 '&ulastelement='+ulast+
                    731:                                 '&ufirstelement='+ufirst+
                    732:                                 '&uemailelement='+uemail+
1.881     raeburn   733:                                 '&hideudomelement='+hideudom+
                    734:                                 '&coursedom='+crsdom;
1.888     raeburn   735:     if ((caller != null) && (caller != undefined)) {
                    736:         url += '&caller='+caller;
                    737:     }
1.876     raeburn   738:     var title = 'User_Browser';
                    739:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    740:     options += ',width=700,height=600';
                    741:     var stdeditbrowser = open(url,title,options,'1');
                    742:     stdeditbrowser.focus();
                    743: }
                    744: 
1.888     raeburn   745: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   746:     var formid = getFormIdByName(formname);
                    747:     if (formid > -1) {
1.888     raeburn   748:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   749:         var domid = getIndexByName(formid,udom);
                    750:         var hidedomid = getIndexByName(formid,origdom);
                    751:         if (hidedomid > -1) {
                    752:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   753:             var unameval = document.forms[formid].elements[unameid].value;
                    754:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    755:                 if (domid > -1) {
                    756:                     var slct = document.forms[formid].elements[domid];
                    757:                     if (slct.type == 'select-one') {
                    758:                         var i;
                    759:                         for (i=0;i<slct.length;i++) {
                    760:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    761:                         }
                    762:                     }
                    763:                     if (slct.type == 'hidden') {
                    764:                         slct.value = fixeddom;
1.876     raeburn   765:                     }
                    766:                 }
1.468     raeburn   767:             }
                    768:         }
                    769:     }
1.876     raeburn   770:     return;
                    771: }
                    772: 
                    773: $id_functions
                    774: ENDUSERBRW
1.468     raeburn   775: }
                    776: 
                    777: sub setsec_javascript {
1.1075.2.31  raeburn   778:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   779:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    780:         $communityrolestr);
                    781:     if ($role_element ne '') {
                    782:         my @allroles = ('st','ta','ep','in','ad');
                    783:         foreach my $crstype ('Course','Community') {
                    784:             if ($crstype eq 'Community') {
                    785:                 foreach my $role (@allroles) {
                    786:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    787:                 }
                    788:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    789:             } else {
                    790:                 foreach my $role (@allroles) {
                    791:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    792:                 }
                    793:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    794:             }
                    795:         }
                    796:         $rolestr = '"'.join('","',@allroles).'"';
                    797:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    798:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    799:     }
1.468     raeburn   800:     my $setsections = qq|
                    801: function setSect(sectionlist) {
1.629     raeburn   802:     var sectionsArray = new Array();
                    803:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    804:         sectionsArray = sectionlist.split(",");
                    805:     }
1.468     raeburn   806:     var numSections = sectionsArray.length;
                    807:     document.$formname.$sec_element.length = 0;
                    808:     if (numSections == 0) {
                    809:         document.$formname.$sec_element.multiple=false;
                    810:         document.$formname.$sec_element.size=1;
                    811:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    812:     } else {
                    813:         if (numSections == 1) {
                    814:             document.$formname.$sec_element.multiple=false;
                    815:             document.$formname.$sec_element.size=1;
                    816:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    817:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    818:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    819:         } else {
                    820:             for (var i=0; i<numSections; i++) {
                    821:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    822:             }
                    823:             document.$formname.$sec_element.multiple=true
                    824:             if (numSections < 3) {
                    825:                 document.$formname.$sec_element.size=numSections;
                    826:             } else {
                    827:                 document.$formname.$sec_element.size=3;
                    828:             }
                    829:             document.$formname.$sec_element.options[0].selected = false
                    830:         }
                    831:     }
1.91      www       832: }
1.905     raeburn   833: 
                    834: function setRole(crstype) {
1.468     raeburn   835: |;
1.905     raeburn   836:     if ($role_element eq '') {
                    837:         $setsections .= '    return;
                    838: }
                    839: ';
                    840:     } else {
                    841:         $setsections .= qq|
                    842:     var elementLength = document.$formname.$role_element.length;
                    843:     var allroles = Array($rolestr);
                    844:     var courserolenames = Array($courserolestr);
                    845:     var communityrolenames = Array($communityrolestr);
                    846:     if (elementLength != undefined) {
                    847:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    848:             if (crstype == 'Course') {
                    849:                 return;
                    850:             } else {
                    851:                 allroles[5] = 'co';
                    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 = communityrolenames[i];
                    855:                 }
                    856:             }
                    857:         } else {
                    858:             if (crstype == 'Community') {
                    859:                 return;
                    860:             } else {
                    861:                 allroles[5] = 'cc';
                    862:                 for (var i=0; i<6; i++) {
                    863:                     document.$formname.$role_element.options[i].value = allroles[i];
                    864:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    865:                 }
                    866:             }
                    867:         }
                    868:     }
                    869:     return;
                    870: }
                    871: |;
                    872:     }
1.1075.2.31  raeburn   873:     if ($credits_element) {
                    874:         $setsections .= qq|
                    875: function setCredits(defaultcredits) {
                    876:     document.$formname.$credits_element.value = defaultcredits;
                    877:     return;
                    878: }
                    879: |;
                    880:     }
1.468     raeburn   881:     return $setsections;
                    882: }
                    883: 
1.91      www       884: sub selectcourse_link {
1.909     raeburn   885:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    886:        $typeelement) = @_;
                    887:    my $type = $selecttype;
1.871     raeburn   888:    my $linktext = &mt('Select Course');
                    889:    if ($selecttype eq 'Community') {
1.909     raeburn   890:        $linktext = &mt('Select Community');
1.906     raeburn   891:    } elsif ($selecttype eq 'Course/Community') {
                    892:        $linktext = &mt('Select Course/Community');
1.909     raeburn   893:        $type = '';
1.1019    raeburn   894:    } elsif ($selecttype eq 'Select') {
                    895:        $linktext = &mt('Select');
                    896:        $type = '';
1.871     raeburn   897:    }
1.787     bisitz    898:    return '<span class="LC_nobreak">'
                    899:          ."<a href='"
                    900:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    901:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   902:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   903:          ."'>".$linktext.'</a>'
1.787     bisitz    904:          .'</span>';
1.74      www       905: }
1.42      matthew   906: 
1.653     raeburn   907: sub selectauthor_link {
                    908:    my ($form,$udom)=@_;
                    909:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    910:           &mt('Select Author').'</a>';
                    911: }
                    912: 
1.876     raeburn   913: sub selectuser_link {
1.881     raeburn   914:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   915:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   916:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   917:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   918:            ');">'.$linktext.'</a>';
1.876     raeburn   919: }
                    920: 
1.273     raeburn   921: sub check_uncheck_jscript {
                    922:     my $jscript = <<"ENDSCRT";
                    923: function checkAll(field) {
                    924:     if (field.length > 0) {
                    925:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   926:             if (!field[i].disabled) {
                    927:                 field[i].checked = true;
                    928:             }
1.273     raeburn   929:         }
                    930:     } else {
1.1075.2.14  raeburn   931:         if (!field.disabled) {
                    932:             field.checked = true;
                    933:         }
1.273     raeburn   934:     }
                    935: }
                    936:  
                    937: function uncheckAll(field) {
                    938:     if (field.length > 0) {
                    939:         for (i = 0; i < field.length; i++) {
                    940:             field[i].checked = false ;
1.543     albertel  941:         }
                    942:     } else {
1.273     raeburn   943:         field.checked = false ;
                    944:     }
                    945: }
                    946: ENDSCRT
                    947:     return $jscript;
                    948: }
                    949: 
1.656     www       950: sub select_timezone {
1.1075.2.115  raeburn   951:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    952:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   953:    if ($includeempty) {
                    954:        $output .= '<option value=""';
                    955:        if (($selected eq '') || ($selected eq 'local')) {
                    956:            $output .= ' selected="selected" ';
                    957:        }
                    958:        $output .= '> </option>';
                    959:    }
1.657     raeburn   960:    my @timezones = DateTime::TimeZone->all_names;
                    961:    foreach my $tzone (@timezones) {
                    962:        $output.= '<option value="'.$tzone.'"';
                    963:        if ($tzone eq $selected) {
                    964:            $output.=' selected="selected"';
                    965:        }
                    966:        $output.=">$tzone</option>\n";
1.656     www       967:    }
                    968:    $output.="</select>";
                    969:    return $output;
                    970: }
1.273     raeburn   971: 
1.687     raeburn   972: sub select_datelocale {
1.1075.2.115  raeburn   973:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    974:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   975:     if ($includeempty) {
                    976:         $output .= '<option value=""';
                    977:         if ($selected eq '') {
                    978:             $output .= ' selected="selected" ';
                    979:         }
                    980:         $output .= '> </option>';
                    981:     }
1.1075.2.102  raeburn   982:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   983:     my (@possibles,%locale_names);
1.1075.2.102  raeburn   984:     my @locales = DateTime::Locale->ids();
                    985:     foreach my $id (@locales) {
                    986:         if ($id ne '') {
                    987:             my ($en_terr,$native_terr);
                    988:             my $loc = DateTime::Locale->load($id);
                    989:             if (ref($loc)) {
                    990:                 $en_terr = $loc->name();
                    991:                 $native_terr = $loc->native_name();
1.687     raeburn   992:                 if (grep(/^en$/,@languages) || !@languages) {
                    993:                     if ($en_terr ne '') {
                    994:                         $locale_names{$id} = '('.$en_terr.')';
                    995:                     } elsif ($native_terr ne '') {
                    996:                         $locale_names{$id} = $native_terr;
                    997:                     }
                    998:                 } else {
                    999:                     if ($native_terr ne '') {
                   1000:                         $locale_names{$id} = $native_terr.' ';
                   1001:                     } elsif ($en_terr ne '') {
                   1002:                         $locale_names{$id} = '('.$en_terr.')';
                   1003:                     }
                   1004:                 }
1.1075.2.94  raeburn  1005:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1075.2.102  raeburn  1006:                 push(@possibles,$id);
1.687     raeburn  1007:             }
                   1008:         }
                   1009:     }
                   1010:     foreach my $item (sort(@possibles)) {
                   1011:         $output.= '<option value="'.$item.'"';
                   1012:         if ($item eq $selected) {
                   1013:             $output.=' selected="selected"';
                   1014:         }
                   1015:         $output.=">$item";
                   1016:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn  1017:             $output.='  '.$locale_names{$item};
1.687     raeburn  1018:         }
                   1019:         $output.="</option>\n";
                   1020:     }
                   1021:     $output.="</select>";
                   1022:     return $output;
                   1023: }
                   1024: 
1.792     raeburn  1025: sub select_language {
1.1075.2.115  raeburn  1026:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1027:     my %langchoices;
                   1028:     if ($includeempty) {
1.1075.2.32  raeburn  1029:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1030:     }
                   1031:     foreach my $id (&languageids()) {
                   1032:         my $code = &supportedlanguagecode($id);
                   1033:         if ($code) {
                   1034:             $langchoices{$code} = &plainlanguagedescription($id);
                   1035:         }
                   1036:     }
1.1075.2.32  raeburn  1037:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1075.2.115  raeburn  1038:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1039: }
                   1040: 
1.42      matthew  1041: =pod
1.36      matthew  1042: 
1.648     raeburn  1043: =item * &linked_select_forms(...)
1.36      matthew  1044: 
                   1045: linked_select_forms returns a string containing a <script></script> block
                   1046: and html for two <select> menus.  The select menus will be linked in that
                   1047: changing the value of the first menu will result in new values being placed
                   1048: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1049: order unless a defined order is provided.
1.36      matthew  1050: 
                   1051: linked_select_forms takes the following ordered inputs:
                   1052: 
                   1053: =over 4
                   1054: 
1.112     bowersj2 1055: =item * $formname, the name of the <form> tag
1.36      matthew  1056: 
1.112     bowersj2 1057: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1058: 
1.112     bowersj2 1059: =item * $firstdefault, the default value for the first menu
1.36      matthew  1060: 
1.112     bowersj2 1061: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1062: 
1.112     bowersj2 1063: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1064: 
1.112     bowersj2 1065: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1066: 
1.609     raeburn  1067: =item * $menuorder, the order of values in the first menu
                   1068: 
1.1075.2.31  raeburn  1069: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1070:         event for the first <select> tag
                   1071: 
                   1072: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1073:         event for the second <select> tag
                   1074: 
1.41      ng       1075: =back 
                   1076: 
1.36      matthew  1077: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1078: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1079: values for the first select menu.  The text that coincides with the 
1.41      ng       1080: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1081: and text for the second menu are given in the hash pointed to by 
                   1082: $menu{$choice1}->{'select2'}.  
                   1083: 
1.112     bowersj2 1084:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1085:                        default => "B3",
                   1086:                        select2 => { 
                   1087:                            B1 => "Choice B1",
                   1088:                            B2 => "Choice B2",
                   1089:                            B3 => "Choice B3",
                   1090:                            B4 => "Choice B4"
1.609     raeburn  1091:                            },
                   1092:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1093:                    },
                   1094:                A2 => { text =>"Choice A2" ,
                   1095:                        default => "C2",
                   1096:                        select2 => { 
                   1097:                            C1 => "Choice C1",
                   1098:                            C2 => "Choice C2",
                   1099:                            C3 => "Choice C3"
1.609     raeburn  1100:                            },
                   1101:                        order => ['C2','C1','C3'],
1.112     bowersj2 1102:                    },
                   1103:                A3 => { text =>"Choice A3" ,
                   1104:                        default => "D6",
                   1105:                        select2 => { 
                   1106:                            D1 => "Choice D1",
                   1107:                            D2 => "Choice D2",
                   1108:                            D3 => "Choice D3",
                   1109:                            D4 => "Choice D4",
                   1110:                            D5 => "Choice D5",
                   1111:                            D6 => "Choice D6",
                   1112:                            D7 => "Choice D7"
1.609     raeburn  1113:                            },
                   1114:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1115:                    }
                   1116:                );
1.36      matthew  1117: 
                   1118: =cut
                   1119: 
                   1120: sub linked_select_forms {
                   1121:     my ($formname,
                   1122:         $middletext,
                   1123:         $firstdefault,
                   1124:         $firstselectname,
                   1125:         $secondselectname, 
1.609     raeburn  1126:         $hashref,
                   1127:         $menuorder,
1.1075.2.31  raeburn  1128:         $onchangefirst,
                   1129:         $onchangesecond
1.36      matthew  1130:         ) = @_;
                   1131:     my $second = "document.$formname.$secondselectname";
                   1132:     my $first = "document.$formname.$firstselectname";
                   1133:     # output the javascript to do the changing
                   1134:     my $result = '';
1.776     bisitz   1135:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1136:     $result.="// <![CDATA[\n";
1.36      matthew  1137:     $result.="var select2data = new Object();\n";
                   1138:     $" = '","';
                   1139:     my $debug = '';
                   1140:     foreach my $s1 (sort(keys(%$hashref))) {
                   1141:         $result.="select2data.d_$s1 = new Object();\n";        
                   1142:         $result.="select2data.d_$s1.def = new String('".
                   1143:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1144:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1145:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1146:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1147:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1148:         }
1.36      matthew  1149:         $result.="\"@s2values\");\n";
                   1150:         $result.="select2data.d_$s1.texts = new Array(";        
                   1151:         my @s2texts;
                   1152:         foreach my $value (@s2values) {
1.1075.2.119  raeburn  1153:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1154:         }
                   1155:         $result.="\"@s2texts\");\n";
                   1156:     }
                   1157:     $"=' ';
                   1158:     $result.= <<"END";
                   1159: 
                   1160: function select1_changed() {
                   1161:     // Determine new choice
                   1162:     var newvalue = "d_" + $first.value;
                   1163:     // update select2
                   1164:     var values     = select2data[newvalue].values;
                   1165:     var texts      = select2data[newvalue].texts;
                   1166:     var select2def = select2data[newvalue].def;
                   1167:     var i;
                   1168:     // out with the old
                   1169:     for (i = 0; i < $second.options.length; i++) {
                   1170:         $second.options[i] = null;
                   1171:     }
                   1172:     // in with the nuclear
                   1173:     for (i=0;i<values.length; i++) {
                   1174:         $second.options[i] = new Option(values[i]);
1.143     matthew  1175:         $second.options[i].value = values[i];
1.36      matthew  1176:         $second.options[i].text = texts[i];
                   1177:         if (values[i] == select2def) {
                   1178:             $second.options[i].selected = true;
                   1179:         }
                   1180:     }
                   1181: }
1.824     bisitz   1182: // ]]>
1.36      matthew  1183: </script>
                   1184: END
                   1185:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1186:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1187:     my @order = sort(keys(%{$hashref}));
                   1188:     if (ref($menuorder) eq 'ARRAY') {
                   1189:         @order = @{$menuorder};
                   1190:     }
                   1191:     foreach my $value (@order) {
1.36      matthew  1192:         $result.="    <option value=\"$value\" ";
1.253     albertel 1193:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1194:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1195:     }
                   1196:     $result .= "</select>\n";
                   1197:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1198:     $result .= $middletext;
1.1075.2.31  raeburn  1199:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1200:     if ($onchangesecond) {
                   1201:         $result .= ' onchange="'.$onchangesecond.'"';
                   1202:     }
                   1203:     $result .= ">\n";
1.36      matthew  1204:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1205:     
                   1206:     my @secondorder = sort(keys(%select2));
                   1207:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1208:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1209:     }
                   1210:     foreach my $value (@secondorder) {
1.36      matthew  1211:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1212:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1213:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1214:     }
                   1215:     $result .= "</select>\n";
                   1216:     #    return $debug;
                   1217:     return $result;
                   1218: }   #  end of sub linked_select_forms {
                   1219: 
1.45      matthew  1220: =pod
1.44      bowersj2 1221: 
1.973     raeburn  1222: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1223: 
1.112     bowersj2 1224: Returns a string corresponding to an HTML link to the given help
                   1225: $topic, where $topic corresponds to the name of a .tex file in
                   1226: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1227: spaces. 
                   1228: 
                   1229: $text will optionally be linked to the same topic, allowing you to
                   1230: link text in addition to the graphic. If you do not want to link
                   1231: text, but wish to specify one of the later parameters, pass an
                   1232: empty string. 
                   1233: 
                   1234: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1235: the link will not open a new window. If false, the link will open
                   1236: a new window using Javascript. (Default is false.) 
                   1237: 
                   1238: $width and $height are optional numerical parameters that will
                   1239: override the width and height of the popped up window, which may
1.973     raeburn  1240: be useful for certain help topics with big pictures included.
                   1241: 
                   1242: $imgid is the id of the img tag used for the help icon. This may be
                   1243: used in a javascript call to switch the image src.  See 
                   1244: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1245: 
                   1246: =cut
                   1247: 
                   1248: sub help_open_topic {
1.973     raeburn  1249:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1250:     $text = "" if (not defined $text);
1.44      bowersj2 1251:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1252:     $width = 500 if (not defined $width);
1.44      bowersj2 1253:     $height = 400 if (not defined $height);
                   1254:     my $filename = $topic;
                   1255:     $filename =~ s/ /_/g;
                   1256: 
1.48      bowersj2 1257:     my $template = "";
                   1258:     my $link;
1.572     banghart 1259:     
1.159     www      1260:     $topic=~s/\W/\_/g;
1.44      bowersj2 1261: 
1.572     banghart 1262:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1263:         if ($env{'browser.mobile'}) {
                   1264: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1265:         } else {
                   1266:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1267:         }
1.1037    www      1268:     } elsif ($stayOnPage eq 'popup') {
                   1269:         $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 1270:     } else {
1.48      bowersj2 1271: 	$link = "/adm/help/${filename}.hlp";
                   1272:     }
                   1273: 
                   1274:     # Add the text
1.755     neumanie 1275:     if ($text ne "") {	
1.763     bisitz   1276: 	$template.='<span class="LC_help_open_topic">'
                   1277:                   .'<a target="_top" href="'.$link.'">'
                   1278:                   .$text.'</a>';
1.48      bowersj2 1279:     }
                   1280: 
1.763     bisitz   1281:     # (Always) Add the graphic
1.179     matthew  1282:     my $title = &mt('Online Help');
1.667     raeburn  1283:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1284:     if ($imgid ne '') {
                   1285:         $imgid = ' id="'.$imgid.'"';
                   1286:     }
1.763     bisitz   1287:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1288:               .'<img src="'.$helpicon.'" border="0"'
                   1289:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1290:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1291:               .' /></a>';
                   1292:     if ($text ne "") {	
                   1293:         $template.='</span>';
                   1294:     }
1.44      bowersj2 1295:     return $template;
                   1296: 
1.106     bowersj2 1297: }
                   1298: 
                   1299: # This is a quicky function for Latex cheatsheet editing, since it 
                   1300: # appears in at least four places
                   1301: sub helpLatexCheatsheet {
1.1037    www      1302:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1303:     my $out;
1.106     bowersj2 1304:     my $addOther = '';
1.732     raeburn  1305:     if ($topic) {
1.1037    www      1306: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1307:     }
                   1308:     $out = '<span>' # Start cheatsheet
                   1309: 	  .$addOther
                   1310:           .'<span>'
1.1037    www      1311: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1312: 	  .'</span> <span>'
1.1037    www      1313: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1314: 	  .'</span>';
1.732     raeburn  1315:     unless ($not_author) {
1.763     bisitz   1316:         $out .= ' <span>'
1.1037    www      1317: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1318: 	       .'</span> <span>'
1.1075.2.78  raeburn  1319:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1320:                .'</span>';
1.732     raeburn  1321:     }
1.763     bisitz   1322:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1323:     return $out;
1.172     www      1324: }
                   1325: 
1.430     albertel 1326: sub general_help {
                   1327:     my $helptopic='Student_Intro';
                   1328:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1329: 	$helptopic='Authoring_Intro';
1.907     raeburn  1330:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1331: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1332:     } elsif ($env{'request.role'}=~/^dc/) {
                   1333:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1334:     }
                   1335:     return $helptopic;
                   1336: }
                   1337: 
                   1338: sub update_help_link {
                   1339:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1340:     my $origurl = $ENV{'REQUEST_URI'};
                   1341:     $origurl=~s|^/~|/priv/|;
                   1342:     my $timestamp = time;
                   1343:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1344:         $$datum = &escape($$datum);
                   1345:     }
                   1346: 
                   1347:     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";
                   1348:     my $output .= <<"ENDOUTPUT";
                   1349: <script type="text/javascript">
1.824     bisitz   1350: // <![CDATA[
1.430     albertel 1351: banner_link = '$banner_link';
1.824     bisitz   1352: // ]]>
1.430     albertel 1353: </script>
                   1354: ENDOUTPUT
                   1355:     return $output;
                   1356: }
                   1357: 
                   1358: # now just updates the help link and generates a blue icon
1.193     raeburn  1359: sub help_open_menu {
1.430     albertel 1360:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1361: 	= @_;    
1.949     droeschl 1362:     $stayOnPage = 1;
1.430     albertel 1363:     my $output;
                   1364:     if ($component_help) {
                   1365: 	if (!$text) {
                   1366: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1367: 				       $width,$height);
                   1368: 	} else {
                   1369: 	    my $help_text;
                   1370: 	    $help_text=&unescape($topic);
                   1371: 	    $output='<table><tr><td>'.
                   1372: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1373: 				 $width,$height).'</td></tr></table>';
                   1374: 	}
                   1375:     }
                   1376:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1377:     return $output.$banner_link;
                   1378: }
                   1379: 
                   1380: sub top_nav_help {
1.1075.2.158  raeburn  1381:     my ($text,$linkattr) = @_;
1.436     albertel 1382:     $text = &mt($text);
1.1075.2.60  raeburn  1383:     my $stay_on_page;
                   1384:     unless ($env{'environment.remote'} eq 'on') {
                   1385:         $stay_on_page = 1;
                   1386:     }
1.1075.2.61  raeburn  1387:     my ($link,$banner_link);
                   1388:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1389:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1390: 	                         : "javascript:helpMenu('open')";
                   1391:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1392:     }
1.201     raeburn  1393:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1394:     if ($link) {
                   1395:         return <<"END";
1.436     albertel 1396: $banner_link
1.1075.2.158  raeburn  1397: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1398: END
1.1075.2.61  raeburn  1399:     } else {
                   1400:         return '&nbsp;'.$text.'&nbsp;';
                   1401:     }
1.436     albertel 1402: }
                   1403: 
                   1404: sub help_menu_js {
1.1075.2.52  raeburn  1405:     my ($httphost) = @_;
1.949     droeschl 1406:     my $stayOnPage = 1;
1.436     albertel 1407:     my $width = 620;
                   1408:     my $height = 600;
1.430     albertel 1409:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1410:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1411:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1412:     my $start_page =
                   1413:         &Apache::loncommon::start_page('Help Menu', undef,
                   1414: 				       {'frameset'    => 1,
                   1415: 					'js_ready'    => 1,
1.1075.2.136  raeburn  1416:                                         'use_absolute' => $httphost,
1.331     albertel 1417: 					'add_entries' => {
                   1418: 					    'border' => '0',
1.579     raeburn  1419: 					    'rows'   => "110,*",},});
1.331     albertel 1420:     my $end_page =
                   1421:         &Apache::loncommon::end_page({'frameset' => 1,
                   1422: 				      'js_ready' => 1,});
                   1423: 
1.436     albertel 1424:     my $template .= <<"ENDTEMPLATE";
                   1425: <script type="text/javascript">
1.877     bisitz   1426: // <![CDATA[
1.253     albertel 1427: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1428: var banner_link = '';
1.243     raeburn  1429: function helpMenu(target) {
                   1430:     var caller = this;
                   1431:     if (target == 'open') {
                   1432:         var newWindow = null;
                   1433:         try {
1.262     albertel 1434:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1435:         }
                   1436:         catch(error) {
                   1437:             writeHelp(caller);
                   1438:             return;
                   1439:         }
                   1440:         if (newWindow) {
                   1441:             caller = newWindow;
                   1442:         }
1.193     raeburn  1443:     }
1.243     raeburn  1444:     writeHelp(caller);
                   1445:     return;
                   1446: }
                   1447: function writeHelp(caller) {
1.1075.2.61  raeburn  1448:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1449:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1450:     caller.document.close();
                   1451:     caller.focus();
1.193     raeburn  1452: }
1.877     bisitz   1453: // END LON-CAPA Internal -->
1.253     albertel 1454: // ]]>
1.436     albertel 1455: </script>
1.193     raeburn  1456: ENDTEMPLATE
                   1457:     return $template;
                   1458: }
                   1459: 
1.172     www      1460: sub help_open_bug {
                   1461:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1462:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1463:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1464:     $text = "" if (not defined $text);
                   1465: 	$stayOnPage=1;
1.184     albertel 1466:     $width = 600 if (not defined $width);
                   1467:     $height = 600 if (not defined $height);
1.172     www      1468: 
                   1469:     $topic=~s/\W+/\+/g;
                   1470:     my $link='';
                   1471:     my $template='';
1.379     albertel 1472:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1473: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1474:     if (!$stayOnPage)
                   1475:     {
                   1476: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1477:     }
                   1478:     else
                   1479:     {
                   1480: 	$link = $url;
                   1481:     }
                   1482:     # Add the text
                   1483:     if ($text ne "")
                   1484:     {
                   1485: 	$template .= 
                   1486:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1487:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1488:     }
                   1489: 
                   1490:     # Add the graphic
1.179     matthew  1491:     my $title = &mt('Report a Bug');
1.215     albertel 1492:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1493:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1494:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1495: ENDTEMPLATE
                   1496:     if ($text ne '') { $template.='</td></tr></table>' };
                   1497:     return $template;
                   1498: 
                   1499: }
                   1500: 
                   1501: sub help_open_faq {
                   1502:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1503:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1504:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1505:     $text = "" if (not defined $text);
                   1506: 	$stayOnPage=1;
                   1507:     $width = 350 if (not defined $width);
                   1508:     $height = 400 if (not defined $height);
                   1509: 
                   1510:     $topic=~s/\W+/\+/g;
                   1511:     my $link='';
                   1512:     my $template='';
                   1513:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1514:     if (!$stayOnPage)
                   1515:     {
                   1516: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1517:     }
                   1518:     else
                   1519:     {
                   1520: 	$link = $url;
                   1521:     }
                   1522: 
                   1523:     # Add the text
                   1524:     if ($text ne "")
                   1525:     {
                   1526: 	$template .= 
1.173     www      1527:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1528:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1529:     }
                   1530: 
                   1531:     # Add the graphic
1.179     matthew  1532:     my $title = &mt('View the FAQ');
1.215     albertel 1533:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1534:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1535:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1536: ENDTEMPLATE
                   1537:     if ($text ne '') { $template.='</td></tr></table>' };
                   1538:     return $template;
                   1539: 
1.44      bowersj2 1540: }
1.37      matthew  1541: 
1.180     matthew  1542: ###############################################################
                   1543: ###############################################################
                   1544: 
1.45      matthew  1545: =pod
                   1546: 
1.648     raeburn  1547: =item * &change_content_javascript():
1.256     matthew  1548: 
                   1549: This and the next function allow you to create small sections of an
                   1550: otherwise static HTML page that you can update on the fly with
                   1551: Javascript, even in Netscape 4.
                   1552: 
                   1553: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1554: must be written to the HTML page once. It will prove the Javascript
                   1555: function "change(name, content)". Calling the change function with the
                   1556: name of the section 
                   1557: you want to update, matching the name passed to C<changable_area>, and
                   1558: the new content you want to put in there, will put the content into
                   1559: that area.
                   1560: 
                   1561: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1562: to contain room for the original contents. You need to "make space"
                   1563: for whatever changes you wish to make, and be B<sure> to check your
                   1564: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1565: it's adequate for updating a one-line status display, but little more.
                   1566: This script will set the space to 100% width, so you only need to
                   1567: worry about height in Netscape 4.
                   1568: 
                   1569: Modern browsers are much less limiting, and if you can commit to the
                   1570: user not using Netscape 4, this feature may be used freely with
                   1571: pretty much any HTML.
                   1572: 
                   1573: =cut
                   1574: 
                   1575: sub change_content_javascript {
                   1576:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1577:     if ($env{'browser.type'} eq 'netscape' &&
                   1578: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1579: 	return (<<NETSCAPE4);
                   1580: 	function change(name, content) {
                   1581: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1582: 	    doc.open();
                   1583: 	    doc.write(content);
                   1584: 	    doc.close();
                   1585: 	}
                   1586: NETSCAPE4
                   1587:     } else {
                   1588: 	# Otherwise, we need to use semi-standards-compliant code
                   1589: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1590: 	# is really scary, and every useful browser supports it
                   1591: 	return (<<DOMBASED);
                   1592: 	function change(name, content) {
                   1593: 	    element = document.getElementById(name);
                   1594: 	    element.innerHTML = content;
                   1595: 	}
                   1596: DOMBASED
                   1597:     }
                   1598: }
                   1599: 
                   1600: =pod
                   1601: 
1.648     raeburn  1602: =item * &changable_area($name,$origContent):
1.256     matthew  1603: 
                   1604: This provides a "changable area" that can be modified on the fly via
                   1605: the Javascript code provided in C<change_content_javascript>. $name is
                   1606: the name you will use to reference the area later; do not repeat the
                   1607: same name on a given HTML page more then once. $origContent is what
                   1608: the area will originally contain, which can be left blank.
                   1609: 
                   1610: =cut
                   1611: 
                   1612: sub changable_area {
                   1613:     my ($name, $origContent) = @_;
                   1614: 
1.258     albertel 1615:     if ($env{'browser.type'} eq 'netscape' &&
                   1616: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1617: 	# If this is netscape 4, we need to use the Layer tag
                   1618: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1619:     } else {
                   1620: 	return "<span id='$name'>$origContent</span>";
                   1621:     }
                   1622: }
                   1623: 
                   1624: =pod
                   1625: 
1.648     raeburn  1626: =item * &viewport_geometry_js 
1.590     raeburn  1627: 
                   1628: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1629: 
                   1630: =cut
                   1631: 
                   1632: 
                   1633: sub viewport_geometry_js { 
                   1634:     return <<"GEOMETRY";
                   1635: var Geometry = {};
                   1636: function init_geometry() {
                   1637:     if (Geometry.init) { return };
                   1638:     Geometry.init=1;
                   1639:     if (window.innerHeight) {
                   1640:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1641:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1642:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1643:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1644:     }
                   1645:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1646:         Geometry.getViewportHeight =
                   1647:             function() { return document.documentElement.clientHeight; };
                   1648:         Geometry.getViewportWidth =
                   1649:             function() { return document.documentElement.clientWidth; };
                   1650: 
                   1651:         Geometry.getHorizontalScroll =
                   1652:             function() { return document.documentElement.scrollLeft; };
                   1653:         Geometry.getVerticalScroll =
                   1654:             function() { return document.documentElement.scrollTop; };
                   1655:     }
                   1656:     else if (document.body.clientHeight) {
                   1657:         Geometry.getViewportHeight =
                   1658:             function() { return document.body.clientHeight; };
                   1659:         Geometry.getViewportWidth =
                   1660:             function() { return document.body.clientWidth; };
                   1661:         Geometry.getHorizontalScroll =
                   1662:             function() { return document.body.scrollLeft; };
                   1663:         Geometry.getVerticalScroll =
                   1664:             function() { return document.body.scrollTop; };
                   1665:     }
                   1666: }
                   1667: 
                   1668: GEOMETRY
                   1669: }
                   1670: 
                   1671: =pod
                   1672: 
1.648     raeburn  1673: =item * &viewport_size_js()
1.590     raeburn  1674: 
                   1675: 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. 
                   1676: 
                   1677: =cut
                   1678: 
                   1679: sub viewport_size_js {
                   1680:     my $geometry = &viewport_geometry_js();
                   1681:     return <<"DIMS";
                   1682: 
                   1683: $geometry
                   1684: 
                   1685: function getViewportDims(width,height) {
                   1686:     init_geometry();
                   1687:     width.value = Geometry.getViewportWidth();
                   1688:     height.value = Geometry.getViewportHeight();
                   1689:     return;
                   1690: }
                   1691: 
                   1692: DIMS
                   1693: }
                   1694: 
                   1695: =pod
                   1696: 
1.648     raeburn  1697: =item * &resize_textarea_js()
1.565     albertel 1698: 
                   1699: emits the needed javascript to resize a textarea to be as big as possible
                   1700: 
                   1701: creates a function resize_textrea that takes two IDs first should be
                   1702: the id of the element to resize, second should be the id of a div that
                   1703: surrounds everything that comes after the textarea, this routine needs
                   1704: to be attached to the <body> for the onload and onresize events.
                   1705: 
1.648     raeburn  1706: =back
1.565     albertel 1707: 
                   1708: =cut
                   1709: 
                   1710: sub resize_textarea_js {
1.590     raeburn  1711:     my $geometry = &viewport_geometry_js();
1.565     albertel 1712:     return <<"RESIZE";
                   1713:     <script type="text/javascript">
1.824     bisitz   1714: // <![CDATA[
1.590     raeburn  1715: $geometry
1.565     albertel 1716: 
1.588     albertel 1717: function getX(element) {
                   1718:     var x = 0;
                   1719:     while (element) {
                   1720: 	x += element.offsetLeft;
                   1721: 	element = element.offsetParent;
                   1722:     }
                   1723:     return x;
                   1724: }
                   1725: function getY(element) {
                   1726:     var y = 0;
                   1727:     while (element) {
                   1728: 	y += element.offsetTop;
                   1729: 	element = element.offsetParent;
                   1730:     }
                   1731:     return y;
                   1732: }
                   1733: 
                   1734: 
1.565     albertel 1735: function resize_textarea(textarea_id,bottom_id) {
                   1736:     init_geometry();
                   1737:     var textarea        = document.getElementById(textarea_id);
                   1738:     //alert(textarea);
                   1739: 
1.588     albertel 1740:     var textarea_top    = getY(textarea);
1.565     albertel 1741:     var textarea_height = textarea.offsetHeight;
                   1742:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1743:     var bottom_top      = getY(bottom);
1.565     albertel 1744:     var bottom_height   = bottom.offsetHeight;
                   1745:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1746:     var fudge           = 23;
1.565     albertel 1747:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1748:     if (new_height < 300) {
                   1749: 	new_height = 300;
                   1750:     }
                   1751:     textarea.style.height=new_height+'px';
                   1752: }
1.824     bisitz   1753: // ]]>
1.565     albertel 1754: </script>
                   1755: RESIZE
                   1756: 
                   1757: }
                   1758: 
1.1075.2.112  raeburn  1759: sub colorfuleditor_js {
                   1760:     return <<"COLORFULEDIT"
                   1761: <script type="text/javascript">
                   1762: // <![CDATA[>
                   1763:     function fold_box(curDepth, lastresource){
                   1764: 
                   1765:     // we need a list because there can be several blocks you need to fold in one tag
                   1766:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1767:     // but there is only one folding button per tag
                   1768:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1769: 
                   1770:         if(block.item(0).style.display == 'none'){
                   1771: 
                   1772:             foldbutton.value = '@{[&mt("Hide")]}';
                   1773:             for (i = 0; i < block.length; i++){
                   1774:                 block.item(i).style.display = '';
                   1775:             }
                   1776:         }else{
                   1777: 
                   1778:             foldbutton.value = '@{[&mt("Show")]}';
                   1779:             for (i = 0; i < block.length; i++){
                   1780:                 // block.item(i).style.visibility = 'collapse';
                   1781:                 block.item(i).style.display = 'none';
                   1782:             }
                   1783:         };
                   1784:         saveState(lastresource);
                   1785:     }
                   1786: 
                   1787:     function saveState (lastresource) {
                   1788: 
                   1789:         var tag_list = getTagList();
                   1790:         if(tag_list != null){
                   1791:             var timestamp = new Date().getTime();
                   1792:             var key = lastresource;
                   1793: 
                   1794:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1795:             // starting with timestamp
                   1796:             var value = timestamp+';';
                   1797: 
                   1798:             // building the list of key-value pairs
                   1799:             for(var i = 0; i < tag_list.length; i++){
                   1800:                 value += tag_list[i]+',';
                   1801:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1802:             }
                   1803: 
                   1804:             // only iterate whole storage if nothing to override
                   1805:             if(localStorage.getItem(key) == null){
                   1806: 
                   1807:                 // prevent storage from growing large
                   1808:                 if(localStorage.length > 50){
                   1809:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1810:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1811:                     var oldest_key;
                   1812: 
                   1813:                     for(var i = 1; i < localStorage.length; i++){
                   1814:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1815:                             oldest_key = localStorage.key(i);
                   1816:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1817:                         }
                   1818:                     }
                   1819:                     localStorage.removeItem(oldest_key);
                   1820:                 }
                   1821:             }
                   1822:             localStorage.setItem(key,value);
                   1823:         }
                   1824:     }
                   1825: 
                   1826:     // restore folding status of blocks (on page load)
                   1827:     function restoreState (lastresource) {
                   1828:         if(localStorage.getItem(lastresource) != null){
                   1829:             var key = lastresource;
                   1830:             var value = localStorage.getItem(key);
                   1831:             var regex_delTimestamp = /^\d+;/;
                   1832: 
                   1833:             value.replace(regex_delTimestamp, '');
                   1834: 
                   1835:             var valueArr = value.split(';');
                   1836:             var pairs;
                   1837:             var elements;
                   1838:             for (var i = 0; i < valueArr.length; i++){
                   1839:                 pairs = valueArr[i].split(',');
                   1840:                 elements = document.getElementsByName(pairs[0]);
                   1841: 
                   1842:                 for (var j = 0; j < elements.length; j++){
                   1843:                     elements[j].style.display = pairs[1];
                   1844:                     if (pairs[1] == "none"){
                   1845:                         var regex_id = /([_\\d]+)\$/;
                   1846:                         regex_id.exec(pairs[0]);
                   1847:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1848:                     }
                   1849:                 }
                   1850:             }
                   1851:         }
                   1852:     }
                   1853: 
                   1854:     function getTagList () {
                   1855: 
                   1856:         var stringToSearch = document.lonhomework.innerHTML;
                   1857: 
                   1858:         var ret = new Array();
                   1859:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1860:         var tag_list = stringToSearch.match(regex_findBlock);
                   1861: 
                   1862:         if(tag_list != null){
                   1863:             for(var i = 0; i < tag_list.length; i++){
                   1864:                 ret.push(tag_list[i].replace(/"/, ''));
                   1865:             }
                   1866:         }
                   1867:         return ret;
                   1868:     }
                   1869: 
                   1870:     function saveScrollPosition (resource) {
                   1871:         var tag_list = getTagList();
                   1872: 
                   1873:         // we dont always want to jump to the first block
                   1874:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1875:         if(\$(window).scrollTop() > 170){
                   1876:             if(tag_list != null){
                   1877:                 var result;
                   1878:                 for(var i = 0; i < tag_list.length; i++){
                   1879:                     if(isElementInViewport(tag_list[i])){
                   1880:                         result += tag_list[i]+';';
                   1881:                     }
                   1882:                 }
                   1883:                 sessionStorage.setItem('anchor_'+resource, result);
                   1884:             }
                   1885:         } else {
                   1886:             // we dont need to save zero, just delete the item to leave everything tidy
                   1887:             sessionStorage.removeItem('anchor_'+resource);
                   1888:         }
                   1889:     }
                   1890: 
                   1891:     function restoreScrollPosition(resource){
                   1892: 
                   1893:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1894:         if(elem != null){
                   1895:             var tag_list = elem.split(';');
                   1896:             var elem_list;
                   1897: 
                   1898:             for(var i = 0; i < tag_list.length; i++){
                   1899:                 elem_list = document.getElementsByName(tag_list[i]);
                   1900: 
                   1901:                 if(elem_list.length > 0){
                   1902:                     elem = elem_list[0];
                   1903:                     break;
                   1904:                 }
                   1905:             }
                   1906:             elem.scrollIntoView();
                   1907:         }
                   1908:     }
                   1909: 
                   1910:     function isElementInViewport(el) {
                   1911: 
                   1912:         // change to last element instead of first
                   1913:         var elem = document.getElementsByName(el);
                   1914:         var rect = elem[0].getBoundingClientRect();
                   1915: 
                   1916:         return (
                   1917:             rect.top >= 0 &&
                   1918:             rect.left >= 0 &&
                   1919:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1920:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1921:         );
                   1922:     }
                   1923: 
                   1924:     function autosize(depth){
                   1925:         var cmInst = window['cm'+depth];
                   1926:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1927: 
                   1928:         // is fixed size, switching to dynamic
                   1929:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1930:             cmInst.setSize("","auto");
                   1931:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1932:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1933: 
                   1934:         // is dynamic size, switching to fixed
                   1935:         } else {
                   1936:             cmInst.setSize("","300px");
                   1937:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1938:             sessionStorage.removeItem("autosized_"+depth);
                   1939:         }
                   1940:     }
                   1941: 
                   1942: 
                   1943: 
                   1944: // ]]>
                   1945: </script>
                   1946: COLORFULEDIT
                   1947: }
                   1948: 
                   1949: sub xmleditor_js {
                   1950:     return <<XMLEDIT
                   1951: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1952: <script type="text/javascript">
                   1953: // <![CDATA[>
                   1954: 
                   1955:     function saveScrollPosition (resource) {
                   1956: 
                   1957:         var scrollPos = \$(window).scrollTop();
                   1958:         sessionStorage.setItem(resource,scrollPos);
                   1959:     }
                   1960: 
                   1961:     function restoreScrollPosition(resource){
                   1962: 
                   1963:         var scrollPos = sessionStorage.getItem(resource);
                   1964:         \$(window).scrollTop(scrollPos);
                   1965:     }
                   1966: 
                   1967:     // unless internet explorer
                   1968:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1969: 
                   1970:         \$(document).ready(function() {
                   1971:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1972:         });
                   1973:     }
                   1974: 
                   1975:     // inserts text at cursor position into codemirror (xml editor only)
                   1976:     function insertText(text){
                   1977:         cm.focus();
                   1978:         var curPos = cm.getCursor();
                   1979:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1980:     }
                   1981: // ]]>
                   1982: </script>
                   1983: XMLEDIT
                   1984: }
                   1985: 
                   1986: sub insert_folding_button {
                   1987:     my $curDepth = $Apache::lonxml::curdepth;
                   1988:     my $lastresource = $env{'request.ambiguous'};
                   1989: 
                   1990:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   1991:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   1992: }
                   1993: 
                   1994: 
1.565     albertel 1995: =pod
                   1996: 
1.256     matthew  1997: =head1 Excel and CSV file utility routines
                   1998: 
                   1999: =cut
                   2000: 
                   2001: ###############################################################
                   2002: ###############################################################
                   2003: 
                   2004: =pod
                   2005: 
1.1075.2.56  raeburn  2006: =over 4
                   2007: 
1.648     raeburn  2008: =item * &csv_translate($text) 
1.37      matthew  2009: 
1.185     www      2010: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2011: format.
                   2012: 
                   2013: =cut
                   2014: 
1.180     matthew  2015: ###############################################################
                   2016: ###############################################################
1.37      matthew  2017: sub csv_translate {
                   2018:     my $text = shift;
                   2019:     $text =~ s/\"/\"\"/g;
1.209     albertel 2020:     $text =~ s/\n/ /g;
1.37      matthew  2021:     return $text;
                   2022: }
1.180     matthew  2023: 
                   2024: ###############################################################
                   2025: ###############################################################
                   2026: 
                   2027: =pod
                   2028: 
1.648     raeburn  2029: =item * &define_excel_formats()
1.180     matthew  2030: 
                   2031: Define some commonly used Excel cell formats.
                   2032: 
                   2033: Currently supported formats:
                   2034: 
                   2035: =over 4
                   2036: 
                   2037: =item header
                   2038: 
                   2039: =item bold
                   2040: 
                   2041: =item h1
                   2042: 
                   2043: =item h2
                   2044: 
                   2045: =item h3
                   2046: 
1.256     matthew  2047: =item h4
                   2048: 
                   2049: =item i
                   2050: 
1.180     matthew  2051: =item date
                   2052: 
                   2053: =back
                   2054: 
                   2055: Inputs: $workbook
                   2056: 
                   2057: Returns: $format, a hash reference.
                   2058: 
1.1057    foxr     2059: 
1.180     matthew  2060: =cut
                   2061: 
                   2062: ###############################################################
                   2063: ###############################################################
                   2064: sub define_excel_formats {
                   2065:     my ($workbook) = @_;
                   2066:     my $format;
                   2067:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2068:                                                 bottom    => 1,
                   2069:                                                 align     => 'center');
                   2070:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2071:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2072:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2073:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2074:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2075:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2076:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2077:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2078:     return $format;
                   2079: }
                   2080: 
                   2081: ###############################################################
                   2082: ###############################################################
1.113     bowersj2 2083: 
                   2084: =pod
                   2085: 
1.648     raeburn  2086: =item * &create_workbook()
1.255     matthew  2087: 
                   2088: Create an Excel worksheet.  If it fails, output message on the
                   2089: request object and return undefs.
                   2090: 
                   2091: Inputs: Apache request object
                   2092: 
                   2093: Returns (undef) on failure, 
                   2094:     Excel worksheet object, scalar with filename, and formats 
                   2095:     from &Apache::loncommon::define_excel_formats on success
                   2096: 
                   2097: =cut
                   2098: 
                   2099: ###############################################################
                   2100: ###############################################################
                   2101: sub create_workbook {
                   2102:     my ($r) = @_;
                   2103:         #
                   2104:     # Create the excel spreadsheet
                   2105:     my $filename = '/prtspool/'.
1.258     albertel 2106:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2107:         time.'_'.rand(1000000000).'.xls';
                   2108:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2109:     if (! defined($workbook)) {
                   2110:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2111:         $r->print(
                   2112:             '<p class="LC_error">'
                   2113:            .&mt('Problems occurred in creating the new Excel file.')
                   2114:            .' '.&mt('This error has been logged.')
                   2115:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2116:            .'</p>'
                   2117:         );
1.255     matthew  2118:         return (undef);
                   2119:     }
                   2120:     #
1.1014    foxr     2121:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2122:     #
                   2123:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2124:     return ($workbook,$filename,$format);
                   2125: }
                   2126: 
                   2127: ###############################################################
                   2128: ###############################################################
                   2129: 
                   2130: =pod
                   2131: 
1.648     raeburn  2132: =item * &create_text_file()
1.113     bowersj2 2133: 
1.542     raeburn  2134: Create a file to write to and eventually make available to the user.
1.256     matthew  2135: If file creation fails, outputs an error message on the request object and 
                   2136: return undefs.
1.113     bowersj2 2137: 
1.256     matthew  2138: Inputs: Apache request object, and file suffix
1.113     bowersj2 2139: 
1.256     matthew  2140: Returns (undef) on failure, 
                   2141:     Filehandle and filename on success.
1.113     bowersj2 2142: 
                   2143: =cut
                   2144: 
1.256     matthew  2145: ###############################################################
                   2146: ###############################################################
                   2147: sub create_text_file {
                   2148:     my ($r,$suffix) = @_;
                   2149:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2150:     my $fh;
                   2151:     my $filename = '/prtspool/'.
1.258     albertel 2152:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2153:         time.'_'.rand(1000000000).'.'.$suffix;
                   2154:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2155:     if (! defined($fh)) {
                   2156:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2157:         $r->print(
                   2158:             '<p class="LC_error">'
                   2159:            .&mt('Problems occurred in creating the output file.')
                   2160:            .' '.&mt('This error has been logged.')
                   2161:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2162:            .'</p>'
                   2163:         );
1.113     bowersj2 2164:     }
1.256     matthew  2165:     return ($fh,$filename)
1.113     bowersj2 2166: }
                   2167: 
                   2168: 
1.256     matthew  2169: =pod 
1.113     bowersj2 2170: 
                   2171: =back
                   2172: 
                   2173: =cut
1.37      matthew  2174: 
                   2175: ###############################################################
1.33      matthew  2176: ##        Home server <option> list generating code          ##
                   2177: ###############################################################
1.35      matthew  2178: 
1.169     www      2179: # ------------------------------------------
                   2180: 
                   2181: sub domain_select {
                   2182:     my ($name,$value,$multiple)=@_;
                   2183:     my %domains=map { 
1.514     albertel 2184: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2185:     } &Apache::lonnet::all_domains();
1.169     www      2186:     if ($multiple) {
                   2187: 	$domains{''}=&mt('Any domain');
1.550     albertel 2188: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2189: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2190:     } else {
1.550     albertel 2191: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2192: 	return &select_form($name,$value,\%domains);
1.169     www      2193:     }
                   2194: }
                   2195: 
1.282     albertel 2196: #-------------------------------------------
                   2197: 
                   2198: =pod
                   2199: 
1.519     raeburn  2200: =head1 Routines for form select boxes
                   2201: 
                   2202: =over 4
                   2203: 
1.648     raeburn  2204: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2205: 
                   2206: Returns a string containing a <select> element int multiple mode
                   2207: 
                   2208: 
                   2209: Args:
                   2210:   $name - name of the <select> element
1.506     raeburn  2211:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2212:   $size - number of rows long the select element is
1.283     albertel 2213:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2214:           (shown text should already have been &mt())
1.506     raeburn  2215:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2216: 
1.282     albertel 2217: =cut
                   2218: 
                   2219: #-------------------------------------------
1.169     www      2220: sub multiple_select_form {
1.284     albertel 2221:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2222:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2223:     my $output='';
1.191     matthew  2224:     if (! defined($size)) {
                   2225:         $size = 4;
1.283     albertel 2226:         if (scalar(keys(%$hash))<4) {
                   2227:             $size = scalar(keys(%$hash));
1.191     matthew  2228:         }
                   2229:     }
1.734     bisitz   2230:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2231:     my @order;
1.506     raeburn  2232:     if (ref($order) eq 'ARRAY')  {
                   2233:         @order = @{$order};
                   2234:     } else {
                   2235:         @order = sort(keys(%$hash));
1.501     banghart 2236:     }
                   2237:     if (exists($$hash{'select_form_order'})) {
                   2238:         @order = @{$$hash{'select_form_order'}};
                   2239:     }
                   2240:         
1.284     albertel 2241:     foreach my $key (@order) {
1.356     albertel 2242:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2243:         $output.='selected="selected" ' if ($selected{$key});
                   2244:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2245:     }
                   2246:     $output.="</select>\n";
                   2247:     return $output;
                   2248: }
                   2249: 
1.88      www      2250: #-------------------------------------------
                   2251: 
                   2252: =pod
                   2253: 
1.1075.2.115  raeburn  2254: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2255: 
                   2256: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2257: allow a user to select options from a ref to a hash containing:
                   2258: option_name => displayed text. An optional $onchange can include
1.1075.2.115  raeburn  2259: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2260: An optional arg -- $readonly -- if true will cause the select form
                   2261: to be disabled, e.g., for the case where an instructor has a section-
                   2262: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2263: 
1.88      www      2264: See lonrights.pm for an example invocation and use.
                   2265: 
                   2266: =cut
                   2267: 
                   2268: #-------------------------------------------
                   2269: sub select_form {
1.1075.2.115  raeburn  2270:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2271:     return unless (ref($hashref) eq 'HASH');
                   2272:     if ($onchange) {
                   2273:         $onchange = ' onchange="'.$onchange.'"';
                   2274:     }
1.1075.2.129  raeburn  2275:     my $disabled;
                   2276:     if ($readonly) {
                   2277:         $disabled = ' disabled="disabled"';
                   2278:     }
                   2279:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2280:     my @keys;
1.970     raeburn  2281:     if (exists($hashref->{'select_form_order'})) {
                   2282: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2283:     } else {
1.970     raeburn  2284: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2285:     }
1.356     albertel 2286:     foreach my $key (@keys) {
                   2287:         $selectform.=
                   2288: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2289:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2290:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2291:     }
                   2292:     $selectform.="</select>";
                   2293:     return $selectform;
                   2294: }
                   2295: 
1.475     www      2296: # For display filters
                   2297: 
                   2298: sub display_filter {
1.1074    raeburn  2299:     my ($context) = @_;
1.475     www      2300:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2301:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2302:     my $phraseinput = 'hidden';
                   2303:     my $includeinput = 'hidden';
                   2304:     my ($checked,$includetypestext);
                   2305:     if ($env{'form.displayfilter'} eq 'containing') {
                   2306:         $phraseinput = 'text'; 
                   2307:         if ($context eq 'parmslog') {
                   2308:             $includeinput = 'checkbox';
                   2309:             if ($env{'form.includetypes'}) {
                   2310:                 $checked = ' checked="checked"';
                   2311:             }
                   2312:             $includetypestext = &mt('Include parameter types');
                   2313:         }
                   2314:     } else {
                   2315:         $includetypestext = '&nbsp;';
                   2316:     }
                   2317:     my ($additional,$secondid,$thirdid);
                   2318:     if ($context eq 'parmslog') {
                   2319:         $additional = 
                   2320:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2321:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2322:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2323:             '</label>';
                   2324:         $secondid = 'includetypes';
                   2325:         $thirdid = 'includetypestext';
                   2326:     }
                   2327:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2328:                                                     '$secondid','$thirdid')";
                   2329:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2330: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2331: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2332: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2333:            &mt('Filter: [_1]',
1.477     www      2334: 	   &select_form($env{'form.displayfilter'},
                   2335: 			'displayfilter',
1.970     raeburn  2336: 			{'currentfolder' => 'Current folder/page',
1.477     www      2337: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2338: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2339: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2340:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2341:                          '" />'.$additional;
                   2342: }
                   2343: 
                   2344: sub display_filter_js {
                   2345:     my $includetext = &mt('Include parameter types');
                   2346:     return <<"ENDJS";
                   2347:   
                   2348: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2349:     var firstType = 'hidden';
                   2350:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2351:         firstType = 'text';
                   2352:     }
                   2353:     firstObject = document.getElementById(firstid);
                   2354:     if (typeof(firstObject) == 'object') {
                   2355:         if (firstObject.type != firstType) {
                   2356:             changeInputType(firstObject,firstType);
                   2357:         }
                   2358:     }
                   2359:     if (context == 'parmslog') {
                   2360:         var secondType = 'hidden';
                   2361:         if (firstType == 'text') {
                   2362:             secondType = 'checkbox';
                   2363:         }
                   2364:         secondObject = document.getElementById(secondid);  
                   2365:         if (typeof(secondObject) == 'object') {
                   2366:             if (secondObject.type != secondType) {
                   2367:                 changeInputType(secondObject,secondType);
                   2368:             }
                   2369:         }
                   2370:         var textItem = document.getElementById(thirdid);
                   2371:         var currtext = textItem.innerHTML;
                   2372:         var newtext;
                   2373:         if (firstType == 'text') {
                   2374:             newtext = '$includetext';
                   2375:         } else {
                   2376:             newtext = '&nbsp;';
                   2377:         }
                   2378:         if (currtext != newtext) {
                   2379:             textItem.innerHTML = newtext;
                   2380:         }
                   2381:     }
                   2382:     return;
                   2383: }
                   2384: 
                   2385: function changeInputType(oldObject,newType) {
                   2386:     var newObject = document.createElement('input');
                   2387:     newObject.type = newType;
                   2388:     if (oldObject.size) {
                   2389:         newObject.size = oldObject.size;
                   2390:     }
                   2391:     if (oldObject.value) {
                   2392:         newObject.value = oldObject.value;
                   2393:     }
                   2394:     if (oldObject.name) {
                   2395:         newObject.name = oldObject.name;
                   2396:     }
                   2397:     if (oldObject.id) {
                   2398:         newObject.id = oldObject.id;
                   2399:     }
                   2400:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2401:     return;
                   2402: }
                   2403: 
                   2404: ENDJS
1.475     www      2405: }
                   2406: 
1.167     www      2407: sub gradeleveldescription {
                   2408:     my $gradelevel=shift;
                   2409:     my %gradelevels=(0 => 'Not specified',
                   2410: 		     1 => 'Grade 1',
                   2411: 		     2 => 'Grade 2',
                   2412: 		     3 => 'Grade 3',
                   2413: 		     4 => 'Grade 4',
                   2414: 		     5 => 'Grade 5',
                   2415: 		     6 => 'Grade 6',
                   2416: 		     7 => 'Grade 7',
                   2417: 		     8 => 'Grade 8',
                   2418: 		     9 => 'Grade 9',
                   2419: 		     10 => 'Grade 10',
                   2420: 		     11 => 'Grade 11',
                   2421: 		     12 => 'Grade 12',
                   2422: 		     13 => 'Grade 13',
                   2423: 		     14 => '100 Level',
                   2424: 		     15 => '200 Level',
                   2425: 		     16 => '300 Level',
                   2426: 		     17 => '400 Level',
                   2427: 		     18 => 'Graduate Level');
                   2428:     return &mt($gradelevels{$gradelevel});
                   2429: }
                   2430: 
1.163     www      2431: sub select_level_form {
                   2432:     my ($deflevel,$name)=@_;
                   2433:     unless ($deflevel) { $deflevel=0; }
1.167     www      2434:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2435:     for (my $i=0; $i<=18; $i++) {
                   2436:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2437:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2438:                 ">".&gradeleveldescription($i)."</option>\n";
                   2439:     }
                   2440:     $selectform.="</select>";
                   2441:     return $selectform;
1.163     www      2442: }
1.167     www      2443: 
1.35      matthew  2444: #-------------------------------------------
                   2445: 
1.45      matthew  2446: =pod
                   2447: 
1.1075.2.115  raeburn  2448: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2449: 
                   2450: Returns a string containing a <select name='$name' size='1'> form to 
                   2451: allow a user to select the domain to preform an operation in.  
                   2452: See loncreateuser.pm for an example invocation and use.
                   2453: 
1.90      www      2454: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2455: selected");
                   2456: 
1.743     raeburn  2457: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2458: 
1.910     raeburn  2459: 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.
                   2460: 
1.1075.2.36  raeburn  2461: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2462: 
1.1075.2.115  raeburn  2463: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2464: 
                   2465: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2466: 
1.35      matthew  2467: =cut
                   2468: 
                   2469: #-------------------------------------------
1.34      matthew  2470: sub select_dom_form {
1.1075.2.115  raeburn  2471:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2472:     if ($onchange) {
1.874     raeburn  2473:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2474:     }
1.1075.2.115  raeburn  2475:     if ($disabled) {
                   2476:         $disabled = ' disabled="disabled"';
                   2477:     }
1.1075.2.36  raeburn  2478:     my (@domains,%exclude);
1.910     raeburn  2479:     if (ref($incdoms) eq 'ARRAY') {
                   2480:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2481:     } else {
                   2482:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2483:     }
1.90      www      2484:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2485:     if (ref($excdoms) eq 'ARRAY') {
                   2486:         map { $exclude{$_} = 1; } @{$excdoms};
                   2487:     }
1.1075.2.115  raeburn  2488:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2489:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2490:         next if ($exclude{$dom});
1.356     albertel 2491:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2492:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2493:         if ($showdomdesc) {
                   2494:             if ($dom ne '') {
                   2495:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2496:                 if ($domdesc ne '') {
                   2497:                     $selectdomain .= ' ('.$domdesc.')';
                   2498:                 }
                   2499:             } 
                   2500:         }
                   2501:         $selectdomain .= "</option>\n";
1.34      matthew  2502:     }
                   2503:     $selectdomain.="</select>";
                   2504:     return $selectdomain;
                   2505: }
                   2506: 
1.35      matthew  2507: #-------------------------------------------
                   2508: 
1.45      matthew  2509: =pod
                   2510: 
1.648     raeburn  2511: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2512: 
1.586     raeburn  2513: input: 4 arguments (two required, two optional) - 
                   2514:     $domain - domain of new user
                   2515:     $name - name of form element
                   2516:     $default - Value of 'default' causes a default item to be first 
                   2517:                             option, and selected by default. 
                   2518:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2519:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2520: output: returns 2 items: 
1.586     raeburn  2521: (a) form element which contains either:
                   2522:    (i) <select name="$name">
                   2523:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2524:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2525:        </select>
                   2526:        form item if there are multiple library servers in $domain, or
                   2527:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2528:        if there is only one library server in $domain.
                   2529: 
                   2530: (b) number of library servers found.
                   2531: 
                   2532: See loncreateuser.pm for example of use.
1.35      matthew  2533: 
                   2534: =cut
                   2535: 
                   2536: #-------------------------------------------
1.586     raeburn  2537: sub home_server_form_item {
                   2538:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2539:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2540:     my $result;
                   2541:     my $numlib = keys(%servers);
                   2542:     if ($numlib > 1) {
                   2543:         $result .= '<select name="'.$name.'" />'."\n";
                   2544:         if ($default) {
1.804     bisitz   2545:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2546:                        '</option>'."\n";
                   2547:         }
                   2548:         foreach my $hostid (sort(keys(%servers))) {
                   2549:             $result.= '<option value="'.$hostid.'">'.
                   2550: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2551:         }
                   2552:         $result .= '</select>'."\n";
                   2553:     } elsif ($numlib == 1) {
                   2554:         my $hostid;
                   2555:         foreach my $item (keys(%servers)) {
                   2556:             $hostid = $item;
                   2557:         }
                   2558:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2559:                    $hostid.'" />';
                   2560:                    if (!$hide) {
                   2561:                        $result .= $hostid.' '.$servers{$hostid};
                   2562:                    }
                   2563:                    $result .= "\n";
                   2564:     } elsif ($default) {
                   2565:         $result .= '<input type="hidden" name="'.$name.
                   2566:                    '" value="default" />';
                   2567:                    if (!$hide) {
                   2568:                        $result .= &mt('default');
                   2569:                    }
                   2570:                    $result .= "\n";
1.33      matthew  2571:     }
1.586     raeburn  2572:     return ($result,$numlib);
1.33      matthew  2573: }
1.112     bowersj2 2574: 
                   2575: =pod
                   2576: 
1.534     albertel 2577: =back 
                   2578: 
1.112     bowersj2 2579: =cut
1.87      matthew  2580: 
                   2581: ###############################################################
1.112     bowersj2 2582: ##                  Decoding User Agent                      ##
1.87      matthew  2583: ###############################################################
                   2584: 
                   2585: =pod
                   2586: 
1.112     bowersj2 2587: =head1 Decoding the User Agent
                   2588: 
                   2589: =over 4
                   2590: 
                   2591: =item * &decode_user_agent()
1.87      matthew  2592: 
                   2593: Inputs: $r
                   2594: 
                   2595: Outputs:
                   2596: 
                   2597: =over 4
                   2598: 
1.112     bowersj2 2599: =item * $httpbrowser
1.87      matthew  2600: 
1.112     bowersj2 2601: =item * $clientbrowser
1.87      matthew  2602: 
1.112     bowersj2 2603: =item * $clientversion
1.87      matthew  2604: 
1.112     bowersj2 2605: =item * $clientmathml
1.87      matthew  2606: 
1.112     bowersj2 2607: =item * $clientunicode
1.87      matthew  2608: 
1.112     bowersj2 2609: =item * $clientos
1.87      matthew  2610: 
1.1075.2.42  raeburn  2611: =item * $clientmobile
                   2612: 
                   2613: =item * $clientinfo
                   2614: 
1.1075.2.77  raeburn  2615: =item * $clientosversion
                   2616: 
1.87      matthew  2617: =back
                   2618: 
1.157     matthew  2619: =back 
                   2620: 
1.87      matthew  2621: =cut
                   2622: 
                   2623: ###############################################################
                   2624: ###############################################################
                   2625: sub decode_user_agent {
1.247     albertel 2626:     my ($r)=@_;
1.87      matthew  2627:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2628:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2629:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2630:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2631:     my $clientbrowser='unknown';
                   2632:     my $clientversion='0';
                   2633:     my $clientmathml='';
                   2634:     my $clientunicode='0';
1.1075.2.42  raeburn  2635:     my $clientmobile=0;
1.1075.2.77  raeburn  2636:     my $clientosversion='';
1.87      matthew  2637:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2638:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2639: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2640: 	    $clientbrowser=$bname;
                   2641:             $httpbrowser=~/$vreg/i;
                   2642: 	    $clientversion=$1;
                   2643:             $clientmathml=($clientversion>=$minv);
                   2644:             $clientunicode=($clientversion>=$univ);
                   2645: 	}
                   2646:     }
                   2647:     my $clientos='unknown';
1.1075.2.42  raeburn  2648:     my $clientinfo;
1.87      matthew  2649:     if (($httpbrowser=~/linux/i) ||
                   2650:         ($httpbrowser=~/unix/i) ||
                   2651:         ($httpbrowser=~/ux/i) ||
                   2652:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2653:     if (($httpbrowser=~/vax/i) ||
                   2654:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2655:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2656:     if (($httpbrowser=~/mac/i) ||
                   2657:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2658:     if ($httpbrowser=~/win/i) {
                   2659:         $clientos='win';
                   2660:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2661:             $clientosversion = $1;
                   2662:         }
                   2663:     }
1.87      matthew  2664:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2665:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2666:         $clientmobile=lc($1);
                   2667:     }
                   2668:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2669:         $clientinfo = 'firefox-'.$1;
                   2670:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2671:         $clientinfo = 'chromeframe-'.$1;
                   2672:     }
1.87      matthew  2673:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2674:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2675:             $clientosversion);
1.87      matthew  2676: }
                   2677: 
1.32      matthew  2678: ###############################################################
                   2679: ##    Authentication changing form generation subroutines    ##
                   2680: ###############################################################
                   2681: ##
                   2682: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2683: ## hash, and have reasonable default values.
                   2684: ##
                   2685: ##    formname = the name given in the <form> tag.
1.35      matthew  2686: #-------------------------------------------
                   2687: 
1.45      matthew  2688: =pod
                   2689: 
1.112     bowersj2 2690: =head1 Authentication Routines
                   2691: 
                   2692: =over 4
                   2693: 
1.648     raeburn  2694: =item * &authform_xxxxxx()
1.35      matthew  2695: 
                   2696: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2697: handle some of the conveniences required for authentication forms.  
                   2698: This is not an optimal method, but it works.  
                   2699: 
                   2700: =over 4
                   2701: 
1.112     bowersj2 2702: =item * authform_header
1.35      matthew  2703: 
1.112     bowersj2 2704: =item * authform_authorwarning
1.35      matthew  2705: 
1.112     bowersj2 2706: =item * authform_nochange
1.35      matthew  2707: 
1.112     bowersj2 2708: =item * authform_kerberos
1.35      matthew  2709: 
1.112     bowersj2 2710: =item * authform_internal
1.35      matthew  2711: 
1.112     bowersj2 2712: =item * authform_filesystem
1.35      matthew  2713: 
                   2714: =back
                   2715: 
1.648     raeburn  2716: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2717: 
1.35      matthew  2718: =cut
                   2719: 
                   2720: #-------------------------------------------
1.32      matthew  2721: sub authform_header{  
                   2722:     my %in = (
                   2723:         formname => 'cu',
1.80      albertel 2724:         kerb_def_dom => '',
1.32      matthew  2725:         @_,
                   2726:     );
                   2727:     $in{'formname'} = 'document.' . $in{'formname'};
                   2728:     my $result='';
1.80      albertel 2729: 
                   2730: #---------------------------------------------- Code for upper case translation
                   2731:     my $Javascript_toUpperCase;
                   2732:     unless ($in{kerb_def_dom}) {
                   2733:         $Javascript_toUpperCase =<<"END";
                   2734:         switch (choice) {
                   2735:            case 'krb': currentform.elements[choicearg].value =
                   2736:                currentform.elements[choicearg].value.toUpperCase();
                   2737:                break;
                   2738:            default:
                   2739:         }
                   2740: END
                   2741:     } else {
                   2742:         $Javascript_toUpperCase = "";
                   2743:     }
                   2744: 
1.165     raeburn  2745:     my $radioval = "'nochange'";
1.591     raeburn  2746:     if (defined($in{'curr_authtype'})) {
                   2747:         if ($in{'curr_authtype'} ne '') {
                   2748:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2749:         }
1.174     matthew  2750:     }
1.165     raeburn  2751:     my $argfield = 'null';
1.591     raeburn  2752:     if (defined($in{'mode'})) {
1.165     raeburn  2753:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2754:             if (defined($in{'curr_autharg'})) {
                   2755:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2756:                     $argfield = "'$in{'curr_autharg'}'";
                   2757:                 }
                   2758:             }
                   2759:         }
                   2760:     }
                   2761: 
1.32      matthew  2762:     $result.=<<"END";
                   2763: var current = new Object();
1.165     raeburn  2764: current.radiovalue = $radioval;
                   2765: current.argfield = $argfield;
1.32      matthew  2766: 
                   2767: function changed_radio(choice,currentform) {
                   2768:     var choicearg = choice + 'arg';
                   2769:     // If a radio button in changed, we need to change the argfield
                   2770:     if (current.radiovalue != choice) {
                   2771:         current.radiovalue = choice;
                   2772:         if (current.argfield != null) {
                   2773:             currentform.elements[current.argfield].value = '';
                   2774:         }
                   2775:         if (choice == 'nochange') {
                   2776:             current.argfield = null;
                   2777:         } else {
                   2778:             current.argfield = choicearg;
                   2779:             switch(choice) {
                   2780:                 case 'krb': 
                   2781:                     currentform.elements[current.argfield].value = 
                   2782:                         "$in{'kerb_def_dom'}";
                   2783:                 break;
                   2784:               default:
                   2785:                 break;
                   2786:             }
                   2787:         }
                   2788:     }
                   2789:     return;
                   2790: }
1.22      www      2791: 
1.32      matthew  2792: function changed_text(choice,currentform) {
                   2793:     var choicearg = choice + 'arg';
                   2794:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2795:         $Javascript_toUpperCase
1.32      matthew  2796:         // clear old field
                   2797:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2798:             currentform.elements[current.argfield].value = '';
                   2799:         }
                   2800:         current.argfield = choicearg;
                   2801:     }
                   2802:     set_auth_radio_buttons(choice,currentform);
                   2803:     return;
1.20      www      2804: }
1.32      matthew  2805: 
                   2806: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2807:     var numauthchoices = currentform.login.length;
                   2808:     if (typeof numauthchoices  == "undefined") {
                   2809:         return;
                   2810:     } 
1.32      matthew  2811:     var i=0;
1.986     raeburn  2812:     while (i < numauthchoices) {
1.32      matthew  2813:         if (currentform.login[i].value == newvalue) { break; }
                   2814:         i++;
                   2815:     }
1.986     raeburn  2816:     if (i == numauthchoices) {
1.32      matthew  2817:         return;
                   2818:     }
                   2819:     current.radiovalue = newvalue;
                   2820:     currentform.login[i].checked = true;
                   2821:     return;
                   2822: }
                   2823: END
                   2824:     return $result;
                   2825: }
                   2826: 
1.1075.2.20  raeburn  2827: sub authform_authorwarning {
1.32      matthew  2828:     my $result='';
1.144     matthew  2829:     $result='<i>'.
                   2830:         &mt('As a general rule, only authors or co-authors should be '.
                   2831:             'filesystem authenticated '.
                   2832:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2833:     return $result;
                   2834: }
                   2835: 
1.1075.2.20  raeburn  2836: sub authform_nochange {
1.32      matthew  2837:     my %in = (
                   2838:               formname => 'document.cu',
                   2839:               kerb_def_dom => 'MSU.EDU',
                   2840:               @_,
                   2841:           );
1.1075.2.20  raeburn  2842:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2843:     my $result;
1.1075.2.20  raeburn  2844:     if (!$authnum) {
                   2845:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2846:     } else {
                   2847:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2848:                   '<input type="radio" name="login" value="nochange" '.
                   2849:                   'checked="checked" onclick="'.
1.281     albertel 2850:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2851: 	    '</label>';
1.586     raeburn  2852:     }
1.32      matthew  2853:     return $result;
                   2854: }
                   2855: 
1.591     raeburn  2856: sub authform_kerberos {
1.32      matthew  2857:     my %in = (
                   2858:               formname => 'document.cu',
                   2859:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2860:               kerb_def_auth => 'krb4',
1.32      matthew  2861:               @_,
                   2862:               );
1.586     raeburn  2863:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2864:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2865:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2866:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2867:        $check5 = ' checked="checked"';
1.80      albertel 2868:     } else {
1.772     bisitz   2869:        $check4 = ' checked="checked"';
1.80      albertel 2870:     }
1.1075.2.117  raeburn  2871:     if ($in{'readonly'}) {
                   2872:         $disabled = ' disabled="disabled"';
                   2873:     }
1.165     raeburn  2874:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2875:     if (defined($in{'curr_authtype'})) {
                   2876:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2877:             $krbcheck = ' checked="checked"';
1.623     raeburn  2878:             if (defined($in{'mode'})) {
                   2879:                 if ($in{'mode'} eq 'modifyuser') {
                   2880:                     $krbcheck = '';
                   2881:                 }
                   2882:             }
1.591     raeburn  2883:             if (defined($in{'curr_kerb_ver'})) {
                   2884:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2885:                     $check5 = ' checked="checked"';
1.591     raeburn  2886:                     $check4 = '';
                   2887:                 } else {
1.772     bisitz   2888:                     $check4 = ' checked="checked"';
1.591     raeburn  2889:                     $check5 = '';
                   2890:                 }
1.586     raeburn  2891:             }
1.591     raeburn  2892:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2893:                 $krbarg = $in{'curr_autharg'};
                   2894:             }
1.586     raeburn  2895:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2896:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2897:                     $result = 
                   2898:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2899:         $in{'curr_autharg'},$krbver);
                   2900:                 } else {
                   2901:                     $result =
                   2902:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2903:                 }
                   2904:                 return $result; 
                   2905:             }
                   2906:         }
                   2907:     } else {
                   2908:         if ($authnum == 1) {
1.784     bisitz   2909:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2910:         }
                   2911:     }
1.586     raeburn  2912:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2913:         return;
1.587     raeburn  2914:     } elsif ($authtype eq '') {
1.591     raeburn  2915:         if (defined($in{'mode'})) {
1.587     raeburn  2916:             if ($in{'mode'} eq 'modifycourse') {
                   2917:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2918:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  2919:                 }
                   2920:             }
                   2921:         }
1.586     raeburn  2922:     }
                   2923:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2924:     if ($authtype eq '') {
                   2925:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2926:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  2927:                     $krbcheck.$disabled.' />';
1.586     raeburn  2928:     }
                   2929:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2930:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2931:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2932:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2933:          $in{'curr_authtype'} eq 'krb4')) {
                   2934:         $result .= &mt
1.144     matthew  2935:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2936:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2937:          '<label>'.$authtype,
1.281     albertel 2938:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2939:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2940:              'onchange="'.$jscall.'"'.$disabled.' />',
                   2941:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   2942:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 2943: 	 '</label>');
1.586     raeburn  2944:     } elsif ($can_assign{'krb4'}) {
                   2945:         $result .= &mt
                   2946:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2947:          '[_3] Version 4 [_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="4" />',
                   2953:          '</label>');
                   2954:     } elsif ($can_assign{'krb5'}) {
                   2955:         $result .= &mt
                   2956:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2957:          '[_3] Version 5 [_4]',
                   2958:          '<label>'.$authtype,
                   2959:          '</label><input type="text" size="10" name="krbarg" '.
                   2960:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2961:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2962:          '<label><input type="hidden" name="krbver" value="5" />',
                   2963:          '</label>');
                   2964:     }
1.32      matthew  2965:     return $result;
                   2966: }
                   2967: 
1.1075.2.20  raeburn  2968: sub authform_internal {
1.586     raeburn  2969:     my %in = (
1.32      matthew  2970:                 formname => 'document.cu',
                   2971:                 kerb_def_dom => 'MSU.EDU',
                   2972:                 @_,
                   2973:                 );
1.1075.2.117  raeburn  2974:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2975:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  2976:     if ($in{'readonly'}) {
                   2977:         $disabled = ' disabled="disabled"';
                   2978:     }
1.591     raeburn  2979:     if (defined($in{'curr_authtype'})) {
                   2980:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2981:             if ($can_assign{'int'}) {
1.772     bisitz   2982:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2983:                 if (defined($in{'mode'})) {
                   2984:                     if ($in{'mode'} eq 'modifyuser') {
                   2985:                         $intcheck = '';
                   2986:                     }
                   2987:                 }
1.591     raeburn  2988:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2989:                     $intarg = $in{'curr_autharg'};
                   2990:                 }
                   2991:             } else {
                   2992:                 $result = &mt('Currently internally authenticated.');
                   2993:                 return $result;
1.165     raeburn  2994:             }
                   2995:         }
1.586     raeburn  2996:     } else {
                   2997:         if ($authnum == 1) {
1.784     bisitz   2998:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2999:         }
                   3000:     }
                   3001:     if (!$can_assign{'int'}) {
                   3002:         return;
1.587     raeburn  3003:     } elsif ($authtype eq '') {
1.591     raeburn  3004:         if (defined($in{'mode'})) {
1.587     raeburn  3005:             if ($in{'mode'} eq 'modifycourse') {
                   3006:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3007:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3008:                 }
                   3009:             }
                   3010:         }
1.165     raeburn  3011:     }
1.586     raeburn  3012:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3013:     if ($authtype eq '') {
                   3014:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  3015:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3016:     }
1.605     bisitz   3017:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3018:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3019:     $result = &mt
1.144     matthew  3020:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3021:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3022:     $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  3023:     return $result;
                   3024: }
                   3025: 
1.1075.2.20  raeburn  3026: sub authform_local {
1.32      matthew  3027:     my %in = (
                   3028:               formname => 'document.cu',
                   3029:               kerb_def_dom => 'MSU.EDU',
                   3030:               @_,
                   3031:               );
1.1075.2.117  raeburn  3032:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3033:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3034:     if ($in{'readonly'}) {
                   3035:         $disabled = ' disabled="disabled"';
                   3036:     }
1.591     raeburn  3037:     if (defined($in{'curr_authtype'})) {
                   3038:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3039:             if ($can_assign{'loc'}) {
1.772     bisitz   3040:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3041:                 if (defined($in{'mode'})) {
                   3042:                     if ($in{'mode'} eq 'modifyuser') {
                   3043:                         $loccheck = '';
                   3044:                     }
                   3045:                 }
1.591     raeburn  3046:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3047:                     $locarg = $in{'curr_autharg'};
                   3048:                 }
                   3049:             } else {
                   3050:                 $result = &mt('Currently using local (institutional) authentication.');
                   3051:                 return $result;
1.165     raeburn  3052:             }
                   3053:         }
1.586     raeburn  3054:     } else {
                   3055:         if ($authnum == 1) {
1.784     bisitz   3056:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3057:         }
                   3058:     }
                   3059:     if (!$can_assign{'loc'}) {
                   3060:         return;
1.587     raeburn  3061:     } elsif ($authtype eq '') {
1.591     raeburn  3062:         if (defined($in{'mode'})) {
1.587     raeburn  3063:             if ($in{'mode'} eq 'modifycourse') {
                   3064:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3065:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3066:                 }
                   3067:             }
                   3068:         }
1.165     raeburn  3069:     }
1.586     raeburn  3070:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3071:     if ($authtype eq '') {
                   3072:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3073:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3074:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3075:     }
                   3076:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3077:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3078:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3079:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3080:     return $result;
                   3081: }
                   3082: 
1.1075.2.20  raeburn  3083: sub authform_filesystem {
1.32      matthew  3084:     my %in = (
                   3085:               formname => 'document.cu',
                   3086:               kerb_def_dom => 'MSU.EDU',
                   3087:               @_,
                   3088:               );
1.1075.2.117  raeburn  3089:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3090:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3091:     if ($in{'readonly'}) {
                   3092:         $disabled = ' disabled="disabled"';
                   3093:     }
1.591     raeburn  3094:     if (defined($in{'curr_authtype'})) {
                   3095:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3096:             if ($can_assign{'fsys'}) {
1.772     bisitz   3097:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3098:                 if (defined($in{'mode'})) {
                   3099:                     if ($in{'mode'} eq 'modifyuser') {
                   3100:                         $fsyscheck = '';
                   3101:                     }
                   3102:                 }
1.586     raeburn  3103:             } else {
                   3104:                 $result = &mt('Currently Filesystem Authenticated.');
                   3105:                 return $result;
                   3106:             }           
                   3107:         }
                   3108:     } else {
                   3109:         if ($authnum == 1) {
1.784     bisitz   3110:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3111:         }
                   3112:     }
                   3113:     if (!$can_assign{'fsys'}) {
                   3114:         return;
1.587     raeburn  3115:     } elsif ($authtype eq '') {
1.591     raeburn  3116:         if (defined($in{'mode'})) {
1.587     raeburn  3117:             if ($in{'mode'} eq 'modifycourse') {
                   3118:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3119:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3120:                 }
                   3121:             }
                   3122:         }
1.586     raeburn  3123:     }
                   3124:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3125:     if ($authtype eq '') {
                   3126:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3127:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3128:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3129:     }
1.1075.2.158  raeburn  3130:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3131:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3132:     $result = &mt
1.144     matthew  3133:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1075.2.158  raeburn  3134:          '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3135:     return $result;
                   3136: }
                   3137: 
1.586     raeburn  3138: sub get_assignable_auth {
                   3139:     my ($dom) = @_;
                   3140:     if ($dom eq '') {
                   3141:         $dom = $env{'request.role.domain'};
                   3142:     }
                   3143:     my %can_assign = (
                   3144:                           krb4 => 1,
                   3145:                           krb5 => 1,
                   3146:                           int  => 1,
                   3147:                           loc  => 1,
                   3148:                      );
                   3149:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3150:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3151:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3152:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3153:             my $context;
                   3154:             if ($env{'request.role'} =~ /^au/) {
                   3155:                 $context = 'author';
1.1075.2.117  raeburn  3156:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3157:                 $context = 'domain';
                   3158:             } elsif ($env{'request.course.id'}) {
                   3159:                 $context = 'course';
                   3160:             }
                   3161:             if ($context) {
                   3162:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3163:                    %can_assign = %{$authhash->{$context}}; 
                   3164:                 }
                   3165:             }
                   3166:         }
                   3167:     }
                   3168:     my $authnum = 0;
                   3169:     foreach my $key (keys(%can_assign)) {
                   3170:         if ($can_assign{$key}) {
                   3171:             $authnum ++;
                   3172:         }
                   3173:     }
                   3174:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3175:         $authnum --;
                   3176:     }
                   3177:     return ($authnum,%can_assign);
                   3178: }
                   3179: 
1.1075.2.137  raeburn  3180: sub check_passwd_rules {
                   3181:     my ($domain,$plainpass) = @_;
                   3182:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3183:     my ($min,$max,@chars,@brokerule,$warning);
1.1075.2.138  raeburn  3184:     $min = $Apache::lonnet::passwdmin;
1.1075.2.137  raeburn  3185:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3186:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1075.2.138  raeburn  3187:             if ($passwdconf{'min'} > $min) {
                   3188:                 $min = $passwdconf{'min'};
                   3189:             }
1.1075.2.137  raeburn  3190:         }
                   3191:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3192:             $max = $passwdconf{'max'};
                   3193:         }
                   3194:         @chars = @{$passwdconf{'chars'}};
                   3195:     }
                   3196:     if (($min) && (length($plainpass) < $min)) {
                   3197:         push(@brokerule,'min');
                   3198:     }
                   3199:     if (($max) && (length($plainpass) > $max)) {
                   3200:         push(@brokerule,'max');
                   3201:     }
                   3202:     if (@chars) {
                   3203:         my %rules;
                   3204:         map { $rules{$_} = 1; } @chars;
                   3205:         if ($rules{'uc'}) {
                   3206:             unless ($plainpass =~ /[A-Z]/) {
                   3207:                 push(@brokerule,'uc');
                   3208:             }
                   3209:         }
                   3210:         if ($rules{'lc'}) {
                   3211:             unless ($plainpass =~ /[a-z]/) {
                   3212:                 push(@brokerule,'lc');
                   3213:             }
                   3214:         }
                   3215:         if ($rules{'num'}) {
                   3216:             unless ($plainpass =~ /\d/) {
                   3217:                 push(@brokerule,'num');
                   3218:             }
                   3219:         }
                   3220:         if ($rules{'spec'}) {
                   3221:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3222:                 push(@brokerule,'spec');
                   3223:             }
                   3224:         }
                   3225:     }
                   3226:     if (@brokerule) {
                   3227:         my %rulenames = &Apache::lonlocal::texthash(
                   3228:             uc   => 'At least one upper case letter',
                   3229:             lc   => 'At least one lower case letter',
                   3230:             num  => 'At least one number',
                   3231:             spec => 'At least one non-alphanumeric',
                   3232:         );
                   3233:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3234:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3235:         $rulenames{'num'} .= ': 0123456789';
                   3236:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3237:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3238:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3239:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1075.2.143  raeburn  3240:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1075.2.137  raeburn  3241:             if (grep(/^$rule$/,@brokerule)) {
                   3242:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3243:             }
                   3244:         }
                   3245:         $warning .= '</ul>';
                   3246:     }
                   3247:     if (wantarray) {
                   3248:         return @brokerule;
                   3249:     }
                   3250:     return $warning;
                   3251: }
                   3252: 
1.80      albertel 3253: ###############################################################
                   3254: ##    Get Kerberos Defaults for Domain                 ##
                   3255: ###############################################################
                   3256: ##
                   3257: ## Returns default kerberos version and an associated argument
                   3258: ## as listed in file domain.tab. If not listed, provides
                   3259: ## appropriate default domain and kerberos version.
                   3260: ##
                   3261: #-------------------------------------------
                   3262: 
                   3263: =pod
                   3264: 
1.648     raeburn  3265: =item * &get_kerberos_defaults()
1.80      albertel 3266: 
                   3267: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3268: version and domain. If not found, it defaults to version 4 and the 
                   3269: domain of the server.
1.80      albertel 3270: 
1.648     raeburn  3271: =over 4
                   3272: 
1.80      albertel 3273: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3274: 
1.648     raeburn  3275: =back
                   3276: 
                   3277: =back
                   3278: 
1.80      albertel 3279: =cut
                   3280: 
                   3281: #-------------------------------------------
                   3282: sub get_kerberos_defaults {
                   3283:     my $domain=shift;
1.641     raeburn  3284:     my ($krbdef,$krbdefdom);
                   3285:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3286:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3287:         $krbdef = $domdefaults{'auth_def'};
                   3288:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3289:     } else {
1.80      albertel 3290:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3291:         my $krbdefdom=$1;
                   3292:         $krbdefdom=~tr/a-z/A-Z/;
                   3293:         $krbdef = "krb4";
                   3294:     }
                   3295:     return ($krbdef,$krbdefdom);
                   3296: }
1.112     bowersj2 3297: 
1.32      matthew  3298: 
1.46      matthew  3299: ###############################################################
                   3300: ##                Thesaurus Functions                        ##
                   3301: ###############################################################
1.20      www      3302: 
1.46      matthew  3303: =pod
1.20      www      3304: 
1.112     bowersj2 3305: =head1 Thesaurus Functions
                   3306: 
                   3307: =over 4
                   3308: 
1.648     raeburn  3309: =item * &initialize_keywords()
1.46      matthew  3310: 
                   3311: Initializes the package variable %Keywords if it is empty.  Uses the
                   3312: package variable $thesaurus_db_file.
                   3313: 
                   3314: =cut
                   3315: 
                   3316: ###################################################
                   3317: 
                   3318: sub initialize_keywords {
                   3319:     return 1 if (scalar keys(%Keywords));
                   3320:     # If we are here, %Keywords is empty, so fill it up
                   3321:     #   Make sure the file we need exists...
                   3322:     if (! -e $thesaurus_db_file) {
                   3323:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3324:                                  " failed because it does not exist");
                   3325:         return 0;
                   3326:     }
                   3327:     #   Set up the hash as a database
                   3328:     my %thesaurus_db;
                   3329:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3330:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3331:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3332:                                  $thesaurus_db_file);
                   3333:         return 0;
                   3334:     } 
                   3335:     #  Get the average number of appearances of a word.
                   3336:     my $avecount = $thesaurus_db{'average.count'};
                   3337:     #  Put keywords (those that appear > average) into %Keywords
                   3338:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3339:         my ($count,undef) = split /:/,$data;
                   3340:         $Keywords{$word}++ if ($count > $avecount);
                   3341:     }
                   3342:     untie %thesaurus_db;
                   3343:     # Remove special values from %Keywords.
1.356     albertel 3344:     foreach my $value ('total.count','average.count') {
                   3345:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3346:   }
1.46      matthew  3347:     return 1;
                   3348: }
                   3349: 
                   3350: ###################################################
                   3351: 
                   3352: =pod
                   3353: 
1.648     raeburn  3354: =item * &keyword($word)
1.46      matthew  3355: 
                   3356: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3357: than the average number of times in the thesaurus database.  Calls 
                   3358: &initialize_keywords
                   3359: 
                   3360: =cut
                   3361: 
                   3362: ###################################################
1.20      www      3363: 
                   3364: sub keyword {
1.46      matthew  3365:     return if (!&initialize_keywords());
                   3366:     my $word=lc(shift());
                   3367:     $word=~s/\W//g;
                   3368:     return exists($Keywords{$word});
1.20      www      3369: }
1.46      matthew  3370: 
                   3371: ###############################################################
                   3372: 
                   3373: =pod 
1.20      www      3374: 
1.648     raeburn  3375: =item * &get_related_words()
1.46      matthew  3376: 
1.160     matthew  3377: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3378: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3379: will be returned.  The order of the words returned is determined by the
                   3380: database which holds them.
                   3381: 
                   3382: Uses global $thesaurus_db_file.
                   3383: 
1.1057    foxr     3384: 
1.46      matthew  3385: =cut
                   3386: 
                   3387: ###############################################################
                   3388: sub get_related_words {
                   3389:     my $keyword = shift;
                   3390:     my %thesaurus_db;
                   3391:     if (! -e $thesaurus_db_file) {
                   3392:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3393:                                  "failed because the file does not exist");
                   3394:         return ();
                   3395:     }
                   3396:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3397:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3398:         return ();
                   3399:     } 
                   3400:     my @Words=();
1.429     www      3401:     my $count=0;
1.46      matthew  3402:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3403: 	# The first element is the number of times
                   3404: 	# the word appears.  We do not need it now.
1.429     www      3405: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3406: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3407: 	my $threshold=$mostfrequentcount/10;
                   3408:         foreach my $possibleword (@RelatedWords) {
                   3409:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3410:             if ($wordcount>$threshold) {
                   3411: 		push(@Words,$word);
                   3412:                 $count++;
                   3413:                 if ($count>10) { last; }
                   3414: 	    }
1.20      www      3415:         }
                   3416:     }
1.46      matthew  3417:     untie %thesaurus_db;
                   3418:     return @Words;
1.14      harris41 3419: }
1.46      matthew  3420: 
1.112     bowersj2 3421: =pod
                   3422: 
                   3423: =back
                   3424: 
                   3425: =cut
1.61      www      3426: 
                   3427: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3428: =pod
                   3429: 
1.112     bowersj2 3430: =head1 User Name Functions
                   3431: 
                   3432: =over 4
                   3433: 
1.648     raeburn  3434: =item * &plainname($uname,$udom,$first)
1.81      albertel 3435: 
1.112     bowersj2 3436: Takes a users logon name and returns it as a string in
1.226     albertel 3437: "first middle last generation" form 
                   3438: if $first is set to 'lastname' then it returns it as
                   3439: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3440: 
                   3441: =cut
1.61      www      3442: 
1.295     www      3443: 
1.81      albertel 3444: ###############################################################
1.61      www      3445: sub plainname {
1.226     albertel 3446:     my ($uname,$udom,$first)=@_;
1.537     albertel 3447:     return if (!defined($uname) || !defined($udom));
1.295     www      3448:     my %names=&getnames($uname,$udom);
1.226     albertel 3449:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3450: 					  $names{'middlename'},
                   3451: 					  $names{'lastname'},
                   3452: 					  $names{'generation'},$first);
                   3453:     $name=~s/^\s+//;
1.62      www      3454:     $name=~s/\s+$//;
                   3455:     $name=~s/\s+/ /g;
1.353     albertel 3456:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3457:     return $name;
1.61      www      3458: }
1.66      www      3459: 
                   3460: # -------------------------------------------------------------------- Nickname
1.81      albertel 3461: =pod
                   3462: 
1.648     raeburn  3463: =item * &nickname($uname,$udom)
1.81      albertel 3464: 
                   3465: Gets a users name and returns it as a string as
                   3466: 
                   3467: "&quot;nickname&quot;"
1.66      www      3468: 
1.81      albertel 3469: if the user has a nickname or
                   3470: 
                   3471: "first middle last generation"
                   3472: 
                   3473: if the user does not
                   3474: 
                   3475: =cut
1.66      www      3476: 
                   3477: sub nickname {
                   3478:     my ($uname,$udom)=@_;
1.537     albertel 3479:     return if (!defined($uname) || !defined($udom));
1.295     www      3480:     my %names=&getnames($uname,$udom);
1.68      albertel 3481:     my $name=$names{'nickname'};
1.66      www      3482:     if ($name) {
                   3483:        $name='&quot;'.$name.'&quot;'; 
                   3484:     } else {
                   3485:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3486: 	     $names{'lastname'}.' '.$names{'generation'};
                   3487:        $name=~s/\s+$//;
                   3488:        $name=~s/\s+/ /g;
                   3489:     }
                   3490:     return $name;
                   3491: }
                   3492: 
1.295     www      3493: sub getnames {
                   3494:     my ($uname,$udom)=@_;
1.537     albertel 3495:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3496:     if ($udom eq 'public' && $uname eq 'public') {
                   3497: 	return ('lastname' => &mt('Public'));
                   3498:     }
1.295     www      3499:     my $id=$uname.':'.$udom;
                   3500:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3501:     if ($cached) {
                   3502: 	return %{$names};
                   3503:     } else {
                   3504: 	my %loadnames=&Apache::lonnet::get('environment',
                   3505:                     ['firstname','middlename','lastname','generation','nickname'],
                   3506: 					 $udom,$uname);
                   3507: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3508: 	return %loadnames;
                   3509:     }
                   3510: }
1.61      www      3511: 
1.542     raeburn  3512: # -------------------------------------------------------------------- getemails
1.648     raeburn  3513: 
1.542     raeburn  3514: =pod
                   3515: 
1.648     raeburn  3516: =item * &getemails($uname,$udom)
1.542     raeburn  3517: 
                   3518: Gets a user's email information and returns it as a hash with keys:
                   3519: notification, critnotification, permanentemail
                   3520: 
                   3521: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3522: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3523:  
1.648     raeburn  3524: 
1.542     raeburn  3525: =cut
                   3526: 
1.648     raeburn  3527: 
1.466     albertel 3528: sub getemails {
                   3529:     my ($uname,$udom)=@_;
                   3530:     if ($udom eq 'public' && $uname eq 'public') {
                   3531: 	return;
                   3532:     }
1.467     www      3533:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3534:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3535:     my $id=$uname.':'.$udom;
                   3536:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3537:     if ($cached) {
                   3538: 	return %{$names};
                   3539:     } else {
                   3540: 	my %loadnames=&Apache::lonnet::get('environment',
                   3541:                     			   ['notification','critnotification',
                   3542: 					    'permanentemail'],
                   3543: 					   $udom,$uname);
                   3544: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3545: 	return %loadnames;
                   3546:     }
                   3547: }
                   3548: 
1.551     albertel 3549: sub flush_email_cache {
                   3550:     my ($uname,$udom)=@_;
                   3551:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3552:     if (!$uname) { $uname=$env{'user.name'};   }
                   3553:     return if ($udom eq 'public' && $uname eq 'public');
                   3554:     my $id=$uname.':'.$udom;
                   3555:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3556: }
                   3557: 
1.728     raeburn  3558: # -------------------------------------------------------------------- getlangs
                   3559: 
                   3560: =pod
                   3561: 
                   3562: =item * &getlangs($uname,$udom)
                   3563: 
                   3564: Gets a user's language preference and returns it as a hash with key:
                   3565: language.
                   3566: 
                   3567: =cut
                   3568: 
                   3569: 
                   3570: sub getlangs {
                   3571:     my ($uname,$udom) = @_;
                   3572:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3573:     if (!$uname) { $uname=$env{'user.name'};   }
                   3574:     my $id=$uname.':'.$udom;
                   3575:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3576:     if ($cached) {
                   3577:         return %{$langs};
                   3578:     } else {
                   3579:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3580:                                            $udom,$uname);
                   3581:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3582:         return %loadlangs;
                   3583:     }
                   3584: }
                   3585: 
                   3586: sub flush_langs_cache {
                   3587:     my ($uname,$udom)=@_;
                   3588:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3589:     if (!$uname) { $uname=$env{'user.name'};   }
                   3590:     return if ($udom eq 'public' && $uname eq 'public');
                   3591:     my $id=$uname.':'.$udom;
                   3592:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3593: }
                   3594: 
1.61      www      3595: # ------------------------------------------------------------------ Screenname
1.81      albertel 3596: 
                   3597: =pod
                   3598: 
1.648     raeburn  3599: =item * &screenname($uname,$udom)
1.81      albertel 3600: 
                   3601: Gets a users screenname and returns it as a string
                   3602: 
                   3603: =cut
1.61      www      3604: 
                   3605: sub screenname {
                   3606:     my ($uname,$udom)=@_;
1.258     albertel 3607:     if ($uname eq $env{'user.name'} &&
                   3608: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3609:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3610:     return $names{'screenname'};
1.62      www      3611: }
                   3612: 
1.212     albertel 3613: 
1.802     bisitz   3614: # ------------------------------------------------------------- Confirm Wrapper
                   3615: =pod
                   3616: 
1.1075.2.42  raeburn  3617: =item * &confirmwrapper($message)
1.802     bisitz   3618: 
                   3619: Wrap messages about completion of operation in box
                   3620: 
                   3621: =cut
                   3622: 
                   3623: sub confirmwrapper {
                   3624:     my ($message)=@_;
                   3625:     if ($message) {
                   3626:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3627:                .$message."\n"
                   3628:                .'</div>'."\n";
                   3629:     } else {
                   3630:         return $message;
                   3631:     }
                   3632: }
                   3633: 
1.62      www      3634: # ------------------------------------------------------------- Message Wrapper
                   3635: 
                   3636: sub messagewrapper {
1.369     www      3637:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3638:     return 
1.441     albertel 3639:         '<a href="/adm/email?compose=individual&amp;'.
                   3640:         'recname='.$username.'&amp;recdom='.$domain.
                   3641: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3642:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3643: }
1.802     bisitz   3644: 
1.74      www      3645: # --------------------------------------------------------------- Notes Wrapper
                   3646: 
                   3647: sub noteswrapper {
                   3648:     my ($link,$un,$do)=@_;
                   3649:     return 
1.896     amueller 3650: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3651: }
1.802     bisitz   3652: 
1.62      www      3653: # ------------------------------------------------------------- Aboutme Wrapper
                   3654: 
                   3655: sub aboutmewrapper {
1.1070    raeburn  3656:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3657:     if (!defined($username)  && !defined($domain)) {
                   3658:         return;
                   3659:     }
1.1075.2.15  raeburn  3660:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3661: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3662: }
                   3663: 
                   3664: # ------------------------------------------------------------ Syllabus Wrapper
                   3665: 
                   3666: sub syllabuswrapper {
1.707     bisitz   3667:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3668:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3669: }
1.14      harris41 3670: 
1.802     bisitz   3671: # -----------------------------------------------------------------------------
                   3672: 
1.208     matthew  3673: sub track_student_link {
1.887     raeburn  3674:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3675:     my $link ="/adm/trackstudent?";
1.208     matthew  3676:     my $title = 'View recent activity';
                   3677:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3678:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3679:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3680:         $title .= ' of this student';
1.268     albertel 3681:     } 
1.208     matthew  3682:     if (defined($target) && $target !~ /^\s*$/) {
                   3683:         $target = qq{target="$target"};
                   3684:     } else {
                   3685:         $target = '';
                   3686:     }
1.268     albertel 3687:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3688:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3689:     $title = &mt($title);
                   3690:     $linktext = &mt($linktext);
1.448     albertel 3691:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3692: 	&help_open_topic('View_recent_activity');
1.208     matthew  3693: }
                   3694: 
1.781     raeburn  3695: sub slot_reservations_link {
                   3696:     my ($linktext,$sname,$sdom,$target) = @_;
                   3697:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3698:     my $title = 'View slot reservation history';
                   3699:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3700:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3701:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3702:         $title .= ' of this student';
                   3703:     }
                   3704:     if (defined($target) && $target !~ /^\s*$/) {
                   3705:         $target = qq{target="$target"};
                   3706:     } else {
                   3707:         $target = '';
                   3708:     }
                   3709:     $title = &mt($title);
                   3710:     $linktext = &mt($linktext);
                   3711:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3712: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3713: 
                   3714: }
                   3715: 
1.508     www      3716: # ===================================================== Display a student photo
                   3717: 
                   3718: 
1.509     albertel 3719: sub student_image_tag {
1.508     www      3720:     my ($domain,$user)=@_;
                   3721:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3722:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3723: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3724:     } else {
                   3725: 	return '';
                   3726:     }
                   3727: }
                   3728: 
1.112     bowersj2 3729: =pod
                   3730: 
                   3731: =back
                   3732: 
                   3733: =head1 Access .tab File Data
                   3734: 
                   3735: =over 4
                   3736: 
1.648     raeburn  3737: =item * &languageids() 
1.112     bowersj2 3738: 
                   3739: returns list of all language ids
                   3740: 
                   3741: =cut
                   3742: 
1.14      harris41 3743: sub languageids {
1.16      harris41 3744:     return sort(keys(%language));
1.14      harris41 3745: }
                   3746: 
1.112     bowersj2 3747: =pod
                   3748: 
1.648     raeburn  3749: =item * &languagedescription() 
1.112     bowersj2 3750: 
                   3751: returns description of a specified language id
                   3752: 
                   3753: =cut
                   3754: 
1.14      harris41 3755: sub languagedescription {
1.125     www      3756:     my $code=shift;
                   3757:     return  ($supported_language{$code}?'* ':'').
                   3758:             $language{$code}.
1.126     www      3759: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3760: }
                   3761: 
1.1048    foxr     3762: =pod
                   3763: 
                   3764: =item * &plainlanguagedescription
                   3765: 
                   3766: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3767: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3768: 
                   3769: =cut
                   3770: 
1.145     www      3771: sub plainlanguagedescription {
                   3772:     my $code=shift;
                   3773:     return $language{$code};
                   3774: }
                   3775: 
1.1048    foxr     3776: =pod
                   3777: 
                   3778: =item * &supportedlanguagecode
                   3779: 
                   3780: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3781: code.
                   3782: 
                   3783: =cut
                   3784: 
1.145     www      3785: sub supportedlanguagecode {
                   3786:     my $code=shift;
                   3787:     return $supported_language{$code};
1.97      www      3788: }
                   3789: 
1.112     bowersj2 3790: =pod
                   3791: 
1.1048    foxr     3792: =item * &latexlanguage()
                   3793: 
                   3794: Given a language key code returns the correspondnig language to use
                   3795: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3796: is no supported hyphenation for the language code.
                   3797: 
                   3798: =cut
                   3799: 
                   3800: sub latexlanguage {
                   3801:     my $code = shift;
                   3802:     return $latex_language{$code};
                   3803: }
                   3804: 
                   3805: =pod
                   3806: 
                   3807: =item * &latexhyphenation()
                   3808: 
                   3809: Same as above but what's supplied is the language as it might be stored
                   3810: in the metadata.
                   3811: 
                   3812: =cut
                   3813: 
                   3814: sub latexhyphenation {
                   3815:     my $key = shift;
                   3816:     return $latex_language_bykey{$key};
                   3817: }
                   3818: 
                   3819: =pod
                   3820: 
1.648     raeburn  3821: =item * &copyrightids() 
1.112     bowersj2 3822: 
                   3823: returns list of all copyrights
                   3824: 
                   3825: =cut
                   3826: 
                   3827: sub copyrightids {
                   3828:     return sort(keys(%cprtag));
                   3829: }
                   3830: 
                   3831: =pod
                   3832: 
1.648     raeburn  3833: =item * &copyrightdescription() 
1.112     bowersj2 3834: 
                   3835: returns description of a specified copyright id
                   3836: 
                   3837: =cut
                   3838: 
                   3839: sub copyrightdescription {
1.166     www      3840:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3841: }
1.197     matthew  3842: 
                   3843: =pod
                   3844: 
1.648     raeburn  3845: =item * &source_copyrightids() 
1.192     taceyjo1 3846: 
                   3847: returns list of all source copyrights
                   3848: 
                   3849: =cut
                   3850: 
                   3851: sub source_copyrightids {
                   3852:     return sort(keys(%scprtag));
                   3853: }
                   3854: 
                   3855: =pod
                   3856: 
1.648     raeburn  3857: =item * &source_copyrightdescription() 
1.192     taceyjo1 3858: 
                   3859: returns description of a specified source copyright id
                   3860: 
                   3861: =cut
                   3862: 
                   3863: sub source_copyrightdescription {
                   3864:     return &mt($scprtag{shift(@_)});
                   3865: }
1.112     bowersj2 3866: 
                   3867: =pod
                   3868: 
1.648     raeburn  3869: =item * &filecategories() 
1.112     bowersj2 3870: 
                   3871: returns list of all file categories
                   3872: 
                   3873: =cut
                   3874: 
                   3875: sub filecategories {
                   3876:     return sort(keys(%category_extensions));
                   3877: }
                   3878: 
                   3879: =pod
                   3880: 
1.648     raeburn  3881: =item * &filecategorytypes() 
1.112     bowersj2 3882: 
                   3883: returns list of file types belonging to a given file
                   3884: category
                   3885: 
                   3886: =cut
                   3887: 
                   3888: sub filecategorytypes {
1.356     albertel 3889:     my ($cat) = @_;
                   3890:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3891: }
                   3892: 
                   3893: =pod
                   3894: 
1.648     raeburn  3895: =item * &fileembstyle() 
1.112     bowersj2 3896: 
                   3897: returns embedding style for a specified file type
                   3898: 
                   3899: =cut
                   3900: 
                   3901: sub fileembstyle {
                   3902:     return $fe{lc(shift(@_))};
1.169     www      3903: }
                   3904: 
1.351     www      3905: sub filemimetype {
                   3906:     return $fm{lc(shift(@_))};
                   3907: }
                   3908: 
1.169     www      3909: 
                   3910: sub filecategoryselect {
                   3911:     my ($name,$value)=@_;
1.189     matthew  3912:     return &select_form($value,$name,
1.970     raeburn  3913:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3914: }
                   3915: 
                   3916: =pod
                   3917: 
1.648     raeburn  3918: =item * &filedescription() 
1.112     bowersj2 3919: 
                   3920: returns description for a specified file type
                   3921: 
                   3922: =cut
                   3923: 
                   3924: sub filedescription {
1.188     matthew  3925:     my $file_description = $fd{lc(shift())};
                   3926:     $file_description =~ s:([\[\]]):~$1:g;
                   3927:     return &mt($file_description);
1.112     bowersj2 3928: }
                   3929: 
                   3930: =pod
                   3931: 
1.648     raeburn  3932: =item * &filedescriptionex() 
1.112     bowersj2 3933: 
                   3934: returns description for a specified file type with
                   3935: extra formatting
                   3936: 
                   3937: =cut
                   3938: 
                   3939: sub filedescriptionex {
                   3940:     my $ex=shift;
1.188     matthew  3941:     my $file_description = $fd{lc($ex)};
                   3942:     $file_description =~ s:([\[\]]):~$1:g;
                   3943:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3944: }
                   3945: 
                   3946: # End of .tab access
                   3947: =pod
                   3948: 
                   3949: =back
                   3950: 
                   3951: =cut
                   3952: 
                   3953: # ------------------------------------------------------------------ File Types
                   3954: sub fileextensions {
                   3955:     return sort(keys(%fe));
                   3956: }
                   3957: 
1.97      www      3958: # ----------------------------------------------------------- Display Languages
                   3959: # returns a hash with all desired display languages
                   3960: #
                   3961: 
                   3962: sub display_languages {
                   3963:     my %languages=();
1.695     raeburn  3964:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3965: 	$languages{$lang}=1;
1.97      www      3966:     }
                   3967:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3968:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3969: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3970: 	    $languages{$lang}=1;
1.97      www      3971:         }
                   3972:     }
                   3973:     return %languages;
1.14      harris41 3974: }
                   3975: 
1.582     albertel 3976: sub languages {
                   3977:     my ($possible_langs) = @_;
1.695     raeburn  3978:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3979:     if (!ref($possible_langs)) {
                   3980: 	if( wantarray ) {
                   3981: 	    return @preferred_langs;
                   3982: 	} else {
                   3983: 	    return $preferred_langs[0];
                   3984: 	}
                   3985:     }
                   3986:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3987:     my @preferred_possibilities;
                   3988:     foreach my $preferred_lang (@preferred_langs) {
                   3989: 	if (exists($possibilities{$preferred_lang})) {
                   3990: 	    push(@preferred_possibilities, $preferred_lang);
                   3991: 	}
                   3992:     }
                   3993:     if( wantarray ) {
                   3994: 	return @preferred_possibilities;
                   3995:     }
                   3996:     return $preferred_possibilities[0];
                   3997: }
                   3998: 
1.742     raeburn  3999: sub user_lang {
                   4000:     my ($touname,$toudom,$fromcid) = @_;
                   4001:     my @userlangs;
                   4002:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4003:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4004:                     $env{'course.'.$fromcid.'.languages'}));
                   4005:     } else {
                   4006:         my %langhash = &getlangs($touname,$toudom);
                   4007:         if ($langhash{'languages'} ne '') {
                   4008:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4009:         } else {
                   4010:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4011:             if ($domdefs{'lang_def'} ne '') {
                   4012:                 @userlangs = ($domdefs{'lang_def'});
                   4013:             }
                   4014:         }
                   4015:     }
                   4016:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4017:     my $user_lh = Apache::localize->get_handle(@languages);
                   4018:     return $user_lh;
                   4019: }
                   4020: 
                   4021: 
1.112     bowersj2 4022: ###############################################################
                   4023: ##               Student Answer Attempts                     ##
                   4024: ###############################################################
                   4025: 
                   4026: =pod
                   4027: 
                   4028: =head1 Alternate Problem Views
                   4029: 
                   4030: =over 4
                   4031: 
1.648     raeburn  4032: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  4033:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4034: 
                   4035: Return string with previous attempt on problem. Arguments:
                   4036: 
                   4037: =over 4
                   4038: 
                   4039: =item * $symb: Problem, including path
                   4040: 
                   4041: =item * $username: username of the desired student
                   4042: 
                   4043: =item * $domain: domain of the desired student
1.14      harris41 4044: 
1.112     bowersj2 4045: =item * $course: Course ID
1.14      harris41 4046: 
1.112     bowersj2 4047: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4048:     something
1.14      harris41 4049: 
1.112     bowersj2 4050: =item * $regexp: if string matches this regexp, the string will be
                   4051:     sent to $gradesub
1.14      harris41 4052: 
1.112     bowersj2 4053: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4054: 
1.1075.2.86  raeburn  4055: =item * $usec: section of the desired student
                   4056: 
                   4057: =item * $identifier: counter for student (multiple students one problem) or
                   4058:     problem (one student; whole sequence).
                   4059: 
1.112     bowersj2 4060: =back
1.14      harris41 4061: 
1.112     bowersj2 4062: The output string is a table containing all desired attempts, if any.
1.16      harris41 4063: 
1.112     bowersj2 4064: =cut
1.1       albertel 4065: 
                   4066: sub get_previous_attempt {
1.1075.2.86  raeburn  4067:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4068:   my $prevattempts='';
1.43      ng       4069:   no strict 'refs';
1.1       albertel 4070:   if ($symb) {
1.3       albertel 4071:     my (%returnhash)=
                   4072:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4073:     if ($returnhash{'version'}) {
                   4074:       my %lasthash=();
                   4075:       my $version;
                   4076:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  4077:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4078:             if ($key =~ /\.rawrndseed$/) {
                   4079:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4080:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4081:             } else {
                   4082:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4083:             }
1.19      harris41 4084:         }
1.1       albertel 4085:       }
1.596     albertel 4086:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4087:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4088:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4089:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4090:       foreach my $key (sort(keys(%lasthash))) {
                   4091: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4092: 	if ($#parts > 0) {
1.31      albertel 4093: 	  my $data=$parts[-1];
1.989     raeburn  4094:           next if ($data eq 'foilorder');
1.31      albertel 4095: 	  pop(@parts);
1.1010    www      4096:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4097:           if ($data eq 'type') {
                   4098:               unless ($showsurv) {
                   4099:                   my $id = join(',',@parts);
                   4100:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4101:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4102:                       $lasthidden{$ign.'.'.$id} = 1;
                   4103:                   }
1.945     raeburn  4104:               }
1.1075.2.86  raeburn  4105:               if ($identifier ne '') {
                   4106:                   my $id = join(',',@parts);
                   4107:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4108:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4109:                       $hidestatus{$ign.'.'.$id} = 1;
                   4110:                   }
                   4111:               }
                   4112:           } elsif ($data eq 'regrader') {
                   4113:               if (($identifier ne '') && (@parts)) {
                   4114:                   my $id = join(',',@parts);
                   4115:                   $regraded{$ign.'.'.$id} = 1;
                   4116:               }
1.1010    www      4117:           } 
1.31      albertel 4118: 	} else {
1.41      ng       4119: 	  if ($#parts == 0) {
                   4120: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4121: 	  } else {
                   4122: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4123: 	  }
1.31      albertel 4124: 	}
1.16      harris41 4125:       }
1.596     albertel 4126:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4127:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4128:         my (%solved,%resets,%probstatus);
                   4129:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4130:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4131:                 foreach my $id (keys(%regraded)) {
                   4132:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4133:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4134:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4135:                         push(@{$resets{$id}},$version);
                   4136:                     }
                   4137:                 }
                   4138:             }
                   4139:         }
1.40      ng       4140: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4141:             my (@hidden,@unsolved);
1.945     raeburn  4142:             if (%typeparts) {
                   4143:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4144:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4145:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4146:                         push(@hidden,$id);
1.1075.2.86  raeburn  4147:                     } elsif ($identifier ne '') {
                   4148:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4149:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4150:                                 ($hidestatus{$id})) {
                   4151:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4152:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4153:                                 push(@{$solved{$id}},$version);
                   4154:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4155:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4156:                                 my $skip;
                   4157:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4158:                                     foreach my $reset (@{$resets{$id}}) {
                   4159:                                         if ($reset > $solved{$id}[-1]) {
                   4160:                                             $skip=1;
                   4161:                                             last;
                   4162:                                         }
                   4163:                                     }
                   4164:                                 }
                   4165:                                 unless ($skip) {
                   4166:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4167:                                     push(@unsolved,$partslist);
                   4168:                                 }
                   4169:                             }
                   4170:                         }
1.945     raeburn  4171:                     }
                   4172:                 }
                   4173:             }
                   4174:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4175:                            '<td>'.&mt('Transaction [_1]',$version);
                   4176:             if (@unsolved) {
                   4177:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4178:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4179:                                  &mt('Hide').'</label></span>';
                   4180:             }
                   4181:             $prevattempts .= '</td>';
1.945     raeburn  4182:             if (@hidden) {
                   4183:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4184:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4185:                     my $hide;
                   4186:                     foreach my $id (@hidden) {
                   4187:                         if ($key =~ /^\Q$id\E/) {
                   4188:                             $hide = 1;
                   4189:                             last;
                   4190:                         }
                   4191:                     }
                   4192:                     if ($hide) {
                   4193:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4194:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4195:                             my $value = &format_previous_attempt_value($key,
                   4196:                                              $returnhash{$version.':'.$key});
                   4197:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4198:                         } else {
                   4199:                             $prevattempts.='<td>&nbsp;</td>';
                   4200:                         }
                   4201:                     } else {
                   4202:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4203:                             my $value = $returnhash{$version.':'.$key};
                   4204:                             if ($key =~ /\.rndseed$/) {
                   4205:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4206:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4207:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4208:                                 }
                   4209:                             }
                   4210:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4211:                                            '&nbsp;</td>';
1.945     raeburn  4212:                         } else {
                   4213:                             $prevattempts.='<td>&nbsp;</td>';
                   4214:                         }
                   4215:                     }
                   4216:                 }
                   4217:             } else {
                   4218: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4219:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4220:                     my $value = $returnhash{$version.':'.$key};
                   4221:                     if ($key =~ /\.rndseed$/) {
                   4222:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4223:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4224:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4225:                         }
                   4226:                     }
                   4227:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4228:                                    '&nbsp;</td>';
1.945     raeburn  4229: 	        }
                   4230:             }
                   4231: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4232: 	 }
1.1       albertel 4233:       }
1.945     raeburn  4234:       my @currhidden = keys(%lasthidden);
1.596     albertel 4235:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4236:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4237:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4238:           if (%typeparts) {
                   4239:               my $hidden;
                   4240:               foreach my $id (@currhidden) {
                   4241:                   if ($key =~ /^\Q$id\E/) {
                   4242:                       $hidden = 1;
                   4243:                       last;
                   4244:                   }
                   4245:               }
                   4246:               if ($hidden) {
                   4247:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4248:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4249:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4250:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4251:                           $value = &$gradesub($value);
                   4252:                       }
                   4253:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4254:                   } else {
                   4255:                       $prevattempts.='<td>&nbsp;</td>';
                   4256:                   }
                   4257:               } else {
                   4258:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4259:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4260:                       $value = &$gradesub($value);
                   4261:                   }
                   4262:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4263:               }
                   4264:           } else {
                   4265: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4266: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4267:                   $value = &$gradesub($value);
                   4268:               }
                   4269: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4270:           }
1.16      harris41 4271:       }
1.596     albertel 4272:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4273:     } else {
1.596     albertel 4274:       $prevattempts=
                   4275: 	  &start_data_table().&start_data_table_row().
                   4276: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4277: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4278:     }
                   4279:   } else {
1.596     albertel 4280:     $prevattempts=
                   4281: 	  &start_data_table().&start_data_table_row().
                   4282: 	  '<td>'.&mt('No data.').'</td>'.
                   4283: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4284:   }
1.10      albertel 4285: }
                   4286: 
1.581     albertel 4287: sub format_previous_attempt_value {
                   4288:     my ($key,$value) = @_;
1.1011    www      4289:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4290: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4291:     } elsif (ref($value) eq 'ARRAY') {
                   4292: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4293:     } elsif ($key =~ /answerstring$/) {
                   4294:         my %answers = &Apache::lonnet::str2hash($value);
                   4295:         my @anskeys = sort(keys(%answers));
                   4296:         if (@anskeys == 1) {
                   4297:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4298:             if ($answer =~ m{\0}) {
                   4299:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4300:             }
                   4301:             my $tag_internal_answer_name = 'INTERNAL';
                   4302:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4303:                 $value = $answer; 
                   4304:             } else {
                   4305:                 $value = $anskeys[0].'='.$answer;
                   4306:             }
                   4307:         } else {
                   4308:             foreach my $ans (@anskeys) {
                   4309:                 my $answer = $answers{$ans};
1.1001    raeburn  4310:                 if ($answer =~ m{\0}) {
                   4311:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4312:                 }
                   4313:                 $value .=  $ans.'='.$answer.'<br />';;
                   4314:             } 
                   4315:         }
1.581     albertel 4316:     } else {
                   4317: 	$value = &unescape($value);
                   4318:     }
                   4319:     return $value;
                   4320: }
                   4321: 
                   4322: 
1.107     albertel 4323: sub relative_to_absolute {
                   4324:     my ($url,$output)=@_;
                   4325:     my $parser=HTML::TokeParser->new(\$output);
                   4326:     my $token;
                   4327:     my $thisdir=$url;
                   4328:     my @rlinks=();
                   4329:     while ($token=$parser->get_token) {
                   4330: 	if ($token->[0] eq 'S') {
                   4331: 	    if ($token->[1] eq 'a') {
                   4332: 		if ($token->[2]->{'href'}) {
                   4333: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4334: 		}
                   4335: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4336: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4337: 	    } elsif ($token->[1] eq 'base') {
                   4338: 		$thisdir=$token->[2]->{'href'};
                   4339: 	    }
                   4340: 	}
                   4341:     }
                   4342:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4343:     foreach my $link (@rlinks) {
1.726     raeburn  4344: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4345: 		($link=~/^\//) ||
                   4346: 		($link=~/^javascript:/i) ||
                   4347: 		($link=~/^mailto:/i) ||
                   4348: 		($link=~/^\#/)) {
                   4349: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4350: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4351: 	}
                   4352:     }
                   4353: # -------------------------------------------------- Deal with Applet codebases
                   4354:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4355:     return $output;
                   4356: }
                   4357: 
1.112     bowersj2 4358: =pod
                   4359: 
1.648     raeburn  4360: =item * &get_student_view()
1.112     bowersj2 4361: 
                   4362: show a snapshot of what student was looking at
                   4363: 
                   4364: =cut
                   4365: 
1.10      albertel 4366: sub get_student_view {
1.186     albertel 4367:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4368:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4369:   my (%form);
1.10      albertel 4370:   my @elements=('symb','courseid','domain','username');
                   4371:   foreach my $element (@elements) {
1.186     albertel 4372:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4373:   }
1.186     albertel 4374:   if (defined($moreenv)) {
                   4375:       %form=(%form,%{$moreenv});
                   4376:   }
1.236     albertel 4377:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4378:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4379:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4380:   $userview=~s/\<body[^\>]*\>//gi;
                   4381:   $userview=~s/\<\/body\>//gi;
                   4382:   $userview=~s/\<html\>//gi;
                   4383:   $userview=~s/\<\/html\>//gi;
                   4384:   $userview=~s/\<head\>//gi;
                   4385:   $userview=~s/\<\/head\>//gi;
                   4386:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4387:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4388:   if (wantarray) {
                   4389:      return ($userview,$response);
                   4390:   } else {
                   4391:      return $userview;
                   4392:   }
                   4393: }
                   4394: 
                   4395: sub get_student_view_with_retries {
                   4396:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4397: 
                   4398:     my $ok = 0;                 # True if we got a good response.
                   4399:     my $content;
                   4400:     my $response;
                   4401: 
                   4402:     # Try to get the student_view done. within the retries count:
                   4403:     
                   4404:     do {
                   4405:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4406:          $ok      = $response->is_success;
                   4407:          if (!$ok) {
                   4408:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4409:          }
                   4410:          $retries--;
                   4411:     } while (!$ok && ($retries > 0));
                   4412:     
                   4413:     if (!$ok) {
                   4414:        $content = '';          # On error return an empty content.
                   4415:     }
1.651     www      4416:     if (wantarray) {
                   4417:        return ($content, $response);
                   4418:     } else {
                   4419:        return $content;
                   4420:     }
1.11      albertel 4421: }
                   4422: 
1.1075.2.149  raeburn  4423: sub css_links {
                   4424:     my ($currsymb,$level) = @_;
                   4425:     my ($links,@symbs,%cssrefs,%httpref);
                   4426:     if ($level eq 'map') {
                   4427:         my $navmap = Apache::lonnavmaps::navmap->new();
                   4428:         if (ref($navmap)) {
                   4429:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   4430:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   4431:             foreach my $res (@resources) {
                   4432:                 if (ref($res) && $res->symb()) {
                   4433:                     push(@symbs,$res->symb());
                   4434:                 }
                   4435:             }
                   4436:         }
                   4437:     } else {
                   4438:         @symbs = ($currsymb);
                   4439:     }
                   4440:     foreach my $symb (@symbs) {
                   4441:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   4442:         if ($css_href =~ /\S/) {
                   4443:             unless ($css_href =~ m{https?://}) {
                   4444:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   4445:                 my $proburl =  &Apache::lonnet::clutter($url);
                   4446:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   4447:                 unless ($css_href =~ m{^/}) {
                   4448:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   4449:                 }
                   4450:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   4451:                     unless (($httpref{'httpref.'.$css_href}) ||
                   4452:                             (&Apache::lonnet::is_on_map($css_href))) {
                   4453:                         my $thisurl = $proburl;
                   4454:                         if ($env{'httpref.'.$proburl}) {
                   4455:                             $thisurl = $env{'httpref.'.$proburl};
                   4456:                         }
                   4457:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   4458:                     }
                   4459:                 }
                   4460:             }
                   4461:             $cssrefs{$css_href} = 1;
                   4462:         }
                   4463:     }
                   4464:     if (keys(%httpref)) {
                   4465:         &Apache::lonnet::appenv(\%httpref);
                   4466:     }
                   4467:     if (keys(%cssrefs)) {
                   4468:         foreach my $css_href (keys(%cssrefs)) {
                   4469:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   4470:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   4471:         }
                   4472:     }
                   4473:     return $links;
                   4474: }
                   4475: 
1.112     bowersj2 4476: =pod
                   4477: 
1.648     raeburn  4478: =item * &get_student_answers() 
1.112     bowersj2 4479: 
                   4480: show a snapshot of how student was answering problem
                   4481: 
                   4482: =cut
                   4483: 
1.11      albertel 4484: sub get_student_answers {
1.100     sakharuk 4485:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4486:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4487:   my (%moreenv);
1.11      albertel 4488:   my @elements=('symb','courseid','domain','username');
                   4489:   foreach my $element (@elements) {
1.186     albertel 4490:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4491:   }
1.186     albertel 4492:   $moreenv{'grade_target'}='answer';
                   4493:   %moreenv=(%form,%moreenv);
1.497     raeburn  4494:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4495:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4496:   return $userview;
1.1       albertel 4497: }
1.116     albertel 4498: 
                   4499: =pod
                   4500: 
                   4501: =item * &submlink()
                   4502: 
1.242     albertel 4503: Inputs: $text $uname $udom $symb $target
1.116     albertel 4504: 
                   4505: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4506: 
                   4507: =cut
                   4508: 
                   4509: ###############################################
                   4510: sub submlink {
1.242     albertel 4511:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4512:     if (!($uname && $udom)) {
                   4513: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4514: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4515: 	if (!$symb) { $symb=$cursymb; }
                   4516:     }
1.254     matthew  4517:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4518:     $symb=&escape($symb);
1.960     bisitz   4519:     if ($target) { $target=" target=\"$target\""; }
                   4520:     return
                   4521:         '<a href="/adm/grades?command=submission'.
                   4522:         '&amp;symb='.$symb.
                   4523:         '&amp;student='.$uname.
                   4524:         '&amp;userdom='.$udom.'"'.
                   4525:         $target.'>'.$text.'</a>';
1.242     albertel 4526: }
                   4527: ##############################################
                   4528: 
                   4529: =pod
                   4530: 
                   4531: =item * &pgrdlink()
                   4532: 
                   4533: Inputs: $text $uname $udom $symb $target
                   4534: 
                   4535: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4536: 
                   4537: =cut
                   4538: 
                   4539: ###############################################
                   4540: sub pgrdlink {
                   4541:     my $link=&submlink(@_);
                   4542:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4543:     return $link;
                   4544: }
                   4545: ##############################################
                   4546: 
                   4547: =pod
                   4548: 
                   4549: =item * &pprmlink()
                   4550: 
                   4551: Inputs: $text $uname $udom $symb $target
                   4552: 
                   4553: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4554: student and a specific resource
1.242     albertel 4555: 
                   4556: =cut
                   4557: 
                   4558: ###############################################
                   4559: sub pprmlink {
                   4560:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4561:     if (!($uname && $udom)) {
                   4562: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4563: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4564: 	if (!$symb) { $symb=$cursymb; }
                   4565:     }
1.254     matthew  4566:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4567:     $symb=&escape($symb);
1.242     albertel 4568:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4569:     return '<a href="/adm/parmset?command=set&amp;'.
                   4570: 	'symb='.$symb.'&amp;uname='.$uname.
                   4571: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4572: }
                   4573: ##############################################
1.37      matthew  4574: 
1.112     bowersj2 4575: =pod
                   4576: 
                   4577: =back
                   4578: 
                   4579: =cut
                   4580: 
1.37      matthew  4581: ###############################################
1.51      www      4582: 
                   4583: 
                   4584: sub timehash {
1.687     raeburn  4585:     my ($thistime) = @_;
                   4586:     my $timezone = &Apache::lonlocal::gettimezone();
                   4587:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4588:                      ->set_time_zone($timezone);
                   4589:     my $wday = $dt->day_of_week();
                   4590:     if ($wday == 7) { $wday = 0; }
                   4591:     return ( 'second' => $dt->second(),
                   4592:              'minute' => $dt->minute(),
                   4593:              'hour'   => $dt->hour(),
                   4594:              'day'     => $dt->day_of_month(),
                   4595:              'month'   => $dt->month(),
                   4596:              'year'    => $dt->year(),
                   4597:              'weekday' => $wday,
                   4598:              'dayyear' => $dt->day_of_year(),
                   4599:              'dlsav'   => $dt->is_dst() );
1.51      www      4600: }
                   4601: 
1.370     www      4602: sub utc_string {
                   4603:     my ($date)=@_;
1.371     www      4604:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4605: }
                   4606: 
1.51      www      4607: sub maketime {
                   4608:     my %th=@_;
1.687     raeburn  4609:     my ($epoch_time,$timezone,$dt);
                   4610:     $timezone = &Apache::lonlocal::gettimezone();
                   4611:     eval {
                   4612:         $dt = DateTime->new( year   => $th{'year'},
                   4613:                              month  => $th{'month'},
                   4614:                              day    => $th{'day'},
                   4615:                              hour   => $th{'hour'},
                   4616:                              minute => $th{'minute'},
                   4617:                              second => $th{'second'},
                   4618:                              time_zone => $timezone,
                   4619:                          );
                   4620:     };
                   4621:     if (!$@) {
                   4622:         $epoch_time = $dt->epoch;
                   4623:         if ($epoch_time) {
                   4624:             return $epoch_time;
                   4625:         }
                   4626:     }
1.51      www      4627:     return POSIX::mktime(
                   4628:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4629:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4630: }
                   4631: 
                   4632: #########################################
1.51      www      4633: 
                   4634: sub findallcourses {
1.482     raeburn  4635:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4636:     my %roles;
                   4637:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4638:     my %courses;
1.51      www      4639:     my $now=time;
1.482     raeburn  4640:     if (!defined($uname)) {
                   4641:         $uname = $env{'user.name'};
                   4642:     }
                   4643:     if (!defined($udom)) {
                   4644:         $udom = $env{'user.domain'};
                   4645:     }
                   4646:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4647:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4648:         if (!%roles) {
                   4649:             %roles = (
                   4650:                        cc => 1,
1.907     raeburn  4651:                        co => 1,
1.482     raeburn  4652:                        in => 1,
                   4653:                        ep => 1,
                   4654:                        ta => 1,
                   4655:                        cr => 1,
                   4656:                        st => 1,
                   4657:              );
                   4658:         }
                   4659:         foreach my $entry (keys(%roleshash)) {
                   4660:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4661:             if ($trole =~ /^cr/) { 
                   4662:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4663:             } else {
                   4664:                 next if (!exists($roles{$trole}));
                   4665:             }
                   4666:             if ($tend) {
                   4667:                 next if ($tend < $now);
                   4668:             }
                   4669:             if ($tstart) {
                   4670:                 next if ($tstart > $now);
                   4671:             }
1.1058    raeburn  4672:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4673:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4674:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4675:             if ($secpart eq '') {
                   4676:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4677:                 $sec = 'none';
1.1058    raeburn  4678:                 $value .= $cnum.'/';
1.482     raeburn  4679:             } else {
                   4680:                 $cnum = $cnumpart;
                   4681:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4682:                 $value .= $cnum.'/'.$sec;
                   4683:             }
                   4684:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4685:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4686:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4687:                 }
                   4688:             } else {
                   4689:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4690:             }
1.482     raeburn  4691:         }
                   4692:     } else {
                   4693:         foreach my $key (keys(%env)) {
1.483     albertel 4694: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4695:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4696: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4697: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4698: 	        next if (%roles && !exists($roles{$role}));
                   4699: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4700:                 my $active=1;
                   4701:                 if ($starttime) {
                   4702: 		    if ($now<$starttime) { $active=0; }
                   4703:                 }
                   4704:                 if ($endtime) {
                   4705:                     if ($now>$endtime) { $active=0; }
                   4706:                 }
                   4707:                 if ($active) {
1.1058    raeburn  4708:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4709:                     if ($sec eq '') {
                   4710:                         $sec = 'none';
1.1058    raeburn  4711:                     } else {
                   4712:                         $value .= $sec;
                   4713:                     }
                   4714:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4715:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4716:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4717:                         }
                   4718:                     } else {
                   4719:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4720:                     }
1.474     raeburn  4721:                 }
                   4722:             }
1.51      www      4723:         }
                   4724:     }
1.474     raeburn  4725:     return %courses;
1.51      www      4726: }
1.37      matthew  4727: 
1.54      www      4728: ###############################################
1.474     raeburn  4729: 
                   4730: sub blockcheck {
1.1075.2.158  raeburn  4731:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.490     raeburn  4732: 
1.1075.2.158  raeburn  4733:     unless ($activity eq 'docs') {
                   4734:         my ($has_evb,$check_ipaccess);
                   4735:         my $dom = $env{'user.domain'};
                   4736:         if ($env{'request.course.id'}) {
                   4737:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4738:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4739:             my $checkrole = "cm./$cdom/$cnum";
                   4740:             my $sec = $env{'request.course.sec'};
                   4741:             if ($sec ne '') {
                   4742:                 $checkrole .= "/$sec";
                   4743:             }
                   4744:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   4745:                 ($env{'request.role'} !~ /^st/)) {
                   4746:                 $has_evb = 1;
                   4747:             }
                   4748:             unless ($has_evb) {
                   4749:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   4750:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   4751:                     if ($udom eq $cdom) {
                   4752:                         $check_ipaccess = 1;
                   4753:                     }
                   4754:                 }
                   4755:             }
                   4756:         }
                   4757:         unless ($has_evb || $check_ipaccess) {
                   4758:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   4759:             if (($dom eq 'public') && ($activity eq 'port')) {
                   4760:                 $dom = $udom;
                   4761:             }
                   4762:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   4763:                 $check_ipaccess = 1;
                   4764:             } else {
                   4765:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   4766:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   4767:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   4768:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   4769:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   4770:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   4771:                         $check_ipaccess = 1;
                   4772:                     }
                   4773:                 }
                   4774:             }
                   4775:         }
                   4776:         if ($check_ipaccess) {
                   4777:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   4778:             unless (defined($cached)) {
                   4779:                 my %domconfig =
                   4780:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   4781:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   4782:             }
                   4783:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   4784:                 foreach my $id (keys(%{$ipaccessref})) {
                   4785:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   4786:                         my $range = $ipaccessref->{$id}->{'ip'};
                   4787:                         if ($range) {
                   4788:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   4789:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   4790:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   4791:                                         return ('','','',$id,$dom);
                   4792:                                         last;
                   4793:                                     }
                   4794:                                 }
                   4795:                             }
                   4796:                         }
                   4797:                     }
                   4798:                 }
                   4799:             }
                   4800:         }
                   4801:     }
1.1075.2.73  raeburn  4802:     if (defined($udom) && defined($uname)) {
                   4803:         # If uname and udom are for a course, check for blocks in the course.
                   4804:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4805:             my ($startblock,$endblock,$triggerblock) =
1.1075.2.147  raeburn  4806:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1075.2.73  raeburn  4807:             return ($startblock,$endblock,$triggerblock);
                   4808:         }
                   4809:     } else {
1.490     raeburn  4810:         $udom = $env{'user.domain'};
                   4811:         $uname = $env{'user.name'};
                   4812:     }
                   4813: 
1.502     raeburn  4814:     my $startblock = 0;
                   4815:     my $endblock = 0;
1.1062    raeburn  4816:     my $triggerblock = '';
1.1075.2.160  raeburn  4817:     my %live_courses;
                   4818:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   4819:         %live_courses = &findallcourses(undef,$uname,$udom);
                   4820:     }
1.474     raeburn  4821: 
1.490     raeburn  4822:     # If uname is for a user, and activity is course-specific, i.e.,
                   4823:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4824: 
1.490     raeburn  4825:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.73  raeburn  4826:          $activity eq 'groups' || $activity eq 'printout') &&
                   4827:         ($env{'request.course.id'})) {
1.490     raeburn  4828:         foreach my $key (keys(%live_courses)) {
                   4829:             if ($key ne $env{'request.course.id'}) {
                   4830:                 delete($live_courses{$key});
                   4831:             }
                   4832:         }
                   4833:     }
                   4834: 
                   4835:     my $otheruser = 0;
                   4836:     my %own_courses;
                   4837:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4838:         # Resource belongs to user other than current user.
                   4839:         $otheruser = 1;
                   4840:         # Gather courses for current user
                   4841:         %own_courses = 
                   4842:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4843:     }
                   4844: 
                   4845:     # Gather active course roles - course coordinator, instructor, 
                   4846:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4847: 
                   4848:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4849:         my ($cdom,$cnum);
                   4850:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4851:             $cdom = $env{'course.'.$course.'.domain'};
                   4852:             $cnum = $env{'course.'.$course.'.num'};
                   4853:         } else {
1.490     raeburn  4854:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4855:         }
                   4856:         my $no_ownblock = 0;
                   4857:         my $no_userblock = 0;
1.533     raeburn  4858:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4859:             # Check if current user has 'evb' priv for this
                   4860:             if (defined($own_courses{$course})) {
                   4861:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4862:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4863:                     if ($sec ne 'none') {
                   4864:                         $checkrole .= '/'.$sec;
                   4865:                     }
                   4866:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4867:                         $no_ownblock = 1;
                   4868:                         last;
                   4869:                     }
                   4870:                 }
                   4871:             }
                   4872:             # if they have 'evb' priv and are currently not playing student
                   4873:             next if (($no_ownblock) &&
                   4874:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4875:         }
1.474     raeburn  4876:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4877:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4878:             if ($sec ne 'none') {
1.482     raeburn  4879:                 $checkrole .= '/'.$sec;
1.474     raeburn  4880:             }
1.490     raeburn  4881:             if ($otheruser) {
                   4882:                 # Resource belongs to user other than current user.
                   4883:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4884:                 my (%allroles,%userroles);
                   4885:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4886:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4887:                         my ($trole,$tdom,$tnum,$tsec);
                   4888:                         if ($entry =~ /^cr/) {
                   4889:                             ($trole,$tdom,$tnum,$tsec) = 
                   4890:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4891:                         } else {
                   4892:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4893:                         }
                   4894:                         my ($spec,$area,$trest);
                   4895:                         $area = '/'.$tdom.'/'.$tnum;
                   4896:                         $trest = $tnum;
                   4897:                         if ($tsec ne '') {
                   4898:                             $area .= '/'.$tsec;
                   4899:                             $trest .= '/'.$tsec;
                   4900:                         }
                   4901:                         $spec = $trole.'.'.$area;
                   4902:                         if ($trole =~ /^cr/) {
                   4903:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4904:                                                               $tdom,$spec,$trest,$area);
                   4905:                         } else {
                   4906:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4907:                                                                 $tdom,$spec,$trest,$area);
                   4908:                         }
                   4909:                     }
1.1075.2.124  raeburn  4910:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  4911:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4912:                         if ($1) {
                   4913:                             $no_userblock = 1;
                   4914:                             last;
                   4915:                         }
1.486     raeburn  4916:                     }
                   4917:                 }
1.490     raeburn  4918:             } else {
                   4919:                 # Resource belongs to current user
                   4920:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4921:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4922:                     $no_ownblock = 1;
                   4923:                     last;
                   4924:                 }
1.474     raeburn  4925:             }
                   4926:         }
                   4927:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4928:         next if (($no_ownblock) &&
1.491     albertel 4929:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4930:         next if ($no_userblock);
1.474     raeburn  4931: 
1.1075.2.128  raeburn  4932:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  4933:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4934:         
1.1062    raeburn  4935:         my ($start,$end,$trigger) = 
1.1075.2.147  raeburn  4936:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  4937:         if (($start != 0) && 
                   4938:             (($startblock == 0) || ($startblock > $start))) {
                   4939:             $startblock = $start;
1.1062    raeburn  4940:             if ($trigger ne '') {
                   4941:                 $triggerblock = $trigger;
                   4942:             }
1.502     raeburn  4943:         }
                   4944:         if (($end != 0)  &&
                   4945:             (($endblock == 0) || ($endblock < $end))) {
                   4946:             $endblock = $end;
1.1062    raeburn  4947:             if ($trigger ne '') {
                   4948:                 $triggerblock = $trigger;
                   4949:             }
1.502     raeburn  4950:         }
1.490     raeburn  4951:     }
1.1062    raeburn  4952:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4953: }
                   4954: 
                   4955: sub get_blocks {
1.1075.2.147  raeburn  4956:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  4957:     my $startblock = 0;
                   4958:     my $endblock = 0;
1.1062    raeburn  4959:     my $triggerblock = '';
1.490     raeburn  4960:     my $course = $cdom.'_'.$cnum;
                   4961:     $setters->{$course} = {};
                   4962:     $setters->{$course}{'staff'} = [];
                   4963:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4964:     $setters->{$course}{'triggers'} = [];
                   4965:     my (@blockers,%triggered);
                   4966:     my $now = time;
                   4967:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4968:     if ($activity eq 'docs') {
1.1075.2.148  raeburn  4969:         my ($blocked,$nosymbcache,$noenccheck);
1.1075.2.147  raeburn  4970:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   4971:             $blocked = 1;
                   4972:             $nosymbcache = 1;
1.1075.2.148  raeburn  4973:             $noenccheck = 1;
1.1075.2.147  raeburn  4974:         }
1.1075.2.148  raeburn  4975:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  4976:         foreach my $block (@blockers) {
                   4977:             if ($block =~ /^firstaccess____(.+)$/) {
                   4978:                 my $item = $1;
                   4979:                 my $type = 'map';
                   4980:                 my $timersymb = $item;
                   4981:                 if ($item eq 'course') {
                   4982:                     $type = 'course';
                   4983:                 } elsif ($item =~ /___\d+___/) {
                   4984:                     $type = 'resource';
                   4985:                 } else {
                   4986:                     $timersymb = &Apache::lonnet::symbread($item);
                   4987:                 }
                   4988:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4989:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4990:                 $triggered{$block} = {
                   4991:                                        start => $start,
                   4992:                                        end   => $end,
                   4993:                                        type  => $type,
                   4994:                                      };
                   4995:             }
                   4996:         }
                   4997:     } else {
                   4998:         foreach my $block (keys(%commblocks)) {
                   4999:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5000:                 my ($start,$end) = ($1,$2);
                   5001:                 if ($start <= time && $end >= time) {
                   5002:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5003:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5004:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5005:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5006:                                     push(@blockers,$block);
                   5007:                                 }
                   5008:                             }
                   5009:                         }
                   5010:                     }
                   5011:                 }
                   5012:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5013:                 my $item = $1;
                   5014:                 my $timersymb = $item; 
                   5015:                 my $type = 'map';
                   5016:                 if ($item eq 'course') {
                   5017:                     $type = 'course';
                   5018:                 } elsif ($item =~ /___\d+___/) {
                   5019:                     $type = 'resource';
                   5020:                 } else {
                   5021:                     $timersymb = &Apache::lonnet::symbread($item);
                   5022:                 }
                   5023:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5024:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5025:                 if ($start && $end) {
                   5026:                     if (($start <= time) && ($end >= time)) {
1.1075.2.158  raeburn  5027:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5028:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5029:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5030:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5031:                                         push(@blockers,$block);
                   5032:                                         $triggered{$block} = {
                   5033:                                                                start => $start,
                   5034:                                                                end   => $end,
                   5035:                                                                type  => $type,
                   5036:                                                              };
                   5037:                                     }
                   5038:                                 }
                   5039:                             }
1.1062    raeburn  5040:                         }
                   5041:                     }
1.490     raeburn  5042:                 }
1.1062    raeburn  5043:             }
                   5044:         }
                   5045:     }
                   5046:     foreach my $blocker (@blockers) {
                   5047:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5048:             &parse_block_record($commblocks{$blocker});
                   5049:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5050:         my ($start,$end,$triggertype);
                   5051:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5052:             ($start,$end) = ($1,$2);
                   5053:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5054:             $start = $triggered{$blocker}{'start'};
                   5055:             $end = $triggered{$blocker}{'end'};
                   5056:             $triggertype = $triggered{$blocker}{'type'};
                   5057:         }
                   5058:         if ($start) {
                   5059:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5060:             if ($triggertype) {
                   5061:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5062:             } else {
                   5063:                 push(@{$$setters{$course}{'triggers'}},0);
                   5064:             }
                   5065:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5066:                 $startblock = $start;
                   5067:                 if ($triggertype) {
                   5068:                     $triggerblock = $blocker;
1.474     raeburn  5069:                 }
                   5070:             }
1.1062    raeburn  5071:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5072:                $endblock = $end;
                   5073:                if ($triggertype) {
                   5074:                    $triggerblock = $blocker;
                   5075:                }
                   5076:             }
1.474     raeburn  5077:         }
                   5078:     }
1.1062    raeburn  5079:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5080: }
                   5081: 
                   5082: sub parse_block_record {
                   5083:     my ($record) = @_;
                   5084:     my ($setuname,$setudom,$title,$blocks);
                   5085:     if (ref($record) eq 'HASH') {
                   5086:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5087:         $title = &unescape($record->{'event'});
                   5088:         $blocks = $record->{'blocks'};
                   5089:     } else {
                   5090:         my @data = split(/:/,$record,3);
                   5091:         if (scalar(@data) eq 2) {
                   5092:             $title = $data[1];
                   5093:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5094:         } else {
                   5095:             ($setuname,$setudom,$title) = @data;
                   5096:         }
                   5097:         $blocks = { 'com' => 'on' };
                   5098:     }
                   5099:     return ($setuname,$setudom,$title,$blocks);
                   5100: }
                   5101: 
1.854     kalberla 5102: sub blocking_status {
1.1075.2.158  raeburn  5103:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5104:     my %setters;
1.890     droeschl 5105: 
1.1061    raeburn  5106: # check for active blocking
1.1075.2.158  raeburn  5107:     if ($clientip eq '') {
                   5108:         $clientip = &Apache::lonnet::get_requestor_ip();
                   5109:     }
                   5110:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   5111:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5112:     my $blocked = 0;
1.1075.2.158  raeburn  5113:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5114:         $blocked = 1;
                   5115:     }
1.890     droeschl 5116: 
1.1061    raeburn  5117: # caller just wants to know whether a block is active
                   5118:     if (!wantarray) { return $blocked; }
                   5119: 
                   5120: # build a link to a popup window containing the details
                   5121:     my $querystring  = "?activity=$activity";
1.1075.2.158  raeburn  5122: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5123:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1075.2.97  raeburn  5124:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   5125:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5126:     } elsif ($activity eq 'docs') {
1.1075.2.147  raeburn  5127:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5128:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5129:         if ($symb) {
                   5130:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5131:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5132:         }
1.1062    raeburn  5133:     }
1.1061    raeburn  5134: 
                   5135:     my $output .= <<'END_MYBLOCK';
                   5136: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5137:     var options = "width=" + w + ",height=" + h + ",";
                   5138:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5139:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5140:     var newWin = window.open(url, wdwName, options);
                   5141:     newWin.focus();
                   5142: }
1.890     droeschl 5143: END_MYBLOCK
1.854     kalberla 5144: 
1.1061    raeburn  5145:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5146:   
1.1061    raeburn  5147:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5148:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  5149:     my $class = 'LC_comblock';
1.1062    raeburn  5150:     if ($activity eq 'docs') {
                   5151:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  5152:         $class = '';
1.1063    raeburn  5153:     } elsif ($activity eq 'printout') {
                   5154:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  5155:     } elsif ($activity eq 'passwd') {
                   5156:         $text = &mt('Password Changing Blocked');
1.1075.2.158  raeburn  5157:     } elsif ($activity eq 'grades') {
                   5158:         $text = &mt('Gradebook Blocked');
                   5159:     } elsif ($activity eq 'search') {
                   5160:         $text = &mt('Search Blocked');
                   5161:     } elsif ($activity eq 'about') {
                   5162:         $text = &mt('Access to User Information Pages Blocked');
1.1075.2.160  raeburn  5163:     } elsif ($activity eq 'wishlist') {
                   5164:         $text = &mt('Access to Stored Links Blocked');
                   5165:     } elsif ($activity eq 'annotate') {
                   5166:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  5167:     }
1.1061    raeburn  5168:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  5169: <div class='$class'>
1.869     kalberla 5170:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5171:   title='$text'>
                   5172:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5173:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5174:   title='$text'>$text</a>
1.867     kalberla 5175: </div>
                   5176: 
                   5177: END_BLOCK
1.474     raeburn  5178: 
1.1061    raeburn  5179:     return ($blocked, $output);
1.854     kalberla 5180: }
1.490     raeburn  5181: 
1.60      matthew  5182: ###############################################
                   5183: 
1.682     raeburn  5184: sub check_ip_acc {
1.1075.2.105  raeburn  5185:     my ($acc,$clientip)=@_;
1.682     raeburn  5186:     &Apache::lonxml::debug("acc is $acc");
                   5187:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5188:         return 1;
                   5189:     }
                   5190:     my $allowed=0;
1.1075.2.144  raeburn  5191:     my $ip;
                   5192:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5193:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5194:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5195:     } else {
1.1075.2.150  raeburn  5196:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5197:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1075.2.144  raeburn  5198:     }
1.682     raeburn  5199: 
                   5200:     my $name;
                   5201:     foreach my $pattern (split(',',$acc)) {
                   5202:         $pattern =~ s/^\s*//;
                   5203:         $pattern =~ s/\s*$//;
                   5204:         if ($pattern =~ /\*$/) {
                   5205:             #35.8.*
                   5206:             $pattern=~s/\*//;
                   5207:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   5208:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5209:             #35.8.3.[34-56]
                   5210:             my $low=$2;
                   5211:             my $high=$3;
                   5212:             $pattern=$1;
                   5213:             if ($ip =~ /^\Q$pattern\E/) {
                   5214:                 my $last=(split(/\./,$ip))[3];
                   5215:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   5216:             }
                   5217:         } elsif ($pattern =~ /^\*/) {
                   5218:             #*.msu.edu
                   5219:             $pattern=~s/\*//;
                   5220:             if (!defined($name)) {
                   5221:                 use Socket;
                   5222:                 my $netaddr=inet_aton($ip);
                   5223:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5224:             }
                   5225:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   5226:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5227:             #127.0.0.1
                   5228:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   5229:         } else {
                   5230:             #some.name.com
                   5231:             if (!defined($name)) {
                   5232:                 use Socket;
                   5233:                 my $netaddr=inet_aton($ip);
                   5234:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5235:             }
                   5236:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   5237:         }
                   5238:         if ($allowed) { last; }
                   5239:     }
                   5240:     return $allowed;
                   5241: }
                   5242: 
                   5243: ###############################################
                   5244: 
1.60      matthew  5245: =pod
                   5246: 
1.112     bowersj2 5247: =head1 Domain Template Functions
                   5248: 
                   5249: =over 4
                   5250: 
                   5251: =item * &determinedomain()
1.60      matthew  5252: 
                   5253: Inputs: $domain (usually will be undef)
                   5254: 
1.63      www      5255: Returns: Determines which domain should be used for designs
1.60      matthew  5256: 
                   5257: =cut
1.54      www      5258: 
1.60      matthew  5259: ###############################################
1.63      www      5260: sub determinedomain {
                   5261:     my $domain=shift;
1.531     albertel 5262:     if (! $domain) {
1.60      matthew  5263:         # Determine domain if we have not been given one
1.893     raeburn  5264:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5265:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5266:         if ($env{'request.role.domain'}) { 
                   5267:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5268:         }
                   5269:     }
1.63      www      5270:     return $domain;
                   5271: }
                   5272: ###############################################
1.517     raeburn  5273: 
1.518     albertel 5274: sub devalidate_domconfig_cache {
                   5275:     my ($udom)=@_;
                   5276:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5277: }
                   5278: 
                   5279: # ---------------------- Get domain configuration for a domain
                   5280: sub get_domainconf {
                   5281:     my ($udom) = @_;
                   5282:     my $cachetime=1800;
                   5283:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5284:     if (defined($cached)) { return %{$result}; }
                   5285: 
                   5286:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5287: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5288:     my (%designhash,%legacy);
1.518     albertel 5289:     if (keys(%domconfig) > 0) {
                   5290:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5291:             if (keys(%{$domconfig{'login'}})) {
                   5292:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5293:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5294:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5295:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5296:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5297:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5298:                                         if ($key eq 'loginvia') {
                   5299:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5300:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5301:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5302:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5303:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5304:                                                 } else {
                   5305:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5306:                                                 }
1.948     raeburn  5307:                                             }
1.1075.2.87  raeburn  5308:                                         } elsif ($key eq 'headtag') {
                   5309:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5310:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5311:                                             }
1.946     raeburn  5312:                                         }
1.1075.2.87  raeburn  5313:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5314:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5315:                                         }
1.946     raeburn  5316:                                     }
                   5317:                                 }
                   5318:                             }
1.1075.2.158  raeburn  5319:                         } elsif ($key eq 'saml') {
                   5320:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5321:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   5322:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   5323:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
                   5324:                                         foreach my $item ('text','img','alt','url','title','notsso') {
                   5325:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   5326:                                         }
                   5327:                                     }
                   5328:                                 }
                   5329:                             }
1.946     raeburn  5330:                         } else {
                   5331:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5332:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5333:                                     $domconfig{'login'}{$key}{$img};
                   5334:                             }
1.699     raeburn  5335:                         }
                   5336:                     } else {
                   5337:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5338:                     }
1.632     raeburn  5339:                 }
                   5340:             } else {
                   5341:                 $legacy{'login'} = 1;
1.518     albertel 5342:             }
1.632     raeburn  5343:         } else {
                   5344:             $legacy{'login'} = 1;
1.518     albertel 5345:         }
                   5346:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5347:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5348:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5349:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5350:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5351:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5352:                         }
1.518     albertel 5353:                     }
                   5354:                 }
1.632     raeburn  5355:             } else {
                   5356:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5357:             }
1.632     raeburn  5358:         } else {
                   5359:             $legacy{'rolecolors'} = 1;
1.518     albertel 5360:         }
1.948     raeburn  5361:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5362:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5363:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5364:             }
                   5365:         }
1.632     raeburn  5366:         if (keys(%legacy) > 0) {
                   5367:             my %legacyhash = &get_legacy_domconf($udom);
                   5368:             foreach my $item (keys(%legacyhash)) {
                   5369:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5370:                     if ($legacy{'login'}) { 
                   5371:                         $designhash{$item} = $legacyhash{$item};
                   5372:                     }
                   5373:                 } else {
                   5374:                     if ($legacy{'rolecolors'}) {
                   5375:                         $designhash{$item} = $legacyhash{$item};
                   5376:                     }
1.518     albertel 5377:                 }
                   5378:             }
                   5379:         }
1.632     raeburn  5380:     } else {
                   5381:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5382:     }
                   5383:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5384: 				  $cachetime);
                   5385:     return %designhash;
                   5386: }
                   5387: 
1.632     raeburn  5388: sub get_legacy_domconf {
                   5389:     my ($udom) = @_;
                   5390:     my %legacyhash;
                   5391:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5392:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5393:     if (-e $designfile) {
1.1075.2.128  raeburn  5394:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5395:             while (my $line = <$fh>) {
                   5396:                 next if ($line =~ /^\#/);
                   5397:                 chomp($line);
                   5398:                 my ($key,$val)=(split(/\=/,$line));
                   5399:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5400:             }
                   5401:             close($fh);
                   5402:         }
                   5403:     }
1.1026    raeburn  5404:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5405:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5406:     }
                   5407:     return %legacyhash;
                   5408: }
                   5409: 
1.63      www      5410: =pod
                   5411: 
1.112     bowersj2 5412: =item * &domainlogo()
1.63      www      5413: 
                   5414: Inputs: $domain (usually will be undef)
                   5415: 
                   5416: Returns: A link to a domain logo, if the domain logo exists.
                   5417: If the domain logo does not exist, a description of the domain.
                   5418: 
                   5419: =cut
1.112     bowersj2 5420: 
1.63      www      5421: ###############################################
                   5422: sub domainlogo {
1.517     raeburn  5423:     my $domain = &determinedomain(shift);
1.518     albertel 5424:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5425:     # See if there is a logo
                   5426:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5427:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5428:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5429: 	    if ($imgsrc =~ m{^/res/}) {
                   5430: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5431: 		&Apache::lonnet::repcopy($local_name);
                   5432: 	    }
                   5433: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1075.2.162! raeburn  5434:         }
        !          5435:         my $alttext = $domain;
        !          5436:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
        !          5437:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
        !          5438:         }
        !          5439:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 5440:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5441:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5442:     } else {
1.60      matthew  5443:         return '';
1.59      www      5444:     }
                   5445: }
1.63      www      5446: ##############################################
                   5447: 
                   5448: =pod
                   5449: 
1.112     bowersj2 5450: =item * &designparm()
1.63      www      5451: 
                   5452: Inputs: $which parameter; $domain (usually will be undef)
                   5453: 
                   5454: Returns: value of designparamter $which
                   5455: 
                   5456: =cut
1.112     bowersj2 5457: 
1.397     albertel 5458: 
1.400     albertel 5459: ##############################################
1.397     albertel 5460: sub designparm {
                   5461:     my ($which,$domain)=@_;
                   5462:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5463:         return $env{'environment.color.'.$which};
1.96      www      5464:     }
1.63      www      5465:     $domain=&determinedomain($domain);
1.1016    raeburn  5466:     my %domdesign;
                   5467:     unless ($domain eq 'public') {
                   5468:         %domdesign = &get_domainconf($domain);
                   5469:     }
1.520     raeburn  5470:     my $output;
1.517     raeburn  5471:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5472:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5473:     } else {
1.520     raeburn  5474:         $output = $defaultdesign{$which};
                   5475:     }
                   5476:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5477:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5478:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5479:             if ($output =~ m{^/res/}) {
                   5480:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5481:                 &Apache::lonnet::repcopy($local_name);
                   5482:             }
1.520     raeburn  5483:             $output = &lonhttpdurl($output);
                   5484:         }
1.63      www      5485:     }
1.520     raeburn  5486:     return $output;
1.63      www      5487: }
1.59      www      5488: 
1.822     bisitz   5489: ##############################################
                   5490: =pod
                   5491: 
1.832     bisitz   5492: =item * &authorspace()
                   5493: 
1.1028    raeburn  5494: Inputs: $url (usually will be undef).
1.832     bisitz   5495: 
1.1075.2.40  raeburn  5496: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5497:          directory being viewed (or for which action is being taken). 
                   5498:          If $url is provided, and begins /priv/<domain>/<uname>
                   5499:          the path will be that portion of the $context argument.
                   5500:          Otherwise the path will be for the author space of the current
                   5501:          user when the current role is author, or for that of the 
                   5502:          co-author/assistant co-author space when the current role 
                   5503:          is co-author or assistant co-author.
1.832     bisitz   5504: 
                   5505: =cut
                   5506: 
                   5507: sub authorspace {
1.1028    raeburn  5508:     my ($url) = @_;
                   5509:     if ($url ne '') {
                   5510:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5511:            return $1;
                   5512:         }
                   5513:     }
1.832     bisitz   5514:     my $caname = '';
1.1024    www      5515:     my $cadom = '';
1.1028    raeburn  5516:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5517:         ($cadom,$caname) =
1.832     bisitz   5518:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5519:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5520:         $caname = $env{'user.name'};
1.1024    www      5521:         $cadom = $env{'user.domain'};
1.832     bisitz   5522:     }
1.1028    raeburn  5523:     if (($caname ne '') && ($cadom ne '')) {
                   5524:         return "/priv/$cadom/$caname/";
                   5525:     }
                   5526:     return;
1.832     bisitz   5527: }
                   5528: 
                   5529: ##############################################
                   5530: =pod
                   5531: 
1.822     bisitz   5532: =item * &head_subbox()
                   5533: 
                   5534: Inputs: $content (contains HTML code with page functions, etc.)
                   5535: 
                   5536: Returns: HTML div with $content
                   5537:          To be included in page header
                   5538: 
                   5539: =cut
                   5540: 
                   5541: sub head_subbox {
                   5542:     my ($content)=@_;
                   5543:     my $output =
1.993     raeburn  5544:         '<div class="LC_head_subbox">'
1.822     bisitz   5545:        .$content
                   5546:        .'</div>'
                   5547: }
                   5548: 
                   5549: ##############################################
                   5550: =pod
                   5551: 
                   5552: =item * &CSTR_pageheader()
                   5553: 
1.1026    raeburn  5554: Input: (optional) filename from which breadcrumb trail is built.
                   5555:        In most cases no input as needed, as $env{'request.filename'}
                   5556:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5557: 
                   5558: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5559:          To be included on Authoring Space pages
1.822     bisitz   5560: 
                   5561: =cut
                   5562: 
                   5563: sub CSTR_pageheader {
1.1026    raeburn  5564:     my ($trailfile) = @_;
                   5565:     if ($trailfile eq '') {
                   5566:         $trailfile = $env{'request.filename'};
                   5567:     }
                   5568: 
                   5569: # this is for resources; directories have customtitle, and crumbs
                   5570: # and select recent are created in lonpubdir.pm
                   5571: 
                   5572:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5573:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5574:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5575:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5576:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5577: 
                   5578:     my $parentpath = '';
                   5579:     my $lastitem = '';
                   5580:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5581:         $parentpath = $1;
                   5582:         $lastitem = $2;
                   5583:     } else {
                   5584:         $lastitem = $thisdisfn;
                   5585:     }
1.921     bisitz   5586: 
                   5587:     my $output =
1.822     bisitz   5588:          '<div>'
                   5589:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5590:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5591:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5592:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5593:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5594: 
                   5595:     if ($lastitem) {
                   5596:         $output .=
                   5597:              '<span class="LC_filename">'
                   5598:             .$lastitem
                   5599:             .'</span>';
                   5600:     }
                   5601:     $output .=
                   5602:          '<br />'
1.822     bisitz   5603:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5604:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5605:         .'</form>'
                   5606:         .&Apache::lonmenu::constspaceform()
                   5607:         .'</div>';
1.921     bisitz   5608: 
                   5609:     return $output;
1.822     bisitz   5610: }
                   5611: 
1.60      matthew  5612: ###############################################
                   5613: ###############################################
                   5614: 
                   5615: =pod
                   5616: 
1.112     bowersj2 5617: =back
                   5618: 
1.549     albertel 5619: =head1 HTML Helpers
1.112     bowersj2 5620: 
                   5621: =over 4
                   5622: 
                   5623: =item * &bodytag()
1.60      matthew  5624: 
                   5625: Returns a uniform header for LON-CAPA web pages.
                   5626: 
                   5627: Inputs: 
                   5628: 
1.112     bowersj2 5629: =over 4
                   5630: 
                   5631: =item * $title, A title to be displayed on the page.
                   5632: 
                   5633: =item * $function, the current role (can be undef).
                   5634: 
                   5635: =item * $addentries, extra parameters for the <body> tag.
                   5636: 
                   5637: =item * $bodyonly, if defined, only return the <body> tag.
                   5638: 
                   5639: =item * $domain, if defined, force a given domain.
                   5640: 
                   5641: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5642:             text interface only)
1.60      matthew  5643: 
1.814     bisitz   5644: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5645:                      navigational links
1.317     albertel 5646: 
1.338     albertel 5647: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5648: 
1.1075.2.12  raeburn  5649: =item * $no_inline_link, if true and in remote mode, don't show the
                   5650:          'Switch To Inline Menu' link
                   5651: 
1.460     albertel 5652: =item * $args, optional argument valid values are
                   5653:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1075.2.133  raeburn  5654:             use_absolute     -> for external resource or syllabus, this will
                   5655:                                 contain https://<hostname> if server uses
                   5656:                                 https (as per hosts.tab), but request is for http
                   5657:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5658: 
1.1075.2.15  raeburn  5659: =item * $advtoolsref, optional argument, ref to an array containing
                   5660:             inlineremote items to be added in "Functions" menu below
                   5661:             breadcrumbs.
                   5662: 
1.112     bowersj2 5663: =back
                   5664: 
1.60      matthew  5665: Returns: A uniform header for LON-CAPA web pages.  
                   5666: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5667: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5668: other decorations will be returned.
                   5669: 
                   5670: =cut
                   5671: 
1.54      www      5672: sub bodytag {
1.831     bisitz   5673:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5674:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5675: 
1.954     raeburn  5676:     my $public;
                   5677:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5678:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5679:         $public = 1;
                   5680:     }
1.460     albertel 5681:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5682:     my $httphost = $args->{'use_absolute'};
1.1075.2.133  raeburn  5683:     my $hostname = $args->{'hostname'};
1.339     albertel 5684: 
1.183     matthew  5685:     $function = &get_users_function() if (!$function);
1.339     albertel 5686:     my $img =    &designparm($function.'.img',$domain);
                   5687:     my $font =   &designparm($function.'.font',$domain);
                   5688:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5689: 
1.803     bisitz   5690:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5691: 		   'bgcolor' => $pgbg,
1.339     albertel 5692: 		   'text'    => $font,
                   5693:                    'alink'   => &designparm($function.'.alink',$domain),
                   5694: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5695: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5696:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5697: 
1.63      www      5698:  # role and realm
1.1075.2.68  raeburn  5699:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5700:     if ($realm) {
                   5701:         $realm = '/'.$realm;
                   5702:     }
1.1075.2.159  raeburn  5703:     if ($role eq 'ca') {
1.479     albertel 5704:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5705:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5706:     } 
1.55      www      5707: # realm
1.1075.2.158  raeburn  5708:     my ($cid,$sec);
1.258     albertel 5709:     if ($env{'request.course.id'}) {
1.1075.2.158  raeburn  5710:         $cid = $env{'request.course.id'};
                   5711:         if ($env{'request.course.sec'}) {
                   5712:             $sec = $env{'request.course.sec'};
                   5713:         }
                   5714:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   5715:         if (&Apache::lonnet::is_course($1,$2)) {
                   5716:             $cid = $1.'_'.$2;
                   5717:             $sec = $3;
                   5718:         }
                   5719:     }
                   5720:     if ($cid) {
1.378     raeburn  5721:         if ($env{'request.role'} !~ /^cr/) {
                   5722:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  5723:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  5724:             if ($env{'request.role.desc'}) {
                   5725:                 $role = $env{'request.role.desc'};
                   5726:             } else {
                   5727:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5728:             }
1.1075.2.115  raeburn  5729:         } else {
                   5730:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  5731:         }
1.1075.2.158  raeburn  5732:         if ($sec) {
                   5733:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  5734:         }   
1.1075.2.158  raeburn  5735: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  5736:     } else {
                   5737:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5738:     }
1.433     albertel 5739: 
1.359     albertel 5740:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5741: 
1.438     albertel 5742:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5743: 
1.101     www      5744: # construct main body tag
1.359     albertel 5745:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  5746: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5747: 
1.1075.2.38  raeburn  5748:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5749: 
                   5750:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5751:         return $bodytag;
1.1075.2.38  raeburn  5752:     }
1.359     albertel 5753: 
1.954     raeburn  5754:     if ($public) {
1.433     albertel 5755: 	undef($role);
                   5756:     }
1.1075.2.158  raeburn  5757: 
1.762     bisitz   5758:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5759:     #
                   5760:     # Extra info if you are the DC
                   5761:     my $dc_info = '';
1.1075.2.159  raeburn  5762:     if (($env{'user.adv'}) && ($env{'request.course.id'}) &&
1.1075.2.158  raeburn  5763:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  5764:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5765:         $dc_info =~ s/\s+$//;
1.359     albertel 5766:     }
                   5767: 
1.1075.2.108  raeburn  5768:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 5769: 
1.1075.2.13  raeburn  5770:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5771: 
1.1075.2.38  raeburn  5772: 
                   5773: 
1.1075.2.21  raeburn  5774:     my $funclist;
                   5775:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5776:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5777:                     Apache::lonmenu::serverform();
                   5778:         my $forbodytag;
                   5779:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5780:                                             $forcereg,$args->{'group'},
                   5781:                                             $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5782:                                             $advtoolsref,'','',\$forbodytag);
1.1075.2.21  raeburn  5783:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5784:             $funclist = $forbodytag;
                   5785:         }
                   5786:     } else {
1.903     droeschl 5787: 
                   5788:         #    if ($env{'request.state'} eq 'construct') {
                   5789:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5790:         #    }
                   5791: 
1.1075.2.38  raeburn  5792:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5793:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5794: 
1.1075.2.158  raeburn  5795:         my ($left,$right) = Apache::lonmenu::primary_menu($args->{'links_disabled'});
1.1075.2.2  raeburn  5796: 
1.916     droeschl 5797:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5798:             if ($dc_info) {
1.1075.2.158  raeburn  5799:                 $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5800:             }
1.1075.2.38  raeburn  5801:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5802:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5803:             return $bodytag;
                   5804:         }
1.894     droeschl 5805: 
1.927     raeburn  5806:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5807:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5808:         }
1.916     droeschl 5809: 
1.1075.2.38  raeburn  5810:         $bodytag .= $right;
1.852     droeschl 5811: 
1.917     raeburn  5812:         if ($dc_info) {
                   5813:             $dc_info = &dc_courseid_toggle($dc_info);
                   5814:         }
                   5815:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5816: 
1.1075.2.61  raeburn  5817:         #if directed to not display the secondary menu, don't.
                   5818:         if ($args->{'no_secondary_menu'}) {
                   5819:             return $bodytag;
                   5820:         }
1.903     droeschl 5821:         #don't show menus for public users
1.954     raeburn  5822:         if (!$public){
1.1075.2.158  raeburn  5823:             $bodytag .= Apache::lonmenu::secondary_menu($httphost,$args->{'links_disabled'});
1.903     droeschl 5824:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5825:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5826:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5827:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1075.2.133  raeburn  5828:                                 $args->{'bread_crumbs'},'','',$hostname);
1.1075.2.116  raeburn  5829:             } elsif ($forcereg) {
1.1075.2.22  raeburn  5830:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.116  raeburn  5831:                                                             $args->{'group'},
1.1075.2.161  raeburn  5832:                                                             $args->{'hide_buttons'},
                   5833:                                                             $hostname);
1.1075.2.15  raeburn  5834:             } else {
1.1075.2.21  raeburn  5835:                 my $forbodytag;
                   5836:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5837:                                                     $forcereg,$args->{'group'},
                   5838:                                                     $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5839:                                                     $advtoolsref,'',$hostname,
                   5840:                                                     \$forbodytag);
1.1075.2.21  raeburn  5841:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5842:                     $bodytag .= $forbodytag;
                   5843:                 }
1.920     raeburn  5844:             }
1.903     droeschl 5845:         }else{
                   5846:             # this is to seperate menu from content when there's no secondary
                   5847:             # menu. Especially needed for public accessible ressources.
                   5848:             $bodytag .= '<hr style="clear:both" />';
                   5849:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5850:         }
1.903     droeschl 5851: 
1.235     raeburn  5852:         return $bodytag;
1.1075.2.12  raeburn  5853:     }
                   5854: 
                   5855: #
                   5856: # Top frame rendering, Remote is up
                   5857: #
                   5858: 
                   5859:     my $imgsrc = $img;
                   5860:     if ($img =~ /^\/adm/) {
                   5861:         $imgsrc = &lonhttpdurl($img);
                   5862:     }
                   5863:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5864: 
1.1075.2.60  raeburn  5865:     my $help=($no_inline_link?''
                   5866:               :&Apache::loncommon::top_nav_help('Help'));
                   5867: 
1.1075.2.12  raeburn  5868:     # Explicit link to get inline menu
                   5869:     my $menu= ($no_inline_link?''
                   5870:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5871: 
                   5872:     if ($dc_info) {
                   5873:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5874:     }
                   5875: 
1.1075.2.38  raeburn  5876:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5877:     unless ($public) {
                   5878:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5879:                                 undef,'LC_menubuttons_link');
                   5880:     }
                   5881: 
1.1075.2.12  raeburn  5882:     unless ($env{'form.inhibitmenu'}) {
                   5883:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5884:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5885:                        <li>$help</li>
1.1075.2.12  raeburn  5886:                        <li>$menu</li>
                   5887:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5888:     }
1.1075.2.13  raeburn  5889:     if ($env{'request.state'} eq 'construct') {
                   5890:         if (!$public){
                   5891:             if ($env{'request.state'} eq 'construct') {
                   5892:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5893:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5894:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5895:                             &Apache::lonmenu::innerregister($forcereg,
                   5896:                                                             $args->{'bread_crumbs'});
                   5897:             }
                   5898:         }
                   5899:     }
1.1075.2.21  raeburn  5900:     return $bodytag."\n".$funclist;
1.182     matthew  5901: }
                   5902: 
1.917     raeburn  5903: sub dc_courseid_toggle {
                   5904:     my ($dc_info) = @_;
1.980     raeburn  5905:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5906:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5907:            &mt('(More ...)').'</a></span>'.
                   5908:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5909: }
                   5910: 
1.330     albertel 5911: sub make_attr_string {
                   5912:     my ($register,$attr_ref) = @_;
                   5913: 
                   5914:     if ($attr_ref && !ref($attr_ref)) {
                   5915: 	die("addentries Must be a hash ref ".
                   5916: 	    join(':',caller(1))." ".
                   5917: 	    join(':',caller(0))." ");
                   5918:     }
                   5919: 
                   5920:     if ($register) {
1.339     albertel 5921: 	my ($on_load,$on_unload);
                   5922: 	foreach my $key (keys(%{$attr_ref})) {
                   5923: 	    if      (lc($key) eq 'onload') {
                   5924: 		$on_load.=$attr_ref->{$key}.';';
                   5925: 		delete($attr_ref->{$key});
                   5926: 
                   5927: 	    } elsif (lc($key) eq 'onunload') {
                   5928: 		$on_unload.=$attr_ref->{$key}.';';
                   5929: 		delete($attr_ref->{$key});
                   5930: 	    }
                   5931: 	}
1.1075.2.12  raeburn  5932:         if ($env{'environment.remote'} eq 'on') {
                   5933:             $attr_ref->{'onload'}  =
                   5934:                 &Apache::lonmenu::loadevents().  $on_load;
                   5935:             $attr_ref->{'onunload'}=
                   5936:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5937:         } else {  
                   5938: 	    $attr_ref->{'onload'}  = $on_load;
                   5939: 	    $attr_ref->{'onunload'}= $on_unload;
                   5940:         }
1.330     albertel 5941:     }
1.339     albertel 5942: 
1.330     albertel 5943:     my $attr_string;
1.1075.2.56  raeburn  5944:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5945: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5946:     }
                   5947:     return $attr_string;
                   5948: }
                   5949: 
                   5950: 
1.182     matthew  5951: ###############################################
1.251     albertel 5952: ###############################################
                   5953: 
                   5954: =pod
                   5955: 
                   5956: =item * &endbodytag()
                   5957: 
                   5958: Returns a uniform footer for LON-CAPA web pages.
                   5959: 
1.635     raeburn  5960: Inputs: 1 - optional reference to an args hash
                   5961: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5962: a 'Continue' link is not displayed if the page contains an
                   5963: internal redirect in the <head></head> section,
                   5964: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5965: 
                   5966: =cut
                   5967: 
                   5968: sub endbodytag {
1.635     raeburn  5969:     my ($args) = @_;
1.1075.2.6  raeburn  5970:     my $endbodytag;
                   5971:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5972:         $endbodytag='</body>';
                   5973:     }
1.315     albertel 5974:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5975:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5976: 	    $endbodytag=
                   5977: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5978: 	        &mt('Continue').'</a>'.
                   5979: 	        $endbodytag;
                   5980:         }
1.315     albertel 5981:     }
1.251     albertel 5982:     return $endbodytag;
                   5983: }
                   5984: 
1.352     albertel 5985: =pod
                   5986: 
                   5987: =item * &standard_css()
                   5988: 
                   5989: Returns a style sheet
                   5990: 
                   5991: Inputs: (all optional)
                   5992:             domain         -> force to color decorate a page for a specific
                   5993:                                domain
                   5994:             function       -> force usage of a specific rolish color scheme
                   5995:             bgcolor        -> override the default page bgcolor
                   5996: 
                   5997: =cut
                   5998: 
1.343     albertel 5999: sub standard_css {
1.345     albertel 6000:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6001:     $function  = &get_users_function() if (!$function);
                   6002:     my $img    = &designparm($function.'.img',   $domain);
                   6003:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6004:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6005:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6006: #second colour for later usage
1.345     albertel 6007:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6008:     my $pgbg_or_bgcolor =
                   6009: 	         $bgcolor ||
1.352     albertel 6010: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6011:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6012:     my $alink  = &designparm($function.'.alink', $domain);
                   6013:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6014:     my $link   = &designparm($function.'.link',  $domain);
                   6015: 
1.602     albertel 6016:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6017:     my $mono                 = 'monospace';
1.850     bisitz   6018:     my $data_table_head      = $sidebg;
                   6019:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6020:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6021:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6022:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6023:     my $mail_new             = '#FFBB77';
                   6024:     my $mail_new_hover       = '#DD9955';
                   6025:     my $mail_read            = '#BBBB77';
                   6026:     my $mail_read_hover      = '#999944';
                   6027:     my $mail_replied         = '#AAAA88';
                   6028:     my $mail_replied_hover   = '#888855';
                   6029:     my $mail_other           = '#99BBBB';
                   6030:     my $mail_other_hover     = '#669999';
1.391     albertel 6031:     my $table_header         = '#DDDDDD';
1.489     raeburn  6032:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6033:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6034:     my $button_hover         = '#BF2317';
1.392     albertel 6035: 
1.608     albertel 6036:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6037:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6038:                                              : '0 3px 0 4px';
1.448     albertel 6039: 
1.523     albertel 6040: 
1.343     albertel 6041:     return <<END;
1.947     droeschl 6042: 
                   6043: /* needed for iframe to allow 100% height in FF */
                   6044: body, html { 
                   6045:     margin: 0;
                   6046:     padding: 0 0.5%;
                   6047:     height: 99%; /* to avoid scrollbars */
                   6048: }
                   6049: 
1.795     www      6050: body {
1.911     bisitz   6051:   font-family: $sans;
                   6052:   line-height:130%;
                   6053:   font-size:0.83em;
                   6054:   color:$font;
1.795     www      6055: }
                   6056: 
1.959     onken    6057: a:focus,
                   6058: a:focus img {
1.795     www      6059:   color: red;
                   6060: }
1.698     harmsja  6061: 
1.911     bisitz   6062: form, .inline {
                   6063:   display: inline;
1.795     www      6064: }
1.721     harmsja  6065: 
1.795     www      6066: .LC_right {
1.911     bisitz   6067:   text-align:right;
1.795     www      6068: }
                   6069: 
                   6070: .LC_middle {
1.911     bisitz   6071:   vertical-align:middle;
1.795     www      6072: }
1.721     harmsja  6073: 
1.1075.2.38  raeburn  6074: .LC_floatleft {
                   6075:   float: left;
                   6076: }
                   6077: 
                   6078: .LC_floatright {
                   6079:   float: right;
                   6080: }
                   6081: 
1.911     bisitz   6082: .LC_400Box {
                   6083:   width:400px;
                   6084: }
1.721     harmsja  6085: 
1.947     droeschl 6086: .LC_iframecontainer {
                   6087:     width: 98%;
                   6088:     margin: 0;
                   6089:     position: fixed;
                   6090:     top: 8.5em;
                   6091:     bottom: 0;
                   6092: }
                   6093: 
                   6094: .LC_iframecontainer iframe{
                   6095:     border: none;
                   6096:     width: 100%;
                   6097:     height: 100%;
                   6098: }
                   6099: 
1.778     bisitz   6100: .LC_filename {
                   6101:   font-family: $mono;
                   6102:   white-space:pre;
1.921     bisitz   6103:   font-size: 120%;
1.778     bisitz   6104: }
                   6105: 
                   6106: .LC_fileicon {
                   6107:   border: none;
                   6108:   height: 1.3em;
                   6109:   vertical-align: text-bottom;
                   6110:   margin-right: 0.3em;
                   6111:   text-decoration:none;
                   6112: }
                   6113: 
1.1008    www      6114: .LC_setting {
                   6115:   text-decoration:underline;
                   6116: }
                   6117: 
1.350     albertel 6118: .LC_error {
                   6119:   color: red;
                   6120: }
1.795     www      6121: 
1.1075.2.15  raeburn  6122: .LC_warning {
                   6123:   color: darkorange;
                   6124: }
                   6125: 
1.457     albertel 6126: .LC_diff_removed {
1.733     bisitz   6127:   color: red;
1.394     albertel 6128: }
1.532     albertel 6129: 
                   6130: .LC_info,
1.457     albertel 6131: .LC_success,
                   6132: .LC_diff_added {
1.350     albertel 6133:   color: green;
                   6134: }
1.795     www      6135: 
1.802     bisitz   6136: div.LC_confirm_box {
                   6137:   background-color: #FAFAFA;
                   6138:   border: 1px solid $lg_border_color;
                   6139:   margin-right: 0;
                   6140:   padding: 5px;
                   6141: }
                   6142: 
                   6143: div.LC_confirm_box .LC_error img,
                   6144: div.LC_confirm_box .LC_success img {
                   6145:   vertical-align: middle;
                   6146: }
                   6147: 
1.1075.2.108  raeburn  6148: .LC_maxwidth {
                   6149:   max-width: 100%;
                   6150:   height: auto;
                   6151: }
                   6152: 
                   6153: .LC_textsize_mobile {
                   6154:   \@media only screen and (max-device-width: 480px) {
                   6155:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6156:   }
                   6157: }
                   6158: 
1.440     albertel 6159: .LC_icon {
1.771     droeschl 6160:   border: none;
1.790     droeschl 6161:   vertical-align: middle;
1.771     droeschl 6162: }
                   6163: 
1.543     albertel 6164: .LC_docs_spacer {
                   6165:   width: 25px;
                   6166:   height: 1px;
1.771     droeschl 6167:   border: none;
1.543     albertel 6168: }
1.346     albertel 6169: 
1.532     albertel 6170: .LC_internal_info {
1.735     bisitz   6171:   color: #999999;
1.532     albertel 6172: }
                   6173: 
1.794     www      6174: .LC_discussion {
1.1050    www      6175:   background: $data_table_dark;
1.911     bisitz   6176:   border: 1px solid black;
                   6177:   margin: 2px;
1.794     www      6178: }
                   6179: 
                   6180: .LC_disc_action_left {
1.1050    www      6181:   background: $sidebg;
1.911     bisitz   6182:   text-align: left;
1.1050    www      6183:   padding: 4px;
                   6184:   margin: 2px;
1.794     www      6185: }
                   6186: 
                   6187: .LC_disc_action_right {
1.1050    www      6188:   background: $sidebg;
1.911     bisitz   6189:   text-align: right;
1.1050    www      6190:   padding: 4px;
                   6191:   margin: 2px;
1.794     www      6192: }
                   6193: 
                   6194: .LC_disc_new_item {
1.911     bisitz   6195:   background: white;
                   6196:   border: 2px solid red;
1.1050    www      6197:   margin: 4px;
                   6198:   padding: 4px;
1.794     www      6199: }
                   6200: 
                   6201: .LC_disc_old_item {
1.911     bisitz   6202:   background: white;
1.1050    www      6203:   margin: 4px;
                   6204:   padding: 4px;
1.794     www      6205: }
                   6206: 
1.458     albertel 6207: table.LC_pastsubmission {
                   6208:   border: 1px solid black;
                   6209:   margin: 2px;
                   6210: }
                   6211: 
1.924     bisitz   6212: table#LC_menubuttons {
1.345     albertel 6213:   width: 100%;
                   6214:   background: $pgbg;
1.392     albertel 6215:   border: 2px;
1.402     albertel 6216:   border-collapse: separate;
1.803     bisitz   6217:   padding: 0;
1.345     albertel 6218: }
1.392     albertel 6219: 
1.801     tempelho 6220: table#LC_title_bar a {
                   6221:   color: $fontmenu;
                   6222: }
1.836     bisitz   6223: 
1.807     droeschl 6224: table#LC_title_bar {
1.819     tempelho 6225:   clear: both;
1.836     bisitz   6226:   display: none;
1.807     droeschl 6227: }
                   6228: 
1.795     www      6229: table#LC_title_bar,
1.933     droeschl 6230: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6231: table#LC_title_bar.LC_with_remote {
1.359     albertel 6232:   width: 100%;
1.392     albertel 6233:   border-color: $pgbg;
                   6234:   border-style: solid;
                   6235:   border-width: $border;
1.379     albertel 6236:   background: $pgbg;
1.801     tempelho 6237:   color: $fontmenu;
1.392     albertel 6238:   border-collapse: collapse;
1.803     bisitz   6239:   padding: 0;
1.819     tempelho 6240:   margin: 0;
1.359     albertel 6241: }
1.795     www      6242: 
1.933     droeschl 6243: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6244:     margin: 0;
                   6245:     padding: 0;
1.933     droeschl 6246:     position: relative;
                   6247:     list-style: none;
1.913     droeschl 6248: }
1.933     droeschl 6249: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6250:     display: inline;
                   6251: }
1.933     droeschl 6252: 
                   6253: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6254:     padding: 0;
1.933     droeschl 6255:     margin: 0;
                   6256:     float: left;
1.913     droeschl 6257: }
1.933     droeschl 6258: .LC_breadcrumb_tools_tools {
                   6259:     padding: 0;
                   6260:     margin: 0;
1.913     droeschl 6261:     float: right;
                   6262: }
                   6263: 
1.359     albertel 6264: table#LC_title_bar td {
                   6265:   background: $tabbg;
                   6266: }
1.795     www      6267: 
1.911     bisitz   6268: table#LC_menubuttons img {
1.803     bisitz   6269:   border: none;
1.346     albertel 6270: }
1.795     www      6271: 
1.842     droeschl 6272: .LC_breadcrumbs_component {
1.911     bisitz   6273:   float: right;
                   6274:   margin: 0 1em;
1.357     albertel 6275: }
1.842     droeschl 6276: .LC_breadcrumbs_component img {
1.911     bisitz   6277:   vertical-align: middle;
1.777     tempelho 6278: }
1.795     www      6279: 
1.1075.2.108  raeburn  6280: .LC_breadcrumbs_hoverable {
                   6281:   background: $sidebg;
                   6282: }
                   6283: 
1.383     albertel 6284: td.LC_table_cell_checkbox {
                   6285:   text-align: center;
                   6286: }
1.795     www      6287: 
                   6288: .LC_fontsize_small {
1.911     bisitz   6289:   font-size: 70%;
1.705     tempelho 6290: }
                   6291: 
1.844     bisitz   6292: #LC_breadcrumbs {
1.911     bisitz   6293:   clear:both;
                   6294:   background: $sidebg;
                   6295:   border-bottom: 1px solid $lg_border_color;
                   6296:   line-height: 2.5em;
1.933     droeschl 6297:   overflow: hidden;
1.911     bisitz   6298:   margin: 0;
                   6299:   padding: 0;
1.995     raeburn  6300:   text-align: left;
1.819     tempelho 6301: }
1.862     bisitz   6302: 
1.1075.2.16  raeburn  6303: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6304:   clear:both;
                   6305:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6306:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6307:   margin: 0 0 10px 0;
1.966     bisitz   6308:   padding: 3px;
1.995     raeburn  6309:   text-align: left;
1.822     bisitz   6310: }
                   6311: 
1.795     www      6312: .LC_fontsize_medium {
1.911     bisitz   6313:   font-size: 85%;
1.705     tempelho 6314: }
                   6315: 
1.795     www      6316: .LC_fontsize_large {
1.911     bisitz   6317:   font-size: 120%;
1.705     tempelho 6318: }
                   6319: 
1.346     albertel 6320: .LC_menubuttons_inline_text {
                   6321:   color: $font;
1.698     harmsja  6322:   font-size: 90%;
1.701     harmsja  6323:   padding-left:3px;
1.346     albertel 6324: }
                   6325: 
1.934     droeschl 6326: .LC_menubuttons_inline_text img{
                   6327:   vertical-align: middle;
                   6328: }
                   6329: 
1.1051    www      6330: li.LC_menubuttons_inline_text img {
1.951     onken    6331:   cursor:pointer;
1.1002    droeschl 6332:   text-decoration: none;
1.951     onken    6333: }
                   6334: 
1.526     www      6335: .LC_menubuttons_link {
                   6336:   text-decoration: none;
                   6337: }
1.795     www      6338: 
1.522     albertel 6339: .LC_menubuttons_category {
1.521     www      6340:   color: $font;
1.526     www      6341:   background: $pgbg;
1.521     www      6342:   font-size: larger;
                   6343:   font-weight: bold;
                   6344: }
                   6345: 
1.346     albertel 6346: td.LC_menubuttons_text {
1.911     bisitz   6347:   color: $font;
1.346     albertel 6348: }
1.706     harmsja  6349: 
1.346     albertel 6350: .LC_current_location {
                   6351:   background: $tabbg;
                   6352: }
1.795     www      6353: 
1.1075.2.134  raeburn  6354: td.LC_zero_height {
                   6355:   line-height: 0;
                   6356:   cellpadding: 0;
                   6357: }
                   6358: 
1.938     bisitz   6359: table.LC_data_table {
1.347     albertel 6360:   border: 1px solid #000000;
1.402     albertel 6361:   border-collapse: separate;
1.426     albertel 6362:   border-spacing: 1px;
1.610     albertel 6363:   background: $pgbg;
1.347     albertel 6364: }
1.795     www      6365: 
1.422     albertel 6366: .LC_data_table_dense {
                   6367:   font-size: small;
                   6368: }
1.795     www      6369: 
1.507     raeburn  6370: table.LC_nested_outer {
                   6371:   border: 1px solid #000000;
1.589     raeburn  6372:   border-collapse: collapse;
1.803     bisitz   6373:   border-spacing: 0;
1.507     raeburn  6374:   width: 100%;
                   6375: }
1.795     www      6376: 
1.879     raeburn  6377: table.LC_innerpickbox,
1.507     raeburn  6378: table.LC_nested {
1.803     bisitz   6379:   border: none;
1.589     raeburn  6380:   border-collapse: collapse;
1.803     bisitz   6381:   border-spacing: 0;
1.507     raeburn  6382:   width: 100%;
                   6383: }
1.795     www      6384: 
1.911     bisitz   6385: table.LC_data_table tr th,
                   6386: table.LC_calendar tr th,
1.879     raeburn  6387: table.LC_prior_tries tr th,
                   6388: table.LC_innerpickbox tr th {
1.349     albertel 6389:   font-weight: bold;
                   6390:   background-color: $data_table_head;
1.801     tempelho 6391:   color:$fontmenu;
1.701     harmsja  6392:   font-size:90%;
1.347     albertel 6393: }
1.795     www      6394: 
1.879     raeburn  6395: table.LC_innerpickbox tr th,
                   6396: table.LC_innerpickbox tr td {
                   6397:   vertical-align: top;
                   6398: }
                   6399: 
1.711     raeburn  6400: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6401:   background-color: #CCCCCC;
1.711     raeburn  6402:   font-weight: bold;
                   6403:   text-align: left;
                   6404: }
1.795     www      6405: 
1.912     bisitz   6406: table.LC_data_table tr.LC_odd_row > td {
                   6407:   background-color: $data_table_light;
                   6408:   padding: 2px;
                   6409:   vertical-align: top;
                   6410: }
                   6411: 
1.809     bisitz   6412: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6413:   background-color: $data_table_light;
1.912     bisitz   6414:   vertical-align: top;
                   6415: }
                   6416: 
                   6417: table.LC_data_table tr.LC_even_row > td {
                   6418:   background-color: $data_table_dark;
1.425     albertel 6419:   padding: 2px;
1.900     bisitz   6420:   vertical-align: top;
1.347     albertel 6421: }
1.795     www      6422: 
1.809     bisitz   6423: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6424:   background-color: $data_table_dark;
1.900     bisitz   6425:   vertical-align: top;
1.347     albertel 6426: }
1.795     www      6427: 
1.425     albertel 6428: table.LC_data_table tr.LC_data_table_highlight td {
                   6429:   background-color: $data_table_darker;
                   6430: }
1.795     www      6431: 
1.639     raeburn  6432: table.LC_data_table tr td.LC_leftcol_header {
                   6433:   background-color: $data_table_head;
                   6434:   font-weight: bold;
                   6435: }
1.795     www      6436: 
1.451     albertel 6437: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6438: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6439:   font-weight: bold;
                   6440:   font-style: italic;
                   6441:   text-align: center;
                   6442:   padding: 8px;
1.347     albertel 6443: }
1.795     www      6444: 
1.1075.2.30  raeburn  6445: table.LC_data_table tr.LC_empty_row td,
                   6446: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6447:   background-color: $sidebg;
                   6448: }
                   6449: 
                   6450: table.LC_nested tr.LC_empty_row td {
                   6451:   background-color: #FFFFFF;
                   6452: }
                   6453: 
1.890     droeschl 6454: table.LC_caption {
                   6455: }
                   6456: 
1.507     raeburn  6457: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6458:   padding: 4ex
                   6459: }
1.795     www      6460: 
1.507     raeburn  6461: table.LC_nested_outer tr th {
                   6462:   font-weight: bold;
1.801     tempelho 6463:   color:$fontmenu;
1.507     raeburn  6464:   background-color: $data_table_head;
1.701     harmsja  6465:   font-size: small;
1.507     raeburn  6466:   border-bottom: 1px solid #000000;
                   6467: }
1.795     www      6468: 
1.507     raeburn  6469: table.LC_nested_outer tr td.LC_subheader {
                   6470:   background-color: $data_table_head;
                   6471:   font-weight: bold;
                   6472:   font-size: small;
                   6473:   border-bottom: 1px solid #000000;
                   6474:   text-align: right;
1.451     albertel 6475: }
1.795     www      6476: 
1.507     raeburn  6477: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6478:   background-color: #CCCCCC;
1.451     albertel 6479:   font-weight: bold;
                   6480:   font-size: small;
1.507     raeburn  6481:   text-align: center;
                   6482: }
1.795     www      6483: 
1.589     raeburn  6484: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6485: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6486:   text-align: left;
1.451     albertel 6487: }
1.795     www      6488: 
1.507     raeburn  6489: table.LC_nested td {
1.735     bisitz   6490:   background-color: #FFFFFF;
1.451     albertel 6491:   font-size: small;
1.507     raeburn  6492: }
1.795     www      6493: 
1.507     raeburn  6494: table.LC_nested_outer tr th.LC_right_item,
                   6495: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6496: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6497: table.LC_nested tr td.LC_right_item {
1.451     albertel 6498:   text-align: right;
                   6499: }
                   6500: 
1.507     raeburn  6501: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6502:   background-color: #EEEEEE;
1.451     albertel 6503: }
                   6504: 
1.473     raeburn  6505: table.LC_createuser {
                   6506: }
                   6507: 
                   6508: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6509:   font-size: small;
1.473     raeburn  6510: }
                   6511: 
                   6512: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6513:   background-color: #CCCCCC;
1.473     raeburn  6514:   font-weight: bold;
                   6515:   text-align: center;
                   6516: }
                   6517: 
1.349     albertel 6518: table.LC_calendar {
                   6519:   border: 1px solid #000000;
                   6520:   border-collapse: collapse;
1.917     raeburn  6521:   width: 98%;
1.349     albertel 6522: }
1.795     www      6523: 
1.349     albertel 6524: table.LC_calendar_pickdate {
                   6525:   font-size: xx-small;
                   6526: }
1.795     www      6527: 
1.349     albertel 6528: table.LC_calendar tr td {
                   6529:   border: 1px solid #000000;
                   6530:   vertical-align: top;
1.917     raeburn  6531:   width: 14%;
1.349     albertel 6532: }
1.795     www      6533: 
1.349     albertel 6534: table.LC_calendar tr td.LC_calendar_day_empty {
                   6535:   background-color: $data_table_dark;
                   6536: }
1.795     www      6537: 
1.779     bisitz   6538: table.LC_calendar tr td.LC_calendar_day_current {
                   6539:   background-color: $data_table_highlight;
1.777     tempelho 6540: }
1.795     www      6541: 
1.938     bisitz   6542: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6543:   background-color: $mail_new;
                   6544: }
1.795     www      6545: 
1.938     bisitz   6546: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6547:   background-color: $mail_new_hover;
                   6548: }
1.795     www      6549: 
1.938     bisitz   6550: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6551:   background-color: $mail_read;
                   6552: }
1.795     www      6553: 
1.938     bisitz   6554: /*
                   6555: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6556:   background-color: $mail_read_hover;
                   6557: }
1.938     bisitz   6558: */
1.795     www      6559: 
1.938     bisitz   6560: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6561:   background-color: $mail_replied;
                   6562: }
1.795     www      6563: 
1.938     bisitz   6564: /*
                   6565: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6566:   background-color: $mail_replied_hover;
                   6567: }
1.938     bisitz   6568: */
1.795     www      6569: 
1.938     bisitz   6570: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6571:   background-color: $mail_other;
                   6572: }
1.795     www      6573: 
1.938     bisitz   6574: /*
                   6575: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6576:   background-color: $mail_other_hover;
                   6577: }
1.938     bisitz   6578: */
1.494     raeburn  6579: 
1.777     tempelho 6580: table.LC_data_table tr > td.LC_browser_file,
                   6581: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6582:   background: #AAEE77;
1.389     albertel 6583: }
1.795     www      6584: 
1.777     tempelho 6585: table.LC_data_table tr > td.LC_browser_file_locked,
                   6586: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6587:   background: #FFAA99;
1.387     albertel 6588: }
1.795     www      6589: 
1.777     tempelho 6590: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6591:   background: #888888;
1.779     bisitz   6592: }
1.795     www      6593: 
1.777     tempelho 6594: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6595: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6596:   background: #F8F866;
1.777     tempelho 6597: }
1.795     www      6598: 
1.696     bisitz   6599: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6600:   background: #E0E8FF;
1.387     albertel 6601: }
1.696     bisitz   6602: 
1.707     bisitz   6603: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6604:   /* background: #77FF77; */
1.707     bisitz   6605: }
1.795     www      6606: 
1.707     bisitz   6607: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6608:   border-right: 8px solid #FFFF77;
1.707     bisitz   6609: }
1.795     www      6610: 
1.707     bisitz   6611: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6612:   border-right: 8px solid #FFAA77;
1.707     bisitz   6613: }
1.795     www      6614: 
1.707     bisitz   6615: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6616:   border-right: 8px solid #FF7777;
1.707     bisitz   6617: }
1.795     www      6618: 
1.707     bisitz   6619: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6620:   border-right: 8px solid #AAFF77;
1.707     bisitz   6621: }
1.795     www      6622: 
1.707     bisitz   6623: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6624:   border-right: 8px solid #11CC55;
1.707     bisitz   6625: }
                   6626: 
1.388     albertel 6627: span.LC_current_location {
1.701     harmsja  6628:   font-size:larger;
1.388     albertel 6629:   background: $pgbg;
                   6630: }
1.387     albertel 6631: 
1.1029    www      6632: span.LC_current_nav_location {
                   6633:   font-weight:bold;
                   6634:   background: $sidebg;
                   6635: }
                   6636: 
1.395     albertel 6637: span.LC_parm_menu_item {
                   6638:   font-size: larger;
                   6639: }
1.795     www      6640: 
1.395     albertel 6641: span.LC_parm_scope_all {
                   6642:   color: red;
                   6643: }
1.795     www      6644: 
1.395     albertel 6645: span.LC_parm_scope_folder {
                   6646:   color: green;
                   6647: }
1.795     www      6648: 
1.395     albertel 6649: span.LC_parm_scope_resource {
                   6650:   color: orange;
                   6651: }
1.795     www      6652: 
1.395     albertel 6653: span.LC_parm_part {
                   6654:   color: blue;
                   6655: }
1.795     www      6656: 
1.911     bisitz   6657: span.LC_parm_folder,
                   6658: span.LC_parm_symb {
1.395     albertel 6659:   font-size: x-small;
                   6660:   font-family: $mono;
                   6661:   color: #AAAAAA;
                   6662: }
                   6663: 
1.977     bisitz   6664: ul.LC_parm_parmlist li {
                   6665:   display: inline-block;
                   6666:   padding: 0.3em 0.8em;
                   6667:   vertical-align: top;
                   6668:   width: 150px;
                   6669:   border-top:1px solid $lg_border_color;
                   6670: }
                   6671: 
1.795     www      6672: td.LC_parm_overview_level_menu,
                   6673: td.LC_parm_overview_map_menu,
                   6674: td.LC_parm_overview_parm_selectors,
                   6675: td.LC_parm_overview_restrictions  {
1.396     albertel 6676:   border: 1px solid black;
                   6677:   border-collapse: collapse;
                   6678: }
1.795     www      6679: 
1.396     albertel 6680: table.LC_parm_overview_restrictions td {
                   6681:   border-width: 1px 4px 1px 4px;
                   6682:   border-style: solid;
                   6683:   border-color: $pgbg;
                   6684:   text-align: center;
                   6685: }
1.795     www      6686: 
1.396     albertel 6687: table.LC_parm_overview_restrictions th {
                   6688:   background: $tabbg;
                   6689:   border-width: 1px 4px 1px 4px;
                   6690:   border-style: solid;
                   6691:   border-color: $pgbg;
                   6692: }
1.795     www      6693: 
1.398     albertel 6694: table#LC_helpmenu {
1.803     bisitz   6695:   border: none;
1.398     albertel 6696:   height: 55px;
1.803     bisitz   6697:   border-spacing: 0;
1.398     albertel 6698: }
                   6699: 
                   6700: table#LC_helpmenu fieldset legend {
                   6701:   font-size: larger;
                   6702: }
1.795     www      6703: 
1.397     albertel 6704: table#LC_helpmenu_links {
                   6705:   width: 100%;
                   6706:   border: 1px solid black;
                   6707:   background: $pgbg;
1.803     bisitz   6708:   padding: 0;
1.397     albertel 6709:   border-spacing: 1px;
                   6710: }
1.795     www      6711: 
1.397     albertel 6712: table#LC_helpmenu_links tr td {
                   6713:   padding: 1px;
                   6714:   background: $tabbg;
1.399     albertel 6715:   text-align: center;
                   6716:   font-weight: bold;
1.397     albertel 6717: }
1.396     albertel 6718: 
1.795     www      6719: table#LC_helpmenu_links a:link,
                   6720: table#LC_helpmenu_links a:visited,
1.397     albertel 6721: table#LC_helpmenu_links a:active {
                   6722:   text-decoration: none;
                   6723:   color: $font;
                   6724: }
1.795     www      6725: 
1.397     albertel 6726: table#LC_helpmenu_links a:hover {
                   6727:   text-decoration: underline;
                   6728:   color: $vlink;
                   6729: }
1.396     albertel 6730: 
1.417     albertel 6731: .LC_chrt_popup_exists {
                   6732:   border: 1px solid #339933;
                   6733:   margin: -1px;
                   6734: }
1.795     www      6735: 
1.417     albertel 6736: .LC_chrt_popup_up {
                   6737:   border: 1px solid yellow;
                   6738:   margin: -1px;
                   6739: }
1.795     www      6740: 
1.417     albertel 6741: .LC_chrt_popup {
                   6742:   border: 1px solid #8888FF;
                   6743:   background: #CCCCFF;
                   6744: }
1.795     www      6745: 
1.421     albertel 6746: table.LC_pick_box {
                   6747:   border-collapse: separate;
                   6748:   background: white;
                   6749:   border: 1px solid black;
                   6750:   border-spacing: 1px;
                   6751: }
1.795     www      6752: 
1.421     albertel 6753: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6754:   background: $sidebg;
1.421     albertel 6755:   font-weight: bold;
1.900     bisitz   6756:   text-align: left;
1.740     bisitz   6757:   vertical-align: top;
1.421     albertel 6758:   width: 184px;
                   6759:   padding: 8px;
                   6760: }
1.795     www      6761: 
1.579     raeburn  6762: table.LC_pick_box td.LC_pick_box_value {
                   6763:   text-align: left;
                   6764:   padding: 8px;
                   6765: }
1.795     www      6766: 
1.579     raeburn  6767: table.LC_pick_box td.LC_pick_box_select {
                   6768:   text-align: left;
                   6769:   padding: 8px;
                   6770: }
1.795     www      6771: 
1.424     albertel 6772: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6773:   padding: 0;
1.421     albertel 6774:   height: 1px;
                   6775:   background: black;
                   6776: }
1.795     www      6777: 
1.421     albertel 6778: table.LC_pick_box td.LC_pick_box_submit {
                   6779:   text-align: right;
                   6780: }
1.795     www      6781: 
1.579     raeburn  6782: table.LC_pick_box td.LC_evenrow_value {
                   6783:   text-align: left;
                   6784:   padding: 8px;
                   6785:   background-color: $data_table_light;
                   6786: }
1.795     www      6787: 
1.579     raeburn  6788: table.LC_pick_box td.LC_oddrow_value {
                   6789:   text-align: left;
                   6790:   padding: 8px;
                   6791:   background-color: $data_table_light;
                   6792: }
1.795     www      6793: 
1.579     raeburn  6794: span.LC_helpform_receipt_cat {
                   6795:   font-weight: bold;
                   6796: }
1.795     www      6797: 
1.424     albertel 6798: table.LC_group_priv_box {
                   6799:   background: white;
                   6800:   border: 1px solid black;
                   6801:   border-spacing: 1px;
                   6802: }
1.795     www      6803: 
1.424     albertel 6804: table.LC_group_priv_box td.LC_pick_box_title {
                   6805:   background: $tabbg;
                   6806:   font-weight: bold;
                   6807:   text-align: right;
                   6808:   width: 184px;
                   6809: }
1.795     www      6810: 
1.424     albertel 6811: table.LC_group_priv_box td.LC_groups_fixed {
                   6812:   background: $data_table_light;
                   6813:   text-align: center;
                   6814: }
1.795     www      6815: 
1.424     albertel 6816: table.LC_group_priv_box td.LC_groups_optional {
                   6817:   background: $data_table_dark;
                   6818:   text-align: center;
                   6819: }
1.795     www      6820: 
1.424     albertel 6821: table.LC_group_priv_box td.LC_groups_functionality {
                   6822:   background: $data_table_darker;
                   6823:   text-align: center;
                   6824:   font-weight: bold;
                   6825: }
1.795     www      6826: 
1.424     albertel 6827: table.LC_group_priv td {
                   6828:   text-align: left;
1.803     bisitz   6829:   padding: 0;
1.424     albertel 6830: }
                   6831: 
                   6832: .LC_navbuttons {
                   6833:   margin: 2ex 0ex 2ex 0ex;
                   6834: }
1.795     www      6835: 
1.423     albertel 6836: .LC_topic_bar {
                   6837:   font-weight: bold;
                   6838:   background: $tabbg;
1.918     wenzelju 6839:   margin: 1em 0em 1em 2em;
1.805     bisitz   6840:   padding: 3px;
1.918     wenzelju 6841:   font-size: 1.2em;
1.423     albertel 6842: }
1.795     www      6843: 
1.423     albertel 6844: .LC_topic_bar span {
1.918     wenzelju 6845:   left: 0.5em;
                   6846:   position: absolute;
1.423     albertel 6847:   vertical-align: middle;
1.918     wenzelju 6848:   font-size: 1.2em;
1.423     albertel 6849: }
1.795     www      6850: 
1.423     albertel 6851: table.LC_course_group_status {
                   6852:   margin: 20px;
                   6853: }
1.795     www      6854: 
1.423     albertel 6855: table.LC_status_selector td {
                   6856:   vertical-align: top;
                   6857:   text-align: center;
1.424     albertel 6858:   padding: 4px;
                   6859: }
1.795     www      6860: 
1.599     albertel 6861: div.LC_feedback_link {
1.616     albertel 6862:   clear: both;
1.829     kalberla 6863:   background: $sidebg;
1.779     bisitz   6864:   width: 100%;
1.829     kalberla 6865:   padding-bottom: 10px;
                   6866:   border: 1px $tabbg solid;
1.833     kalberla 6867:   height: 22px;
                   6868:   line-height: 22px;
                   6869:   padding-top: 5px;
                   6870: }
                   6871: 
                   6872: div.LC_feedback_link img {
                   6873:   height: 22px;
1.867     kalberla 6874:   vertical-align:middle;
1.829     kalberla 6875: }
                   6876: 
1.911     bisitz   6877: div.LC_feedback_link a {
1.829     kalberla 6878:   text-decoration: none;
1.489     raeburn  6879: }
1.795     www      6880: 
1.867     kalberla 6881: div.LC_comblock {
1.911     bisitz   6882:   display:inline;
1.867     kalberla 6883:   color:$font;
                   6884:   font-size:90%;
                   6885: }
                   6886: 
                   6887: div.LC_feedback_link div.LC_comblock {
                   6888:   padding-left:5px;
                   6889: }
                   6890: 
                   6891: div.LC_feedback_link div.LC_comblock a {
                   6892:   color:$font;
                   6893: }
                   6894: 
1.489     raeburn  6895: span.LC_feedback_link {
1.858     bisitz   6896:   /* background: $feedback_link_bg; */
1.599     albertel 6897:   font-size: larger;
                   6898: }
1.795     www      6899: 
1.599     albertel 6900: span.LC_message_link {
1.858     bisitz   6901:   /* background: $feedback_link_bg; */
1.599     albertel 6902:   font-size: larger;
                   6903:   position: absolute;
                   6904:   right: 1em;
1.489     raeburn  6905: }
1.421     albertel 6906: 
1.515     albertel 6907: table.LC_prior_tries {
1.524     albertel 6908:   border: 1px solid #000000;
                   6909:   border-collapse: separate;
                   6910:   border-spacing: 1px;
1.515     albertel 6911: }
1.523     albertel 6912: 
1.515     albertel 6913: table.LC_prior_tries td {
1.524     albertel 6914:   padding: 2px;
1.515     albertel 6915: }
1.523     albertel 6916: 
                   6917: .LC_answer_correct {
1.795     www      6918:   background: lightgreen;
                   6919:   color: darkgreen;
                   6920:   padding: 6px;
1.523     albertel 6921: }
1.795     www      6922: 
1.523     albertel 6923: .LC_answer_charged_try {
1.797     www      6924:   background: #FFAAAA;
1.795     www      6925:   color: darkred;
                   6926:   padding: 6px;
1.523     albertel 6927: }
1.795     www      6928: 
1.779     bisitz   6929: .LC_answer_not_charged_try,
1.523     albertel 6930: .LC_answer_no_grade,
                   6931: .LC_answer_late {
1.795     www      6932:   background: lightyellow;
1.523     albertel 6933:   color: black;
1.795     www      6934:   padding: 6px;
1.523     albertel 6935: }
1.795     www      6936: 
1.523     albertel 6937: .LC_answer_previous {
1.795     www      6938:   background: lightblue;
                   6939:   color: darkblue;
                   6940:   padding: 6px;
1.523     albertel 6941: }
1.795     www      6942: 
1.779     bisitz   6943: .LC_answer_no_message {
1.777     tempelho 6944:   background: #FFFFFF;
                   6945:   color: black;
1.795     www      6946:   padding: 6px;
1.779     bisitz   6947: }
1.795     www      6948: 
1.1075.2.140  raeburn  6949: .LC_answer_unknown,
                   6950: .LC_answer_warning {
1.779     bisitz   6951:   background: orange;
                   6952:   color: black;
1.795     www      6953:   padding: 6px;
1.777     tempelho 6954: }
1.795     www      6955: 
1.529     albertel 6956: span.LC_prior_numerical,
                   6957: span.LC_prior_string,
                   6958: span.LC_prior_custom,
                   6959: span.LC_prior_reaction,
                   6960: span.LC_prior_math {
1.925     bisitz   6961:   font-family: $mono;
1.523     albertel 6962:   white-space: pre;
                   6963: }
                   6964: 
1.525     albertel 6965: span.LC_prior_string {
1.925     bisitz   6966:   font-family: $mono;
1.525     albertel 6967:   white-space: pre;
                   6968: }
                   6969: 
1.523     albertel 6970: table.LC_prior_option {
                   6971:   width: 100%;
                   6972:   border-collapse: collapse;
                   6973: }
1.795     www      6974: 
1.911     bisitz   6975: table.LC_prior_rank,
1.795     www      6976: table.LC_prior_match {
1.528     albertel 6977:   border-collapse: collapse;
                   6978: }
1.795     www      6979: 
1.528     albertel 6980: table.LC_prior_option tr td,
                   6981: table.LC_prior_rank tr td,
                   6982: table.LC_prior_match tr td {
1.524     albertel 6983:   border: 1px solid #000000;
1.515     albertel 6984: }
                   6985: 
1.855     bisitz   6986: .LC_nobreak {
1.544     albertel 6987:   white-space: nowrap;
1.519     raeburn  6988: }
                   6989: 
1.576     raeburn  6990: span.LC_cusr_emph {
                   6991:   font-style: italic;
                   6992: }
                   6993: 
1.633     raeburn  6994: span.LC_cusr_subheading {
                   6995:   font-weight: normal;
                   6996:   font-size: 85%;
                   6997: }
                   6998: 
1.861     bisitz   6999: div.LC_docs_entry_move {
1.859     bisitz   7000:   border: 1px solid #BBBBBB;
1.545     albertel 7001:   background: #DDDDDD;
1.861     bisitz   7002:   width: 22px;
1.859     bisitz   7003:   padding: 1px;
                   7004:   margin: 0;
1.545     albertel 7005: }
                   7006: 
1.861     bisitz   7007: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7008: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7009:   font-size: x-small;
                   7010: }
1.795     www      7011: 
1.861     bisitz   7012: .LC_docs_entry_parameter {
                   7013:   white-space: nowrap;
                   7014: }
                   7015: 
1.544     albertel 7016: .LC_docs_copy {
1.545     albertel 7017:   color: #000099;
1.544     albertel 7018: }
1.795     www      7019: 
1.544     albertel 7020: .LC_docs_cut {
1.545     albertel 7021:   color: #550044;
1.544     albertel 7022: }
1.795     www      7023: 
1.544     albertel 7024: .LC_docs_rename {
1.545     albertel 7025:   color: #009900;
1.544     albertel 7026: }
1.795     www      7027: 
1.544     albertel 7028: .LC_docs_remove {
1.545     albertel 7029:   color: #990000;
                   7030: }
                   7031: 
1.1075.2.134  raeburn  7032: .LC_domprefs_email,
1.547     albertel 7033: .LC_docs_reinit_warn,
                   7034: .LC_docs_ext_edit {
                   7035:   font-size: x-small;
                   7036: }
                   7037: 
1.545     albertel 7038: table.LC_docs_adddocs td,
                   7039: table.LC_docs_adddocs th {
                   7040:   border: 1px solid #BBBBBB;
                   7041:   padding: 4px;
                   7042:   background: #DDDDDD;
1.543     albertel 7043: }
                   7044: 
1.584     albertel 7045: table.LC_sty_begin {
                   7046:   background: #BBFFBB;
                   7047: }
1.795     www      7048: 
1.584     albertel 7049: table.LC_sty_end {
                   7050:   background: #FFBBBB;
                   7051: }
                   7052: 
1.589     raeburn  7053: table.LC_double_column {
1.803     bisitz   7054:   border-width: 0;
1.589     raeburn  7055:   border-collapse: collapse;
                   7056:   width: 100%;
                   7057:   padding: 2px;
                   7058: }
                   7059: 
                   7060: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7061:   top: 2px;
1.589     raeburn  7062:   left: 2px;
                   7063:   width: 47%;
                   7064:   vertical-align: top;
                   7065: }
                   7066: 
                   7067: table.LC_double_column tr td.LC_right_col {
                   7068:   top: 2px;
1.779     bisitz   7069:   right: 2px;
1.589     raeburn  7070:   width: 47%;
                   7071:   vertical-align: top;
                   7072: }
                   7073: 
1.591     raeburn  7074: div.LC_left_float {
                   7075:   float: left;
                   7076:   padding-right: 5%;
1.597     albertel 7077:   padding-bottom: 4px;
1.591     raeburn  7078: }
                   7079: 
                   7080: div.LC_clear_float_header {
1.597     albertel 7081:   padding-bottom: 2px;
1.591     raeburn  7082: }
                   7083: 
                   7084: div.LC_clear_float_footer {
1.597     albertel 7085:   padding-top: 10px;
1.591     raeburn  7086:   clear: both;
                   7087: }
                   7088: 
1.597     albertel 7089: div.LC_grade_show_user {
1.941     bisitz   7090: /*  border-left: 5px solid $sidebg; */
                   7091:   border-top: 5px solid #000000;
                   7092:   margin: 50px 0 0 0;
1.936     bisitz   7093:   padding: 15px 0 5px 10px;
1.597     albertel 7094: }
1.795     www      7095: 
1.936     bisitz   7096: div.LC_grade_show_user_odd_row {
1.941     bisitz   7097: /*  border-left: 5px solid #000000; */
                   7098: }
                   7099: 
                   7100: div.LC_grade_show_user div.LC_Box {
                   7101:   margin-right: 50px;
1.597     albertel 7102: }
                   7103: 
                   7104: div.LC_grade_submissions,
                   7105: div.LC_grade_message_center,
1.936     bisitz   7106: div.LC_grade_info_links {
1.597     albertel 7107:   margin: 5px;
                   7108:   width: 99%;
                   7109:   background: #FFFFFF;
                   7110: }
1.795     www      7111: 
1.597     albertel 7112: div.LC_grade_submissions_header,
1.936     bisitz   7113: div.LC_grade_message_center_header {
1.705     tempelho 7114:   font-weight: bold;
                   7115:   font-size: large;
1.597     albertel 7116: }
1.795     www      7117: 
1.597     albertel 7118: div.LC_grade_submissions_body,
1.936     bisitz   7119: div.LC_grade_message_center_body {
1.597     albertel 7120:   border: 1px solid black;
                   7121:   width: 99%;
                   7122:   background: #FFFFFF;
                   7123: }
1.795     www      7124: 
1.613     albertel 7125: table.LC_scantron_action {
                   7126:   width: 100%;
                   7127: }
1.795     www      7128: 
1.613     albertel 7129: table.LC_scantron_action tr th {
1.698     harmsja  7130:   font-weight:bold;
                   7131:   font-style:normal;
1.613     albertel 7132: }
1.795     www      7133: 
1.779     bisitz   7134: .LC_edit_problem_header,
1.614     albertel 7135: div.LC_edit_problem_footer {
1.705     tempelho 7136:   font-weight: normal;
                   7137:   font-size:  medium;
1.602     albertel 7138:   margin: 2px;
1.1060    bisitz   7139:   background-color: $sidebg;
1.600     albertel 7140: }
1.795     www      7141: 
1.600     albertel 7142: div.LC_edit_problem_header,
1.602     albertel 7143: div.LC_edit_problem_header div,
1.614     albertel 7144: div.LC_edit_problem_footer,
                   7145: div.LC_edit_problem_footer div,
1.602     albertel 7146: div.LC_edit_problem_editxml_header,
                   7147: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  7148:   z-index: 100;
1.600     albertel 7149: }
1.795     www      7150: 
1.600     albertel 7151: div.LC_edit_problem_header_title {
1.705     tempelho 7152:   font-weight: bold;
                   7153:   font-size: larger;
1.602     albertel 7154:   background: $tabbg;
                   7155:   padding: 3px;
1.1060    bisitz   7156:   margin: 0 0 5px 0;
1.602     albertel 7157: }
1.795     www      7158: 
1.602     albertel 7159: table.LC_edit_problem_header_title {
                   7160:   width: 100%;
1.600     albertel 7161:   background: $tabbg;
1.602     albertel 7162: }
                   7163: 
1.1075.2.112  raeburn  7164: div.LC_edit_actionbar {
                   7165:     background-color: $sidebg;
                   7166:     margin: 0;
                   7167:     padding: 0;
                   7168:     line-height: 200%;
1.602     albertel 7169: }
1.795     www      7170: 
1.1075.2.112  raeburn  7171: div.LC_edit_actionbar div{
                   7172:     padding: 0;
                   7173:     margin: 0;
                   7174:     display: inline-block;
1.600     albertel 7175: }
1.795     www      7176: 
1.1075.2.34  raeburn  7177: .LC_edit_opt {
                   7178:   padding-left: 1em;
                   7179:   white-space: nowrap;
                   7180: }
                   7181: 
1.1075.2.57  raeburn  7182: .LC_edit_problem_latexhelper{
                   7183:     text-align: right;
                   7184: }
                   7185: 
                   7186: #LC_edit_problem_colorful div{
                   7187:     margin-left: 40px;
                   7188: }
                   7189: 
1.1075.2.112  raeburn  7190: #LC_edit_problem_codemirror div{
                   7191:     margin-left: 0px;
                   7192: }
                   7193: 
1.911     bisitz   7194: img.stift {
1.803     bisitz   7195:   border-width: 0;
                   7196:   vertical-align: middle;
1.677     riegler  7197: }
1.680     riegler  7198: 
1.923     bisitz   7199: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7200:   vertical-align: top;
1.777     tempelho 7201: }
1.795     www      7202: 
1.716     raeburn  7203: div.LC_createcourse {
1.911     bisitz   7204:   margin: 10px 10px 10px 10px;
1.716     raeburn  7205: }
                   7206: 
1.917     raeburn  7207: .LC_dccid {
1.1075.2.38  raeburn  7208:   float: right;
1.917     raeburn  7209:   margin: 0.2em 0 0 0;
                   7210:   padding: 0;
                   7211:   font-size: 90%;
                   7212:   display:none;
                   7213: }
                   7214: 
1.897     wenzelju 7215: ol.LC_primary_menu a:hover,
1.721     harmsja  7216: ol#LC_MenuBreadcrumbs a:hover,
                   7217: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7218: ul#LC_secondary_menu a:hover,
1.721     harmsja  7219: .LC_FormSectionClearButton input:hover
1.795     www      7220: ul.LC_TabContent   li:hover a {
1.952     onken    7221:   color:$button_hover;
1.911     bisitz   7222:   text-decoration:none;
1.693     droeschl 7223: }
                   7224: 
1.779     bisitz   7225: h1 {
1.911     bisitz   7226:   padding: 0;
                   7227:   line-height:130%;
1.693     droeschl 7228: }
1.698     harmsja  7229: 
1.911     bisitz   7230: h2,
                   7231: h3,
                   7232: h4,
                   7233: h5,
                   7234: h6 {
                   7235:   margin: 5px 0 5px 0;
                   7236:   padding: 0;
                   7237:   line-height:130%;
1.693     droeschl 7238: }
1.795     www      7239: 
                   7240: .LC_hcell {
1.911     bisitz   7241:   padding:3px 15px 3px 15px;
                   7242:   margin: 0;
                   7243:   background-color:$tabbg;
                   7244:   color:$fontmenu;
                   7245:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7246: }
1.795     www      7247: 
1.840     bisitz   7248: .LC_Box > .LC_hcell {
1.911     bisitz   7249:   margin: 0 -10px 10px -10px;
1.835     bisitz   7250: }
                   7251: 
1.721     harmsja  7252: .LC_noBorder {
1.911     bisitz   7253:   border: 0;
1.698     harmsja  7254: }
1.693     droeschl 7255: 
1.721     harmsja  7256: .LC_FormSectionClearButton input {
1.911     bisitz   7257:   background-color:transparent;
                   7258:   border: none;
                   7259:   cursor:pointer;
                   7260:   text-decoration:underline;
1.693     droeschl 7261: }
1.763     bisitz   7262: 
                   7263: .LC_help_open_topic {
1.911     bisitz   7264:   color: #FFFFFF;
                   7265:   background-color: #EEEEFF;
                   7266:   margin: 1px;
                   7267:   padding: 4px;
                   7268:   border: 1px solid #000033;
                   7269:   white-space: nowrap;
                   7270:   /* vertical-align: middle; */
1.759     neumanie 7271: }
1.693     droeschl 7272: 
1.911     bisitz   7273: dl,
                   7274: ul,
                   7275: div,
                   7276: fieldset {
                   7277:   margin: 10px 10px 10px 0;
                   7278:   /* overflow: hidden; */
1.693     droeschl 7279: }
1.795     www      7280: 
1.1075.2.90  raeburn  7281: article.geogebraweb div {
                   7282:     margin: 0;
                   7283: }
                   7284: 
1.838     bisitz   7285: fieldset > legend {
1.911     bisitz   7286:   font-weight: bold;
                   7287:   padding: 0 5px 0 5px;
1.838     bisitz   7288: }
                   7289: 
1.813     bisitz   7290: #LC_nav_bar {
1.911     bisitz   7291:   float: left;
1.995     raeburn  7292:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7293:   margin: 0 0 2px 0;
1.807     droeschl 7294: }
                   7295: 
1.916     droeschl 7296: #LC_realm {
                   7297:   margin: 0.2em 0 0 0;
                   7298:   padding: 0;
                   7299:   font-weight: bold;
                   7300:   text-align: center;
1.995     raeburn  7301:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7302: }
                   7303: 
1.911     bisitz   7304: #LC_nav_bar em {
                   7305:   font-weight: bold;
                   7306:   font-style: normal;
1.807     droeschl 7307: }
                   7308: 
1.897     wenzelju 7309: ol.LC_primary_menu {
1.934     droeschl 7310:   margin: 0;
1.1075.2.2  raeburn  7311:   padding: 0;
1.807     droeschl 7312: }
                   7313: 
1.852     droeschl 7314: ol#LC_PathBreadcrumbs {
1.911     bisitz   7315:   margin: 0;
1.693     droeschl 7316: }
                   7317: 
1.897     wenzelju 7318: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7319:   color: RGB(80, 80, 80);
                   7320:   vertical-align: middle;
                   7321:   text-align: left;
                   7322:   list-style: none;
1.1075.2.112  raeburn  7323:   position: relative;
1.1075.2.2  raeburn  7324:   float: left;
1.1075.2.112  raeburn  7325:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7326:   line-height: 1.5em;
1.1075.2.2  raeburn  7327: }
                   7328: 
1.1075.2.113  raeburn  7329: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7330: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7331:   display: block;
                   7332:   margin: 0;
                   7333:   padding: 0 5px 0 10px;
                   7334:   text-decoration: none;
                   7335: }
                   7336: 
1.1075.2.112  raeburn  7337: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7338:   display: inline-block;
                   7339:   width: 95%;
                   7340:   text-align: left;
                   7341: }
                   7342: 
                   7343: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7344:   display: inline-block;
                   7345:   width: 5%;
                   7346:   float: right;
                   7347:   text-align: right;
                   7348:   font-size: 70%;
                   7349: }
                   7350: 
                   7351: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7352:   display: none;
1.1075.2.112  raeburn  7353:   width: 15em;
1.1075.2.2  raeburn  7354:   background-color: $data_table_light;
1.1075.2.112  raeburn  7355:   position: absolute;
                   7356:   top: 100%;
                   7357: }
                   7358: 
                   7359: ol.LC_primary_menu ul ul {
                   7360:   left: 100%;
                   7361:   top: 0;
1.1075.2.2  raeburn  7362: }
                   7363: 
1.1075.2.112  raeburn  7364: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7365:   display: block;
                   7366:   position: absolute;
                   7367:   margin: 0;
                   7368:   padding: 0;
1.1075.2.5  raeburn  7369:   z-index: 2;
1.1075.2.2  raeburn  7370: }
                   7371: 
                   7372: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7373: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7374:   font-size: 90%;
1.911     bisitz   7375:   vertical-align: top;
1.1075.2.2  raeburn  7376:   float: none;
1.1075.2.5  raeburn  7377:   border-left: 1px solid black;
                   7378:   border-right: 1px solid black;
1.1075.2.112  raeburn  7379: /* A dark bottom border to visualize different menu options;
                   7380: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7381:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7382: }
                   7383: 
1.1075.2.112  raeburn  7384: ol.LC_primary_menu li li p:hover {
                   7385:   color:$button_hover;
                   7386:   text-decoration:none;
                   7387:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7388: }
                   7389: 
                   7390: ol.LC_primary_menu li li a:hover {
                   7391:    color:$button_hover;
                   7392:    background-color:$data_table_dark;
1.693     droeschl 7393: }
                   7394: 
1.1075.2.112  raeburn  7395: /* Font-size equal to the size of the predecessors*/
                   7396: ol.LC_primary_menu li:hover li li {
                   7397:   font-size: 100%;
                   7398: }
                   7399: 
1.897     wenzelju 7400: ol.LC_primary_menu li img {
1.911     bisitz   7401:   vertical-align: bottom;
1.934     droeschl 7402:   height: 1.1em;
1.1075.2.3  raeburn  7403:   margin: 0.2em 0 0 0;
1.693     droeschl 7404: }
                   7405: 
1.897     wenzelju 7406: ol.LC_primary_menu a {
1.911     bisitz   7407:   color: RGB(80, 80, 80);
                   7408:   text-decoration: none;
1.693     droeschl 7409: }
1.795     www      7410: 
1.949     droeschl 7411: ol.LC_primary_menu a.LC_new_message {
                   7412:   font-weight:bold;
                   7413:   color: darkred;
                   7414: }
                   7415: 
1.975     raeburn  7416: ol.LC_docs_parameters {
                   7417:   margin-left: 0;
                   7418:   padding: 0;
                   7419:   list-style: none;
                   7420: }
                   7421: 
                   7422: ol.LC_docs_parameters li {
                   7423:   margin: 0;
                   7424:   padding-right: 20px;
                   7425:   display: inline;
                   7426: }
                   7427: 
1.976     raeburn  7428: ol.LC_docs_parameters li:before {
                   7429:   content: "\\002022 \\0020";
                   7430: }
                   7431: 
                   7432: li.LC_docs_parameters_title {
                   7433:   font-weight: bold;
                   7434: }
                   7435: 
                   7436: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7437:   content: "";
                   7438: }
                   7439: 
1.897     wenzelju 7440: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7441:   clear: right;
1.911     bisitz   7442:   color: $fontmenu;
                   7443:   background: $tabbg;
                   7444:   list-style: none;
                   7445:   padding: 0;
                   7446:   margin: 0;
                   7447:   width: 100%;
1.995     raeburn  7448:   text-align: left;
1.1075.2.4  raeburn  7449:   float: left;
1.808     droeschl 7450: }
                   7451: 
1.897     wenzelju 7452: ul#LC_secondary_menu li {
1.911     bisitz   7453:   font-weight: bold;
                   7454:   line-height: 1.8em;
                   7455:   border-right: 1px solid black;
1.1075.2.4  raeburn  7456:   float: left;
                   7457: }
                   7458: 
                   7459: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7460:   background-color: $data_table_light;
                   7461: }
                   7462: 
                   7463: ul#LC_secondary_menu li a {
                   7464:   padding: 0 0.8em;
                   7465: }
                   7466: 
                   7467: ul#LC_secondary_menu li ul {
                   7468:   display: none;
                   7469: }
                   7470: 
                   7471: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7472:   display: block;
                   7473:   position: absolute;
                   7474:   margin: 0;
                   7475:   padding: 0;
                   7476:   list-style:none;
                   7477:   float: none;
                   7478:   background-color: $data_table_light;
1.1075.2.5  raeburn  7479:   z-index: 2;
1.1075.2.10  raeburn  7480:   margin-left: -1px;
1.1075.2.4  raeburn  7481: }
                   7482: 
                   7483: ul#LC_secondary_menu li ul li {
                   7484:   font-size: 90%;
                   7485:   vertical-align: top;
                   7486:   border-left: 1px solid black;
                   7487:   border-right: 1px solid black;
1.1075.2.33  raeburn  7488:   background-color: $data_table_light;
1.1075.2.4  raeburn  7489:   list-style:none;
                   7490:   float: none;
                   7491: }
                   7492: 
                   7493: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7494:   background-color: $data_table_dark;
1.807     droeschl 7495: }
                   7496: 
1.847     tempelho 7497: ul.LC_TabContent {
1.911     bisitz   7498:   display:block;
                   7499:   background: $sidebg;
                   7500:   border-bottom: solid 1px $lg_border_color;
                   7501:   list-style:none;
1.1020    raeburn  7502:   margin: -1px -10px 0 -10px;
1.911     bisitz   7503:   padding: 0;
1.693     droeschl 7504: }
                   7505: 
1.795     www      7506: ul.LC_TabContent li,
                   7507: ul.LC_TabContentBigger li {
1.911     bisitz   7508:   float:left;
1.741     harmsja  7509: }
1.795     www      7510: 
1.897     wenzelju 7511: ul#LC_secondary_menu li a {
1.911     bisitz   7512:   color: $fontmenu;
                   7513:   text-decoration: none;
1.693     droeschl 7514: }
1.795     www      7515: 
1.721     harmsja  7516: ul.LC_TabContent {
1.952     onken    7517:   min-height:20px;
1.721     harmsja  7518: }
1.795     www      7519: 
                   7520: ul.LC_TabContent li {
1.911     bisitz   7521:   vertical-align:middle;
1.959     onken    7522:   padding: 0 16px 0 10px;
1.911     bisitz   7523:   background-color:$tabbg;
                   7524:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7525:   border-left: solid 1px $font;
1.721     harmsja  7526: }
1.795     www      7527: 
1.847     tempelho 7528: ul.LC_TabContent .right {
1.911     bisitz   7529:   float:right;
1.847     tempelho 7530: }
                   7531: 
1.911     bisitz   7532: ul.LC_TabContent li a,
                   7533: ul.LC_TabContent li {
                   7534:   color:rgb(47,47,47);
                   7535:   text-decoration:none;
                   7536:   font-size:95%;
                   7537:   font-weight:bold;
1.952     onken    7538:   min-height:20px;
                   7539: }
                   7540: 
1.959     onken    7541: ul.LC_TabContent li a:hover,
                   7542: ul.LC_TabContent li a:focus {
1.952     onken    7543:   color: $button_hover;
1.959     onken    7544:   background:none;
                   7545:   outline:none;
1.952     onken    7546: }
                   7547: 
                   7548: ul.LC_TabContent li:hover {
                   7549:   color: $button_hover;
                   7550:   cursor:pointer;
1.721     harmsja  7551: }
1.795     www      7552: 
1.911     bisitz   7553: ul.LC_TabContent li.active {
1.952     onken    7554:   color: $font;
1.911     bisitz   7555:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7556:   border-bottom:solid 1px #FFFFFF;
                   7557:   cursor: default;
1.744     ehlerst  7558: }
1.795     www      7559: 
1.959     onken    7560: ul.LC_TabContent li.active a {
                   7561:   color:$font;
                   7562:   background:#FFFFFF;
                   7563:   outline: none;
                   7564: }
1.1047    raeburn  7565: 
                   7566: ul.LC_TabContent li.goback {
                   7567:   float: left;
                   7568:   border-left: none;
                   7569: }
                   7570: 
1.870     tempelho 7571: #maincoursedoc {
1.911     bisitz   7572:   clear:both;
1.870     tempelho 7573: }
                   7574: 
                   7575: ul.LC_TabContentBigger {
1.911     bisitz   7576:   display:block;
                   7577:   list-style:none;
                   7578:   padding: 0;
1.870     tempelho 7579: }
                   7580: 
1.795     www      7581: ul.LC_TabContentBigger li {
1.911     bisitz   7582:   vertical-align:bottom;
                   7583:   height: 30px;
                   7584:   font-size:110%;
                   7585:   font-weight:bold;
                   7586:   color: #737373;
1.841     tempelho 7587: }
                   7588: 
1.957     onken    7589: ul.LC_TabContentBigger li.active {
                   7590:   position: relative;
                   7591:   top: 1px;
                   7592: }
                   7593: 
1.870     tempelho 7594: ul.LC_TabContentBigger li a {
1.911     bisitz   7595:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7596:   height: 30px;
                   7597:   line-height: 30px;
                   7598:   text-align: center;
                   7599:   display: block;
                   7600:   text-decoration: none;
1.958     onken    7601:   outline: none;  
1.741     harmsja  7602: }
1.795     www      7603: 
1.870     tempelho 7604: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7605:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7606:   color:$font;
1.744     ehlerst  7607: }
1.795     www      7608: 
1.870     tempelho 7609: ul.LC_TabContentBigger li b {
1.911     bisitz   7610:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7611:   display: block;
                   7612:   float: left;
                   7613:   padding: 0 30px;
1.957     onken    7614:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7615: }
                   7616: 
1.956     onken    7617: ul.LC_TabContentBigger li:hover b {
                   7618:   color:$button_hover;
                   7619: }
                   7620: 
1.870     tempelho 7621: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7622:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7623:   color:$font;
1.957     onken    7624:   border: 0;
1.741     harmsja  7625: }
1.693     droeschl 7626: 
1.870     tempelho 7627: 
1.862     bisitz   7628: ul.LC_CourseBreadcrumbs {
                   7629:   background: $sidebg;
1.1020    raeburn  7630:   height: 2em;
1.862     bisitz   7631:   padding-left: 10px;
1.1020    raeburn  7632:   margin: 0;
1.862     bisitz   7633:   list-style-position: inside;
                   7634: }
                   7635: 
1.911     bisitz   7636: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7637: ol#LC_PathBreadcrumbs {
1.911     bisitz   7638:   padding-left: 10px;
                   7639:   margin: 0;
1.933     droeschl 7640:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7641: }
                   7642: 
1.911     bisitz   7643: ol#LC_MenuBreadcrumbs li,
                   7644: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7645: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7646:   display: inline;
1.933     droeschl 7647:   white-space: normal;  
1.693     droeschl 7648: }
                   7649: 
1.823     bisitz   7650: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7651: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7652:   text-decoration: none;
                   7653:   font-size:90%;
1.693     droeschl 7654: }
1.795     www      7655: 
1.969     droeschl 7656: ol#LC_MenuBreadcrumbs h1 {
                   7657:   display: inline;
                   7658:   font-size: 90%;
                   7659:   line-height: 2.5em;
                   7660:   margin: 0;
                   7661:   padding: 0;
                   7662: }
                   7663: 
1.795     www      7664: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7665:   text-decoration:none;
                   7666:   font-size:100%;
                   7667:   font-weight:bold;
1.693     droeschl 7668: }
1.795     www      7669: 
1.840     bisitz   7670: .LC_Box {
1.911     bisitz   7671:   border: solid 1px $lg_border_color;
                   7672:   padding: 0 10px 10px 10px;
1.746     neumanie 7673: }
1.795     www      7674: 
1.1020    raeburn  7675: .LC_DocsBox {
                   7676:   border: solid 1px $lg_border_color;
                   7677:   padding: 0 0 10px 10px;
                   7678: }
                   7679: 
1.795     www      7680: .LC_AboutMe_Image {
1.911     bisitz   7681:   float:left;
                   7682:   margin-right:10px;
1.747     neumanie 7683: }
1.795     www      7684: 
                   7685: .LC_Clear_AboutMe_Image {
1.911     bisitz   7686:   clear:left;
1.747     neumanie 7687: }
1.795     www      7688: 
1.721     harmsja  7689: dl.LC_ListStyleClean dt {
1.911     bisitz   7690:   padding-right: 5px;
                   7691:   display: table-header-group;
1.693     droeschl 7692: }
                   7693: 
1.721     harmsja  7694: dl.LC_ListStyleClean dd {
1.911     bisitz   7695:   display: table-row;
1.693     droeschl 7696: }
                   7697: 
1.721     harmsja  7698: .LC_ListStyleClean,
                   7699: .LC_ListStyleSimple,
                   7700: .LC_ListStyleNormal,
1.795     www      7701: .LC_ListStyleSpecial {
1.911     bisitz   7702:   /* display:block; */
                   7703:   list-style-position: inside;
                   7704:   list-style-type: none;
                   7705:   overflow: hidden;
                   7706:   padding: 0;
1.693     droeschl 7707: }
                   7708: 
1.721     harmsja  7709: .LC_ListStyleSimple li,
                   7710: .LC_ListStyleSimple dd,
                   7711: .LC_ListStyleNormal li,
                   7712: .LC_ListStyleNormal dd,
                   7713: .LC_ListStyleSpecial li,
1.795     www      7714: .LC_ListStyleSpecial dd {
1.911     bisitz   7715:   margin: 0;
                   7716:   padding: 5px 5px 5px 10px;
                   7717:   clear: both;
1.693     droeschl 7718: }
                   7719: 
1.721     harmsja  7720: .LC_ListStyleClean li,
                   7721: .LC_ListStyleClean dd {
1.911     bisitz   7722:   padding-top: 0;
                   7723:   padding-bottom: 0;
1.693     droeschl 7724: }
                   7725: 
1.721     harmsja  7726: .LC_ListStyleSimple dd,
1.795     www      7727: .LC_ListStyleSimple li {
1.911     bisitz   7728:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7729: }
                   7730: 
1.721     harmsja  7731: .LC_ListStyleSpecial li,
                   7732: .LC_ListStyleSpecial dd {
1.911     bisitz   7733:   list-style-type: none;
                   7734:   background-color: RGB(220, 220, 220);
                   7735:   margin-bottom: 4px;
1.693     droeschl 7736: }
                   7737: 
1.721     harmsja  7738: table.LC_SimpleTable {
1.911     bisitz   7739:   margin:5px;
                   7740:   border:solid 1px $lg_border_color;
1.795     www      7741: }
1.693     droeschl 7742: 
1.721     harmsja  7743: table.LC_SimpleTable tr {
1.911     bisitz   7744:   padding: 0;
                   7745:   border:solid 1px $lg_border_color;
1.693     droeschl 7746: }
1.795     www      7747: 
                   7748: table.LC_SimpleTable thead {
1.911     bisitz   7749:   background:rgb(220,220,220);
1.693     droeschl 7750: }
                   7751: 
1.721     harmsja  7752: div.LC_columnSection {
1.911     bisitz   7753:   display: block;
                   7754:   clear: both;
                   7755:   overflow: hidden;
                   7756:   margin: 0;
1.693     droeschl 7757: }
                   7758: 
1.721     harmsja  7759: div.LC_columnSection>* {
1.911     bisitz   7760:   float: left;
                   7761:   margin: 10px 20px 10px 0;
                   7762:   overflow:hidden;
1.693     droeschl 7763: }
1.721     harmsja  7764: 
1.795     www      7765: table em {
1.911     bisitz   7766:   font-weight: bold;
                   7767:   font-style: normal;
1.748     schulted 7768: }
1.795     www      7769: 
1.779     bisitz   7770: table.LC_tableBrowseRes,
1.795     www      7771: table.LC_tableOfContent {
1.911     bisitz   7772:   border:none;
                   7773:   border-spacing: 1px;
                   7774:   padding: 3px;
                   7775:   background-color: #FFFFFF;
                   7776:   font-size: 90%;
1.753     droeschl 7777: }
1.789     droeschl 7778: 
1.911     bisitz   7779: table.LC_tableOfContent {
                   7780:   border-collapse: collapse;
1.789     droeschl 7781: }
                   7782: 
1.771     droeschl 7783: table.LC_tableBrowseRes a,
1.768     schulted 7784: table.LC_tableOfContent a {
1.911     bisitz   7785:   background-color: transparent;
                   7786:   text-decoration: none;
1.753     droeschl 7787: }
                   7788: 
1.795     www      7789: table.LC_tableOfContent img {
1.911     bisitz   7790:   border: none;
                   7791:   height: 1.3em;
                   7792:   vertical-align: text-bottom;
                   7793:   margin-right: 0.3em;
1.753     droeschl 7794: }
1.757     schulted 7795: 
1.795     www      7796: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7797:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7798: }
                   7799: 
1.795     www      7800: a#LC_content_toolbar_everything {
1.911     bisitz   7801:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7802: }
                   7803: 
1.795     www      7804: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7805:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7806: }
                   7807: 
1.795     www      7808: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7809:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7810: }
                   7811: 
1.795     www      7812: a#LC_content_toolbar_changefolder {
1.911     bisitz   7813:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7814: }
                   7815: 
1.795     www      7816: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7817:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7818: }
                   7819: 
1.1043    raeburn  7820: a#LC_content_toolbar_edittoplevel {
                   7821:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7822: }
                   7823: 
1.795     www      7824: ul#LC_toolbar li a:hover {
1.911     bisitz   7825:   background-position: bottom center;
1.757     schulted 7826: }
                   7827: 
1.795     www      7828: ul#LC_toolbar {
1.911     bisitz   7829:   padding: 0;
                   7830:   margin: 2px;
                   7831:   list-style:none;
                   7832:   position:relative;
                   7833:   background-color:white;
1.1075.2.9  raeburn  7834:   overflow: auto;
1.757     schulted 7835: }
                   7836: 
1.795     www      7837: ul#LC_toolbar li {
1.911     bisitz   7838:   border:1px solid white;
                   7839:   padding: 0;
                   7840:   margin: 0;
                   7841:   float: left;
                   7842:   display:inline;
                   7843:   vertical-align:middle;
1.1075.2.9  raeburn  7844:   white-space: nowrap;
1.911     bisitz   7845: }
1.757     schulted 7846: 
1.783     amueller 7847: 
1.795     www      7848: a.LC_toolbarItem {
1.911     bisitz   7849:   display:block;
                   7850:   padding: 0;
                   7851:   margin: 0;
                   7852:   height: 32px;
                   7853:   width: 32px;
                   7854:   color:white;
                   7855:   border: none;
                   7856:   background-repeat:no-repeat;
                   7857:   background-color:transparent;
1.757     schulted 7858: }
                   7859: 
1.915     droeschl 7860: ul.LC_funclist {
                   7861:     margin: 0;
                   7862:     padding: 0.5em 1em 0.5em 0;
                   7863: }
                   7864: 
1.933     droeschl 7865: ul.LC_funclist > li:first-child {
                   7866:     font-weight:bold; 
                   7867:     margin-left:0.8em;
                   7868: }
                   7869: 
1.915     droeschl 7870: ul.LC_funclist + ul.LC_funclist {
                   7871:     /* 
                   7872:        left border as a seperator if we have more than
                   7873:        one list 
                   7874:     */
                   7875:     border-left: 1px solid $sidebg;
                   7876:     /* 
                   7877:        this hides the left border behind the border of the 
                   7878:        outer box if element is wrapped to the next 'line' 
                   7879:     */
                   7880:     margin-left: -1px;
                   7881: }
                   7882: 
1.843     bisitz   7883: ul.LC_funclist li {
1.915     droeschl 7884:   display: inline;
1.782     bisitz   7885:   white-space: nowrap;
1.915     droeschl 7886:   margin: 0 0 0 25px;
                   7887:   line-height: 150%;
1.782     bisitz   7888: }
                   7889: 
1.974     wenzelju 7890: .LC_hidden {
                   7891:   display: none;
                   7892: }
                   7893: 
1.1030    www      7894: .LCmodal-overlay {
                   7895: 		position:fixed;
                   7896: 		top:0;
                   7897: 		right:0;
                   7898: 		bottom:0;
                   7899: 		left:0;
                   7900: 		height:100%;
                   7901: 		width:100%;
                   7902: 		margin:0;
                   7903: 		padding:0;
                   7904: 		background:#999;
                   7905: 		opacity:.75;
                   7906: 		filter: alpha(opacity=75);
                   7907: 		-moz-opacity: 0.75;
                   7908: 		z-index:101;
                   7909: }
                   7910: 
                   7911: * html .LCmodal-overlay {   
                   7912: 		position: absolute;
                   7913: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7914: }
                   7915: 
                   7916: .LCmodal-window {
                   7917: 		position:fixed;
                   7918: 		top:50%;
                   7919: 		left:50%;
                   7920: 		margin:0;
                   7921: 		padding:0;
                   7922: 		z-index:102;
                   7923: 	}
                   7924: 
                   7925: * html .LCmodal-window {
                   7926: 		position:absolute;
                   7927: }
                   7928: 
                   7929: .LCclose-window {
                   7930: 		position:absolute;
                   7931: 		width:32px;
                   7932: 		height:32px;
                   7933: 		right:8px;
                   7934: 		top:8px;
                   7935: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7936: 		text-indent:-99999px;
                   7937: 		overflow:hidden;
                   7938: 		cursor:pointer;
                   7939: }
                   7940: 
1.1075.2.158  raeburn  7941: .LCisDisabled {
                   7942:   cursor: not-allowed;
                   7943:   opacity: 0.5;
                   7944: }
                   7945: 
                   7946: a[aria-disabled="true"] {
                   7947:   color: currentColor;
                   7948:   display: inline-block;  /* For IE11/ MS Edge bug */
                   7949:   pointer-events: none;
                   7950:   text-decoration: none;
                   7951: }
                   7952: 
1.1075.2.141  raeburn  7953: pre.LC_wordwrap {
                   7954:   white-space: pre-wrap;
                   7955:   white-space: -moz-pre-wrap;
                   7956:   white-space: -pre-wrap;
                   7957:   white-space: -o-pre-wrap;
                   7958:   word-wrap: break-word;
                   7959: }
                   7960: 
1.1075.2.17  raeburn  7961: /*
                   7962:   styles used by TTH when "Default set of options to pass to tth/m
                   7963:   when converting TeX" in course settings has been set
                   7964: 
                   7965:   option passed: -t
                   7966: 
                   7967: */
                   7968: 
                   7969: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7970: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7971: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7972: td div.norm {line-height:normal;}
                   7973: 
                   7974: /*
                   7975:   option passed -y3
                   7976: */
                   7977: 
                   7978: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7979: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7980: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7981: 
1.1075.2.121  raeburn  7982: #LC_minitab_header {
                   7983:   float:left;
                   7984:   width:100%;
                   7985:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   7986:   font-size:93%;
                   7987:   line-height:normal;
                   7988:   margin: 0.5em 0 0.5em 0;
                   7989: }
                   7990: #LC_minitab_header ul {
                   7991:   margin:0;
                   7992:   padding:10px 10px 0;
                   7993:   list-style:none;
                   7994: }
                   7995: #LC_minitab_header li {
                   7996:   float:left;
                   7997:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   7998:   margin:0;
                   7999:   padding:0 0 0 9px;
                   8000: }
                   8001: #LC_minitab_header a {
                   8002:   display:block;
                   8003:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8004:   padding:5px 15px 4px 6px;
                   8005: }
                   8006: #LC_minitab_header #LC_current_minitab {
                   8007:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8008: }
                   8009: #LC_minitab_header #LC_current_minitab a {
                   8010:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8011:   padding-bottom:5px;
                   8012: }
                   8013: 
                   8014: 
1.343     albertel 8015: END
                   8016: }
                   8017: 
1.306     albertel 8018: =pod
                   8019: 
                   8020: =item * &headtag()
                   8021: 
                   8022: Returns a uniform footer for LON-CAPA web pages.
                   8023: 
1.307     albertel 8024: Inputs: $title - optional title for the head
                   8025:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8026:         $args - optional arguments
1.319     albertel 8027:             force_register - if is true call registerurl so the remote is 
                   8028:                              informed
1.415     albertel 8029:             redirect       -> array ref of
                   8030:                                    1- seconds before redirect occurs
                   8031:                                    2- url to redirect to
                   8032:                                    3- whether the side effect should occur
1.315     albertel 8033:                            (side effect of setting 
                   8034:                                $env{'internal.head.redirect'} to the url 
                   8035:                                redirected too)
1.352     albertel 8036:             domain         -> force to color decorate a page for a specific
                   8037:                                domain
                   8038:             function       -> force usage of a specific rolish color scheme
                   8039:             bgcolor        -> override the default page bgcolor
1.460     albertel 8040:             no_auto_mt_title
                   8041:                            -> prevent &mt()ing the title arg
1.464     albertel 8042: 
1.306     albertel 8043: =cut
                   8044: 
                   8045: sub headtag {
1.313     albertel 8046:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8047:     
1.363     albertel 8048:     my $function = $args->{'function'} || &get_users_function();
                   8049:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8050:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  8051:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8052:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8053: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8054: 		   #time(),
1.418     albertel 8055: 		   $env{'environment.color.timestamp'},
1.363     albertel 8056: 		   $function,$domain,$bgcolor);
                   8057: 
1.369     www      8058:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8059: 
1.308     albertel 8060:     my $result =
                   8061: 	'<head>'.
1.1075.2.56  raeburn  8062: 	&font_settings($args);
1.319     albertel 8063: 
1.1075.2.72  raeburn  8064:     my $inhibitprint;
                   8065:     if ($args->{'print_suppress'}) {
                   8066:         $inhibitprint = &print_suppression();
                   8067:     }
1.1064    raeburn  8068: 
1.461     albertel 8069:     if (!$args->{'frameset'}) {
                   8070: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8071:     }
1.1075.2.12  raeburn  8072:     if ($args->{'force_register'}) {
                   8073:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 8074:     }
1.436     albertel 8075:     if (!$args->{'no_nav_bar'} 
                   8076: 	&& !$args->{'only_body'}
                   8077: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  8078: 	$result .= &help_menu_js($httphost);
1.1032    www      8079:         $result.=&modal_window();
1.1038    www      8080:         $result.=&togglebox_script();
1.1034    www      8081:         $result.=&wishlist_window();
1.1041    www      8082:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8083:     } else {
                   8084:         if ($args->{'add_modal'}) {
                   8085:            $result.=&modal_window();
                   8086:         }
                   8087:         if ($args->{'add_wishlist'}) {
                   8088:            $result.=&wishlist_window();
                   8089:         }
1.1038    www      8090:         if ($args->{'add_togglebox'}) {
                   8091:            $result.=&togglebox_script();
                   8092:         }
1.1041    www      8093:         if ($args->{'add_progressbar'}) {
                   8094:            $result.=&LCprogressbarUpdate_script();
                   8095:         }
1.436     albertel 8096:     }
1.314     albertel 8097:     if (ref($args->{'redirect'})) {
1.414     albertel 8098: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8099: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8100: 	if (!$inhibit_continue) {
                   8101: 	    $env{'internal.head.redirect'} = $url;
                   8102: 	}
1.313     albertel 8103: 	$result.=<<ADDMETA
                   8104: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8105: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8106: ADDMETA
1.1075.2.89  raeburn  8107:     } else {
                   8108:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8109:             my $requrl = $env{'request.uri'};
                   8110:             if ($requrl eq '') {
                   8111:                 $requrl = $ENV{'REQUEST_URI'};
                   8112:                 $requrl =~ s/\?.+$//;
                   8113:             }
                   8114:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8115:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8116:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8117:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8118:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8119:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1075.2.145  raeburn  8120:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1075.2.151  raeburn  8121:                     my ($offload,$offloadoth);
1.1075.2.89  raeburn  8122:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8123:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1075.2.145  raeburn  8124:                             $offload = 1;
1.1075.2.151  raeburn  8125:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8126:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8127:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8128:                                     $offloadoth = 1;
                   8129:                                     $dom_in_use = $env{'user.domain'};
                   8130:                                 }
                   8131:                             }
1.1075.2.145  raeburn  8132:                         }
                   8133:                     }
                   8134:                     unless ($offload) {
                   8135:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8136:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8137:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8138:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8139:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8140:                                         $offload = 1;
1.1075.2.151  raeburn  8141:                                         $offloadoth = 1;
1.1075.2.145  raeburn  8142:                                         $dom_in_use = $env{'user.domain'};
                   8143:                                     }
1.1075.2.89  raeburn  8144:                                 }
1.1075.2.145  raeburn  8145:                             }
                   8146:                         }
                   8147:                     }
                   8148:                     if ($offload) {
1.1075.2.158  raeburn  8149:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1075.2.151  raeburn  8150:                         if (($newserver eq '') && ($offloadoth)) {
                   8151:                             my @domains = &Apache::lonnet::current_machine_domains();
                   8152:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   8153:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   8154:                             }
                   8155:                         }
1.1075.2.145  raeburn  8156:                         if (($newserver) && ($newserver ne $lonhost)) {
                   8157:                             my $numsec = 5;
                   8158:                             my $timeout = $numsec * 1000;
                   8159:                             my ($newurl,$locknum,%locks,$msg);
                   8160:                             if ($env{'request.role.adv'}) {
                   8161:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8162:                             }
                   8163:                             my $disable_submit = 0;
                   8164:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8165:                                 $disable_submit = 1;
                   8166:                             }
                   8167:                             if ($locknum) {
                   8168:                                 my @lockinfo = sort(values(%locks));
1.1075.2.153  raeburn  8169:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1075.2.145  raeburn  8170:                                        join(", ",sort(values(%locks)))."\n";
                   8171:                                 if (&show_course()) {
                   8172:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
1.1075.2.89  raeburn  8173:                                 } else {
1.1075.2.145  raeburn  8174:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
                   8175:                                 }
                   8176:                             } else {
                   8177:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8178:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8179:                                 }
                   8180:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8181:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8182:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8183:                                     $newurl .= '&role='.$env{'request.role'};
                   8184:                                 }
                   8185:                                 if ($env{'request.symb'}) {
                   8186:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8187:                                     if ($shownsymb =~ m{^/enc/}) {
                   8188:                                         my $reqdmajor = 2;
                   8189:                                         my $reqdminor = 11;
                   8190:                                         my $reqdsubminor = 3;
                   8191:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8192:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8193:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8194:                                         if (($major eq '' && $minor eq '') ||
                   8195:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8196:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8197:                                              ($reqdsubminor > $subminor))))) {
                   8198:                                             undef($shownsymb);
                   8199:                                         }
1.1075.2.89  raeburn  8200:                                     }
1.1075.2.145  raeburn  8201:                                     if ($shownsymb) {
                   8202:                                         &js_escape(\$shownsymb);
                   8203:                                         $newurl .= '&symb='.$shownsymb;
1.1075.2.89  raeburn  8204:                                     }
1.1075.2.145  raeburn  8205:                                 } else {
                   8206:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8207:                                     &js_escape(\$shownurl);
                   8208:                                     $newurl .= '&origurl='.$shownurl;
1.1075.2.89  raeburn  8209:                                 }
1.1075.2.145  raeburn  8210:                             }
                   8211:                             &js_escape(\$msg);
                   8212:                             $result.=<<OFFLOAD
1.1075.2.89  raeburn  8213: <meta http-equiv="pragma" content="no-cache" />
                   8214: <script type="text/javascript">
1.1075.2.92  raeburn  8215: // <![CDATA[
1.1075.2.89  raeburn  8216: function LC_Offload_Now() {
                   8217:     var dest = "$newurl";
                   8218:     if (dest != '') {
                   8219:         window.location.href="$newurl";
                   8220:     }
                   8221: }
1.1075.2.92  raeburn  8222: \$(document).ready(function () {
                   8223:     window.alert('$msg');
                   8224:     if ($disable_submit) {
1.1075.2.89  raeburn  8225:         \$(".LC_hwk_submit").prop("disabled", true);
                   8226:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  8227:     }
                   8228:     setTimeout('LC_Offload_Now()', $timeout);
                   8229: });
                   8230: // ]]>
1.1075.2.89  raeburn  8231: </script>
                   8232: OFFLOAD
                   8233:                         }
                   8234:                     }
                   8235:                 }
                   8236:             }
                   8237:         }
1.313     albertel 8238:     }
1.306     albertel 8239:     if (!defined($title)) {
                   8240: 	$title = 'The LearningOnline Network with CAPA';
                   8241:     }
1.460     albertel 8242:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8243:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  8244: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8245:     if (!$args->{'frameset'}) {
                   8246:         $result .= ' /';
                   8247:     }
                   8248:     $result .= '>'
1.1064    raeburn  8249:         .$inhibitprint
1.414     albertel 8250: 	.$head_extra;
1.1075.2.108  raeburn  8251:     my $clientmobile;
                   8252:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8253:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8254:     } else {
                   8255:         $clientmobile = $env{'browser.mobile'};
                   8256:     }
                   8257:     if ($clientmobile) {
1.1075.2.42  raeburn  8258:         $result .= '
                   8259: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8260: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8261:     }
1.1075.2.126  raeburn  8262:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8263:     return $result.'</head>';
1.306     albertel 8264: }
                   8265: 
                   8266: =pod
                   8267: 
1.340     albertel 8268: =item * &font_settings()
                   8269: 
                   8270: Returns neccessary <meta> to set the proper encoding
                   8271: 
1.1075.2.56  raeburn  8272: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8273: 
                   8274: =cut
                   8275: 
                   8276: sub font_settings {
1.1075.2.56  raeburn  8277:     my ($args) = @_;
1.340     albertel 8278:     my $headerstring='';
1.1075.2.56  raeburn  8279:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8280:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 8281: 	$headerstring.=
1.1075.2.61  raeburn  8282: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8283:         if (!$args->{'frameset'}) {
                   8284:             $headerstring.= ' /';
                   8285:         }
                   8286:         $headerstring .= '>'."\n";
1.340     albertel 8287:     }
                   8288:     return $headerstring;
                   8289: }
                   8290: 
1.341     albertel 8291: =pod
                   8292: 
1.1064    raeburn  8293: =item * &print_suppression()
                   8294: 
                   8295: In course context returns css which causes the body to be blank when media="print",
                   8296: if printout generation is unavailable for the current resource.
                   8297: 
                   8298: This could be because:
                   8299: 
                   8300: (a) printstartdate is in the future
                   8301: 
                   8302: (b) printenddate is in the past
                   8303: 
                   8304: (c) there is an active exam block with "printout"
                   8305: functionality blocked
                   8306: 
                   8307: Users with pav, pfo or evb privileges are exempt.
                   8308: 
                   8309: Inputs: none
                   8310: 
                   8311: =cut
                   8312: 
                   8313: 
                   8314: sub print_suppression {
                   8315:     my $noprint;
                   8316:     if ($env{'request.course.id'}) {
                   8317:         my $scope = $env{'request.course.id'};
                   8318:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8319:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8320:             return;
                   8321:         }
                   8322:         if ($env{'request.course.sec'} ne '') {
                   8323:             $scope .= "/$env{'request.course.sec'}";
                   8324:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8325:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8326:                 return;
1.1064    raeburn  8327:             }
                   8328:         }
                   8329:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8330:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.158  raeburn  8331:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   8332:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  8333:         if ($blocked) {
                   8334:             my $checkrole = "cm./$cdom/$cnum";
                   8335:             if ($env{'request.course.sec'} ne '') {
                   8336:                 $checkrole .= "/$env{'request.course.sec'}";
                   8337:             }
                   8338:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8339:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8340:                 $noprint = 1;
                   8341:             }
                   8342:         }
                   8343:         unless ($noprint) {
                   8344:             my $symb = &Apache::lonnet::symbread();
                   8345:             if ($symb ne '') {
                   8346:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8347:                 if (ref($navmap)) {
                   8348:                     my $res = $navmap->getBySymb($symb);
                   8349:                     if (ref($res)) {
                   8350:                         if (!$res->resprintable()) {
                   8351:                             $noprint = 1;
                   8352:                         }
                   8353:                     }
                   8354:                 }
                   8355:             }
                   8356:         }
                   8357:         if ($noprint) {
                   8358:             return <<"ENDSTYLE";
                   8359: <style type="text/css" media="print">
                   8360:     body { display:none }
                   8361: </style>
                   8362: ENDSTYLE
                   8363:         }
                   8364:     }
                   8365:     return;
                   8366: }
                   8367: 
                   8368: =pod
                   8369: 
1.341     albertel 8370: =item * &xml_begin()
                   8371: 
                   8372: Returns the needed doctype and <html>
                   8373: 
                   8374: Inputs: none
                   8375: 
                   8376: =cut
                   8377: 
                   8378: sub xml_begin {
1.1075.2.61  raeburn  8379:     my ($is_frameset) = @_;
1.341     albertel 8380:     my $output='';
                   8381: 
                   8382:     if ($env{'browser.mathml'}) {
                   8383: 	$output='<?xml version="1.0"?>'
                   8384:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8385: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8386:             
                   8387: #	    .'<!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">] >'
                   8388: 	    .'<!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">'
                   8389:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8390: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  8391:     } elsif ($is_frameset) {
                   8392:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8393:                 '<html>'."\n";
1.341     albertel 8394:     } else {
1.1075.2.61  raeburn  8395: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8396:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8397:     }
                   8398:     return $output;
                   8399: }
1.340     albertel 8400: 
                   8401: =pod
                   8402: 
1.306     albertel 8403: =item * &start_page()
                   8404: 
                   8405: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8406: 
1.648     raeburn  8407: Inputs:
                   8408: 
                   8409: =over 4
                   8410: 
                   8411: $title - optional title for the page
                   8412: 
                   8413: $head_extra - optional extra HTML to incude inside the <head>
                   8414: 
                   8415: $args - additional optional args supported are:
                   8416: 
                   8417: =over 8
                   8418: 
                   8419:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8420:                                     arg on
1.814     bisitz   8421:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8422:              add_entries    -> additional attributes to add to the  <body>
                   8423:              domain         -> force to color decorate a page for a 
1.317     albertel 8424:                                     specific domain
1.648     raeburn  8425:              function       -> force usage of a specific rolish color
1.317     albertel 8426:                                     scheme
1.648     raeburn  8427:              redirect       -> see &headtag()
                   8428:              bgcolor        -> override the default page bg color
                   8429:              js_ready       -> return a string ready for being used in 
1.317     albertel 8430:                                     a javascript writeln
1.648     raeburn  8431:              html_encode    -> return a string ready for being used in 
1.320     albertel 8432:                                     a html attribute
1.648     raeburn  8433:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8434:                                     $forcereg arg
1.648     raeburn  8435:              frameset       -> if true will start with a <frameset>
1.330     albertel 8436:                                     rather than <body>
1.648     raeburn  8437:              skip_phases    -> hash ref of 
1.338     albertel 8438:                                     head -> skip the <html><head> generation
                   8439:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8440:              no_inline_link -> if true and in remote mode, don't show the
                   8441:                                     'Switch To Inline Menu' link
1.648     raeburn  8442:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8443:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8444:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  8445:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8446:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  8447:              group          -> includes the current group, if page is for a
                   8448:                                specific group
1.1075.2.133  raeburn  8449:              use_absolute   -> for request for external resource or syllabus, this
                   8450:                                will contain https://<hostname> if server uses
                   8451:                                https (as per hosts.tab), but request is for http
                   8452:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1075.2.158  raeburn  8453:              links_disabled -> Links in primary and secondary menus are disabled
                   8454:                                (Can enable them once page has loaded - see lonroles.pm
                   8455:                                for an example).
1.361     albertel 8456: 
1.648     raeburn  8457: =back
1.460     albertel 8458: 
1.648     raeburn  8459: =back
1.562     albertel 8460: 
1.306     albertel 8461: =cut
                   8462: 
                   8463: sub start_page {
1.309     albertel 8464:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8465:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8466: 
1.315     albertel 8467:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  8468:     my ($result,@advtools);
1.964     droeschl 8469: 
1.338     albertel 8470:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8471:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8472:     }
                   8473:     
                   8474:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8475: 	if ($args->{'frameset'}) {
                   8476: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8477: 						$args->{'add_entries'});
                   8478: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8479:         } else {
                   8480:             $result .=
                   8481:                 &bodytag($title, 
                   8482:                          $args->{'function'},       $args->{'add_entries'},
                   8483:                          $args->{'only_body'},      $args->{'domain'},
                   8484:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8485:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  8486:                          $args,                     \@advtools);
1.831     bisitz   8487:         }
1.330     albertel 8488:     }
1.338     albertel 8489: 
1.315     albertel 8490:     if ($args->{'js_ready'}) {
1.713     kaisler  8491: 		$result = &js_ready($result);
1.315     albertel 8492:     }
1.320     albertel 8493:     if ($args->{'html_encode'}) {
1.713     kaisler  8494: 		$result = &html_encode($result);
                   8495:     }
                   8496: 
1.813     bisitz   8497:     # Preparation for new and consistent functionlist at top of screen
                   8498:     # if ($args->{'functionlist'}) {
                   8499:     #            $result .= &build_functionlist();
                   8500:     #}
                   8501: 
1.964     droeschl 8502:     # Don't add anything more if only_body wanted or in const space
                   8503:     return $result if    $args->{'only_body'} 
                   8504:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8505: 
                   8506:     #Breadcrumbs
1.758     kaisler  8507:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8508: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8509: 		#if any br links exists, add them to the breadcrumbs
                   8510: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8511: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8512: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8513: 			}
                   8514: 		}
1.1075.2.19  raeburn  8515:                 # if @advtools array contains items add then to the breadcrumbs
                   8516:                 if (@advtools > 0) {
                   8517:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8518:                 }
1.1075.2.123  raeburn  8519:                 my $menulink;
                   8520:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8521:                 if (exists($args->{'bread_crumbs_nomenu'})) {
                   8522:                     $menulink = 0;
                   8523:                 } else {
                   8524:                     undef($menulink);
                   8525:                 }
1.758     kaisler  8526: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8527: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  8528: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.758     kaisler  8529: 		}else{
1.1075.2.123  raeburn  8530: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8531: 		}
1.1075.2.24  raeburn  8532:     } elsif (($env{'environment.remote'} eq 'on') &&
                   8533:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   8534:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   8535:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  8536:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 8537:     }
1.315     albertel 8538:     return $result;
1.306     albertel 8539: }
                   8540: 
                   8541: sub end_page {
1.315     albertel 8542:     my ($args) = @_;
                   8543:     $env{'internal.end_page'}++;
1.330     albertel 8544:     my $result;
1.335     albertel 8545:     if ($args->{'discussion'}) {
                   8546: 	my ($target,$parser);
                   8547: 	if (ref($args->{'discussion'})) {
                   8548: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8549: 				$args->{'discussion'}{'parser'});
                   8550: 	}
                   8551: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8552:     }
1.330     albertel 8553:     if ($args->{'frameset'}) {
                   8554: 	$result .= '</frameset>';
                   8555:     } else {
1.635     raeburn  8556: 	$result .= &endbodytag($args);
1.330     albertel 8557:     }
1.1075.2.6  raeburn  8558:     unless ($args->{'notbody'}) {
                   8559:         $result .= "\n</html>";
                   8560:     }
1.330     albertel 8561: 
1.315     albertel 8562:     if ($args->{'js_ready'}) {
1.317     albertel 8563: 	$result = &js_ready($result);
1.315     albertel 8564:     }
1.335     albertel 8565: 
1.320     albertel 8566:     if ($args->{'html_encode'}) {
                   8567: 	$result = &html_encode($result);
                   8568:     }
1.335     albertel 8569: 
1.315     albertel 8570:     return $result;
                   8571: }
                   8572: 
1.1034    www      8573: sub wishlist_window {
                   8574:     return(<<'ENDWISHLIST');
1.1046    raeburn  8575: <script type="text/javascript">
1.1034    www      8576: // <![CDATA[
                   8577: // <!-- BEGIN LON-CAPA Internal
                   8578: function set_wishlistlink(title, path) {
                   8579:     if (!title) {
                   8580:         title = document.title;
                   8581:         title = title.replace(/^LON-CAPA /,'');
                   8582:     }
1.1075.2.65  raeburn  8583:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  8584:     title = title.replace("'","\\\'");
1.1034    www      8585:     if (!path) {
                   8586:         path = location.pathname;
                   8587:     }
1.1075.2.65  raeburn  8588:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  8589:     path = path.replace("'","\\\'");
1.1034    www      8590:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8591:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8592: }
                   8593: // END LON-CAPA Internal -->
                   8594: // ]]>
                   8595: </script>
                   8596: ENDWISHLIST
                   8597: }
                   8598: 
1.1030    www      8599: sub modal_window {
                   8600:     return(<<'ENDMODAL');
1.1046    raeburn  8601: <script type="text/javascript">
1.1030    www      8602: // <![CDATA[
                   8603: // <!-- BEGIN LON-CAPA Internal
                   8604: var modalWindow = {
                   8605: 	parent:"body",
                   8606: 	windowId:null,
                   8607: 	content:null,
                   8608: 	width:null,
                   8609: 	height:null,
                   8610: 	close:function()
                   8611: 	{
                   8612: 	        $(".LCmodal-window").remove();
                   8613: 	        $(".LCmodal-overlay").remove();
                   8614: 	},
                   8615: 	open:function()
                   8616: 	{
                   8617: 		var modal = "";
                   8618: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8619: 		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;\">";
                   8620: 		modal += this.content;
                   8621: 		modal += "</div>";	
                   8622: 
                   8623: 		$(this.parent).append(modal);
                   8624: 
                   8625: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8626: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8627: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8628: 	}
                   8629: };
1.1075.2.42  raeburn  8630: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8631: 	{
1.1075.2.119  raeburn  8632:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8633: 		modalWindow.windowId = "myModal";
                   8634: 		modalWindow.width = width;
                   8635: 		modalWindow.height = height;
1.1075.2.80  raeburn  8636: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8637: 		modalWindow.open();
1.1075.2.87  raeburn  8638: 	};
1.1030    www      8639: // END LON-CAPA Internal -->
                   8640: // ]]>
                   8641: </script>
                   8642: ENDMODAL
                   8643: }
                   8644: 
                   8645: sub modal_link {
1.1075.2.42  raeburn  8646:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8647:     unless ($width) { $width=480; }
                   8648:     unless ($height) { $height=400; }
1.1031    www      8649:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  8650:     unless ($transparency) { $transparency='true'; }
                   8651: 
1.1074    raeburn  8652:     my $target_attr;
                   8653:     if (defined($target)) {
                   8654:         $target_attr = 'target="'.$target.'"';
                   8655:     }
                   8656:     return <<"ENDLINK";
1.1075.2.143  raeburn  8657: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  8658: ENDLINK
1.1030    www      8659: }
                   8660: 
1.1032    www      8661: sub modal_adhoc_script {
1.1075.2.155  raeburn  8662:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   8663:     my $mathjax;
                   8664:     if ($possmathjax) {
                   8665:         $mathjax = <<'ENDJAX';
                   8666:                if (typeof MathJax == 'object') {
                   8667:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   8668:                }
                   8669: ENDJAX
                   8670:     }
1.1032    www      8671:     return (<<ENDADHOC);
1.1046    raeburn  8672: <script type="text/javascript">
1.1032    www      8673: // <![CDATA[
                   8674:         var $funcname = function()
                   8675:         {
                   8676:                 modalWindow.windowId = "myModal";
                   8677:                 modalWindow.width = $width;
                   8678:                 modalWindow.height = $height;
                   8679:                 modalWindow.content = '$content';
                   8680:                 modalWindow.open();
1.1075.2.155  raeburn  8681:                 $mathjax
1.1032    www      8682:         };  
                   8683: // ]]>
                   8684: </script>
                   8685: ENDADHOC
                   8686: }
                   8687: 
1.1041    www      8688: sub modal_adhoc_inner {
1.1075.2.155  raeburn  8689:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      8690:     my $innerwidth=$width-20;
                   8691:     $content=&js_ready(
1.1042    www      8692:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  8693:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8694:                  $content.
1.1041    www      8695:                  &end_scrollbox().
1.1075.2.42  raeburn  8696:                  &end_page()
1.1041    www      8697:              );
1.1075.2.155  raeburn  8698:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      8699: }
                   8700: 
                   8701: sub modal_adhoc_window {
1.1075.2.155  raeburn  8702:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   8703:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      8704:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8705: }
                   8706: 
                   8707: sub modal_adhoc_launch {
                   8708:     my ($funcname,$width,$height,$content)=@_;
                   8709:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8710: <script type="text/javascript">
                   8711: // <![CDATA[
                   8712: $funcname();
                   8713: // ]]>
                   8714: </script>
                   8715: ENDLAUNCH
                   8716: }
                   8717: 
                   8718: sub modal_adhoc_close {
                   8719:     return (<<ENDCLOSE);
                   8720: <script type="text/javascript">
                   8721: // <![CDATA[
                   8722: modalWindow.close();
                   8723: // ]]>
                   8724: </script>
                   8725: ENDCLOSE
                   8726: }
                   8727: 
1.1038    www      8728: sub togglebox_script {
                   8729:    return(<<ENDTOGGLE);
                   8730: <script type="text/javascript"> 
                   8731: // <![CDATA[
                   8732: function LCtoggleDisplay(id,hidetext,showtext) {
                   8733:    link = document.getElementById(id + "link").childNodes[0];
                   8734:    with (document.getElementById(id).style) {
                   8735:       if (display == "none" ) {
                   8736:           display = "inline";
                   8737:           link.nodeValue = hidetext;
                   8738:         } else {
                   8739:           display = "none";
                   8740:           link.nodeValue = showtext;
                   8741:        }
                   8742:    }
                   8743: }
                   8744: // ]]>
                   8745: </script>
                   8746: ENDTOGGLE
                   8747: }
                   8748: 
1.1039    www      8749: sub start_togglebox {
                   8750:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8751:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8752:     unless ($showtext) { $showtext=&mt('show'); }
                   8753:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8754:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8755:     return &start_data_table().
                   8756:            &start_data_table_header_row().
                   8757:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8758:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8759:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8760:            &end_data_table_header_row().
                   8761:            '<tr id="'.$id.'" style="display:none""><td>';
                   8762: }
                   8763: 
                   8764: sub end_togglebox {
                   8765:     return '</td></tr>'.&end_data_table();
                   8766: }
                   8767: 
1.1041    www      8768: sub LCprogressbar_script {
1.1075.2.130  raeburn  8769:    my ($id,$number_to_do)=@_;
                   8770:    if ($number_to_do) {
                   8771:        return(<<ENDPROGRESS);
1.1041    www      8772: <script type="text/javascript">
                   8773: // <![CDATA[
1.1045    www      8774: \$('#progressbar$id').progressbar({
1.1041    www      8775:   value: 0,
                   8776:   change: function(event, ui) {
                   8777:     var newVal = \$(this).progressbar('option', 'value');
                   8778:     \$('.pblabel', this).text(LCprogressTxt);
                   8779:   }
                   8780: });
                   8781: // ]]>
                   8782: </script>
                   8783: ENDPROGRESS
1.1075.2.130  raeburn  8784:    } else {
                   8785:        return(<<ENDPROGRESS);
                   8786: <script type="text/javascript">
                   8787: // <![CDATA[
                   8788: \$('#progressbar$id').progressbar({
                   8789:   value: false,
                   8790:   create: function(event, ui) {
                   8791:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   8792:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   8793:   }
                   8794: });
                   8795: // ]]>
                   8796: </script>
                   8797: ENDPROGRESS
                   8798:    }
1.1041    www      8799: }
                   8800: 
                   8801: sub LCprogressbarUpdate_script {
                   8802:    return(<<ENDPROGRESSUPDATE);
                   8803: <style type="text/css">
                   8804: .ui-progressbar { position:relative; }
1.1075.2.130  raeburn  8805: .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      8806: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8807: </style>
                   8808: <script type="text/javascript">
                   8809: // <![CDATA[
1.1045    www      8810: var LCprogressTxt='---';
                   8811: 
1.1075.2.130  raeburn  8812: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      8813:    LCprogressTxt=progresstext;
1.1075.2.130  raeburn  8814:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   8815:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   8816:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
                   8817:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   8818:    } else {
                   8819:        \$('#progressbar'+id).progressbar('value',percent);
                   8820:    }
1.1041    www      8821: }
                   8822: // ]]>
                   8823: </script>
                   8824: ENDPROGRESSUPDATE
                   8825: }
                   8826: 
1.1042    www      8827: my $LClastpercent;
1.1045    www      8828: my $LCidcnt;
                   8829: my $LCcurrentid;
1.1042    www      8830: 
1.1041    www      8831: sub LCprogressbar {
1.1075.2.130  raeburn  8832:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      8833:     $LClastpercent=0;
1.1045    www      8834:     $LCidcnt++;
                   8835:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1075.2.130  raeburn  8836:     my ($starting,$content);
                   8837:     if ($number_to_do) {
                   8838:         $starting=&mt('Starting');
                   8839:         $content=(<<ENDPROGBAR);
                   8840: $preamble
1.1045    www      8841:   <div id="progressbar$LCcurrentid">
1.1041    www      8842:     <span class="pblabel">$starting</span>
                   8843:   </div>
                   8844: ENDPROGBAR
1.1075.2.130  raeburn  8845:     } else {
                   8846:         $starting=&mt('Loading...');
                   8847:         $LClastpercent='false';
                   8848:         $content=(<<ENDPROGBAR);
                   8849: $preamble
                   8850:   <div id="progressbar$LCcurrentid">
                   8851:       <div class="progress-label">$starting</div>
                   8852:   </div>
                   8853: ENDPROGBAR
                   8854:     }
                   8855:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      8856: }
                   8857: 
                   8858: sub LCprogressbarUpdate {
1.1075.2.130  raeburn  8859:     my ($r,$val,$text,$number_to_do)=@_;
                   8860:     if ($number_to_do) {
                   8861:         unless ($val) { 
                   8862:             if ($LClastpercent) {
                   8863:                 $val=$LClastpercent;
                   8864:             } else {
                   8865:                 $val=0;
                   8866:             }
                   8867:         }
                   8868:         if ($val<0) { $val=0; }
                   8869:         if ($val>100) { $val=0; }
                   8870:         $LClastpercent=$val;
                   8871:         unless ($text) { $text=$val.'%'; }
                   8872:     } else {
                   8873:         $val = 'false';
1.1042    www      8874:     }
1.1041    www      8875:     $text=&js_ready($text);
1.1044    www      8876:     &r_print($r,<<ENDUPDATE);
1.1041    www      8877: <script type="text/javascript">
                   8878: // <![CDATA[
1.1075.2.130  raeburn  8879: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      8880: // ]]>
                   8881: </script>
                   8882: ENDUPDATE
1.1035    www      8883: }
                   8884: 
1.1042    www      8885: sub LCprogressbarClose {
                   8886:     my ($r)=@_;
                   8887:     $LClastpercent=0;
1.1044    www      8888:     &r_print($r,<<ENDCLOSE);
1.1042    www      8889: <script type="text/javascript">
                   8890: // <![CDATA[
1.1045    www      8891: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8892: // ]]>
                   8893: </script>
                   8894: ENDCLOSE
1.1044    www      8895: }
                   8896: 
                   8897: sub r_print {
                   8898:     my ($r,$to_print)=@_;
                   8899:     if ($r) {
                   8900:       $r->print($to_print);
                   8901:       $r->rflush();
                   8902:     } else {
                   8903:       print($to_print);
                   8904:     }
1.1042    www      8905: }
                   8906: 
1.320     albertel 8907: sub html_encode {
                   8908:     my ($result) = @_;
                   8909: 
1.322     albertel 8910:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8911:     
                   8912:     return $result;
                   8913: }
1.1044    www      8914: 
1.317     albertel 8915: sub js_ready {
                   8916:     my ($result) = @_;
                   8917: 
1.323     albertel 8918:     $result =~ s/[\n\r]/ /xmsg;
                   8919:     $result =~ s/\\/\\\\/xmsg;
                   8920:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8921:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8922:     
                   8923:     return $result;
                   8924: }
                   8925: 
1.315     albertel 8926: sub validate_page {
                   8927:     if (  exists($env{'internal.start_page'})
1.316     albertel 8928: 	  &&     $env{'internal.start_page'} > 1) {
                   8929: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8930: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8931: 				 $ENV{'request.filename'});
1.315     albertel 8932:     }
                   8933:     if (  exists($env{'internal.end_page'})
1.316     albertel 8934: 	  &&     $env{'internal.end_page'} > 1) {
                   8935: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8936: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8937: 				 $env{'request.filename'});
1.315     albertel 8938:     }
                   8939:     if (     exists($env{'internal.start_page'})
                   8940: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8941: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8942: 				 $env{'request.filename'});
1.315     albertel 8943:     }
                   8944:     if (   ! exists($env{'internal.start_page'})
                   8945: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8946: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8947: 				 $env{'request.filename'});
1.315     albertel 8948:     }
1.306     albertel 8949: }
1.315     albertel 8950: 
1.996     www      8951: 
                   8952: sub start_scrollbox {
1.1075.2.56  raeburn  8953:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8954:     unless ($outerwidth) { $outerwidth='520px'; }
                   8955:     unless ($width) { $width='500px'; }
                   8956:     unless ($height) { $height='200px'; }
1.1075    raeburn  8957:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8958:     if ($id ne '') {
1.1075.2.42  raeburn  8959:         $table_id = ' id="table_'.$id.'"';
                   8960:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8961:     }
1.1075    raeburn  8962:     if ($bgcolor ne '') {
                   8963:         $tdcol = "background-color: $bgcolor;";
                   8964:     }
1.1075.2.42  raeburn  8965:     my $nicescroll_js;
                   8966:     if ($env{'browser.mobile'}) {
                   8967:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8968:     }
1.1075    raeburn  8969:     return <<"END";
1.1075.2.42  raeburn  8970: $nicescroll_js
                   8971: 
                   8972: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8973: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8974: END
1.996     www      8975: }
                   8976: 
                   8977: sub end_scrollbox {
1.1036    www      8978:     return '</div></td></tr></table>';
1.996     www      8979: }
                   8980: 
1.1075.2.42  raeburn  8981: sub nicescroll_javascript {
                   8982:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8983:     my %options;
                   8984:     if (ref($cursor) eq 'HASH') {
                   8985:         %options = %{$cursor};
                   8986:     }
                   8987:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8988:         $options{'railalign'} = 'left';
                   8989:     }
                   8990:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8991:         my $function  = &get_users_function();
                   8992:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8993:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8994:             $options{'cursorcolor'} = '#00F';
                   8995:         }
                   8996:     }
                   8997:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8998:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8999:             $options{'cursoropacity'}='1.0';
                   9000:         }
                   9001:     } else {
                   9002:         $options{'cursoropacity'}='1.0';
                   9003:     }
                   9004:     if ($options{'cursorfixedheight'} eq 'none') {
                   9005:         delete($options{'cursorfixedheight'});
                   9006:     } else {
                   9007:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9008:     }
                   9009:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9010:         delete($options{'railoffset'});
                   9011:     }
                   9012:     my @niceoptions;
                   9013:     while (my($key,$value) = each(%options)) {
                   9014:         if ($value =~ /^\{.+\}$/) {
                   9015:             push(@niceoptions,$key.':'.$value);
                   9016:         } else {
                   9017:             push(@niceoptions,$key.':"'.$value.'"');
                   9018:         }
                   9019:     }
                   9020:     my $nicescroll_js = '
                   9021: $(document).ready(
                   9022:       function() {
                   9023:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9024:       }
                   9025: );
                   9026: ';
                   9027:     if ($framecheck) {
                   9028:         $nicescroll_js .= '
                   9029: function expand_div(caller) {
                   9030:     if (top === self) {
                   9031:         document.getElementById("'.$id.'").style.width = "auto";
                   9032:         document.getElementById("'.$id.'").style.height = "auto";
                   9033:     } else {
                   9034:         try {
                   9035:             if (parent.frames) {
                   9036:                 if (parent.frames.length > 1) {
                   9037:                     var framesrc = parent.frames[1].location.href;
                   9038:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9039:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9040:                         document.getElementById("'.$id.'").style.width = "auto";
                   9041:                         document.getElementById("'.$id.'").style.height = "auto";
                   9042:                     }
                   9043:                 }
                   9044:             }
                   9045:         } catch (e) {
                   9046:             return;
                   9047:         }
                   9048:     }
                   9049:     return;
                   9050: }
                   9051: ';
                   9052:     }
                   9053:     if ($needjsready) {
                   9054:         $nicescroll_js = '
                   9055: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9056:     } else {
                   9057:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9058:     }
                   9059:     return $nicescroll_js;
                   9060: }
                   9061: 
1.318     albertel 9062: sub simple_error_page {
1.1075.2.49  raeburn  9063:     my ($r,$title,$msg,$args) = @_;
                   9064:     if (ref($args) eq 'HASH') {
                   9065:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   9066:     } else {
                   9067:         $msg = &mt($msg);
                   9068:     }
                   9069: 
1.318     albertel 9070:     my $page =
                   9071: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  9072: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9073: 	&Apache::loncommon::end_page();
                   9074:     if (ref($r)) {
                   9075: 	$r->print($page);
1.327     albertel 9076: 	return;
1.318     albertel 9077:     }
                   9078:     return $page;
                   9079: }
1.347     albertel 9080: 
                   9081: {
1.610     albertel 9082:     my @row_count;
1.961     onken    9083: 
                   9084:     sub start_data_table_count {
                   9085:         unshift(@row_count, 0);
                   9086:         return;
                   9087:     }
                   9088: 
                   9089:     sub end_data_table_count {
                   9090:         shift(@row_count);
                   9091:         return;
                   9092:     }
                   9093: 
1.347     albertel 9094:     sub start_data_table {
1.1018    raeburn  9095: 	my ($add_class,$id) = @_;
1.422     albertel 9096: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9097:         my $table_id;
                   9098:         if (defined($id)) {
                   9099:             $table_id = ' id="'.$id.'"';
                   9100:         }
1.961     onken    9101: 	&start_data_table_count();
1.1018    raeburn  9102: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9103:     }
                   9104: 
                   9105:     sub end_data_table {
1.961     onken    9106: 	&end_data_table_count();
1.389     albertel 9107: 	return '</table>'."\n";;
1.347     albertel 9108:     }
                   9109: 
                   9110:     sub start_data_table_row {
1.974     wenzelju 9111: 	my ($add_class, $id) = @_;
1.610     albertel 9112: 	$row_count[0]++;
                   9113: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9114: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9115:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9116:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9117:     }
1.471     banghart 9118:     
                   9119:     sub continue_data_table_row {
1.974     wenzelju 9120: 	my ($add_class, $id) = @_;
1.610     albertel 9121: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9122: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9123:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9124:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9125:     }
1.347     albertel 9126: 
                   9127:     sub end_data_table_row {
1.389     albertel 9128: 	return '</tr>'."\n";;
1.347     albertel 9129:     }
1.367     www      9130: 
1.421     albertel 9131:     sub start_data_table_empty_row {
1.707     bisitz   9132: #	$row_count[0]++;
1.421     albertel 9133: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9134:     }
                   9135: 
                   9136:     sub end_data_table_empty_row {
                   9137: 	return '</tr>'."\n";;
                   9138:     }
                   9139: 
1.367     www      9140:     sub start_data_table_header_row {
1.389     albertel 9141: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9142:     }
                   9143: 
                   9144:     sub end_data_table_header_row {
1.389     albertel 9145: 	return '</tr>'."\n";;
1.367     www      9146:     }
1.890     droeschl 9147: 
                   9148:     sub data_table_caption {
                   9149:         my $caption = shift;
                   9150:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9151:     }
1.347     albertel 9152: }
                   9153: 
1.548     albertel 9154: =pod
                   9155: 
                   9156: =item * &inhibit_menu_check($arg)
                   9157: 
                   9158: Checks for a inhibitmenu state and generates output to preserve it
                   9159: 
                   9160: Inputs:         $arg - can be any of
                   9161:                      - undef - in which case the return value is a string 
                   9162:                                to add  into arguments list of a uri
                   9163:                      - 'input' - in which case the return value is a HTML
                   9164:                                  <form> <input> field of type hidden to
                   9165:                                  preserve the value
                   9166:                      - a url - in which case the return value is the url with
                   9167:                                the neccesary cgi args added to preserve the
                   9168:                                inhibitmenu state
                   9169:                      - a ref to a url - no return value, but the string is
                   9170:                                         updated to include the neccessary cgi
                   9171:                                         args to preserve the inhibitmenu state
                   9172: 
                   9173: =cut
                   9174: 
                   9175: sub inhibit_menu_check {
                   9176:     my ($arg) = @_;
                   9177:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9178:     if ($arg eq 'input') {
                   9179: 	if ($env{'form.inhibitmenu'}) {
                   9180: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9181: 	} else {
                   9182: 	    return
                   9183: 	}
                   9184:     }
                   9185:     if ($env{'form.inhibitmenu'}) {
                   9186: 	if (ref($arg)) {
                   9187: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9188: 	} elsif ($arg eq '') {
                   9189: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9190: 	} else {
                   9191: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9192: 	}
                   9193:     }
                   9194:     if (!ref($arg)) {
                   9195: 	return $arg;
                   9196:     }
                   9197: }
                   9198: 
1.251     albertel 9199: ###############################################
1.182     matthew  9200: 
                   9201: =pod
                   9202: 
1.549     albertel 9203: =back
                   9204: 
                   9205: =head1 User Information Routines
                   9206: 
                   9207: =over 4
                   9208: 
1.405     albertel 9209: =item * &get_users_function()
1.182     matthew  9210: 
                   9211: Used by &bodytag to determine the current users primary role.
                   9212: Returns either 'student','coordinator','admin', or 'author'.
                   9213: 
                   9214: =cut
                   9215: 
                   9216: ###############################################
                   9217: sub get_users_function {
1.815     tempelho 9218:     my $function = 'norole';
1.818     tempelho 9219:     if ($env{'request.role'}=~/^(st)/) {
                   9220:         $function='student';
                   9221:     }
1.907     raeburn  9222:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9223:         $function='coordinator';
                   9224:     }
1.258     albertel 9225:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9226:         $function='admin';
                   9227:     }
1.826     bisitz   9228:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9229:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9230:         $function='author';
                   9231:     }
                   9232:     return $function;
1.54      www      9233: }
1.99      www      9234: 
                   9235: ###############################################
                   9236: 
1.233     raeburn  9237: =pod
                   9238: 
1.821     raeburn  9239: =item * &show_course()
                   9240: 
                   9241: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9242: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9243: 
                   9244: Inputs:
                   9245: None
                   9246: 
                   9247: Outputs:
                   9248: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9249: 
                   9250: =cut
                   9251: 
                   9252: ###############################################
                   9253: sub show_course {
                   9254:     my $course = !$env{'user.adv'};
                   9255:     if (!$env{'user.adv'}) {
                   9256:         foreach my $env (keys(%env)) {
                   9257:             next if ($env !~ m/^user\.priv\./);
                   9258:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9259:                 $course = 0;
                   9260:                 last;
                   9261:             }
                   9262:         }
                   9263:     }
                   9264:     return $course;
                   9265: }
                   9266: 
                   9267: ###############################################
                   9268: 
                   9269: =pod
                   9270: 
1.542     raeburn  9271: =item * &check_user_status()
1.274     raeburn  9272: 
                   9273: Determines current status of supplied role for a
                   9274: specific user. Roles can be active, previous or future.
                   9275: 
                   9276: Inputs: 
                   9277: user's domain, user's username, course's domain,
1.375     raeburn  9278: course's number, optional section ID.
1.274     raeburn  9279: 
                   9280: Outputs:
                   9281: role status: active, previous or future. 
                   9282: 
                   9283: =cut
                   9284: 
                   9285: sub check_user_status {
1.412     raeburn  9286:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9287:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  9288:     my @uroles = keys(%userinfo);
1.274     raeburn  9289:     my $srchstr;
                   9290:     my $active_chk = 'none';
1.412     raeburn  9291:     my $now = time;
1.274     raeburn  9292:     if (@uroles > 0) {
1.908     raeburn  9293:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9294:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9295:         } else {
1.412     raeburn  9296:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9297:         }
                   9298:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9299:             my $role_end = 0;
                   9300:             my $role_start = 0;
                   9301:             $active_chk = 'active';
1.412     raeburn  9302:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9303:                 $role_end = $1;
                   9304:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9305:                     $role_start = $1;
1.274     raeburn  9306:                 }
                   9307:             }
                   9308:             if ($role_start > 0) {
1.412     raeburn  9309:                 if ($now < $role_start) {
1.274     raeburn  9310:                     $active_chk = 'future';
                   9311:                 }
                   9312:             }
                   9313:             if ($role_end > 0) {
1.412     raeburn  9314:                 if ($now > $role_end) {
1.274     raeburn  9315:                     $active_chk = 'previous';
                   9316:                 }
                   9317:             }
                   9318:         }
                   9319:     }
                   9320:     return $active_chk;
                   9321: }
                   9322: 
                   9323: ###############################################
                   9324: 
                   9325: =pod
                   9326: 
1.405     albertel 9327: =item * &get_sections()
1.233     raeburn  9328: 
                   9329: Determines all the sections for a course including
                   9330: sections with students and sections containing other roles.
1.419     raeburn  9331: Incoming parameters: 
                   9332: 
                   9333: 1. domain
                   9334: 2. course number 
                   9335: 3. reference to array containing roles for which sections should 
                   9336: be gathered (optional).
                   9337: 4. reference to array containing status types for which sections 
                   9338: should be gathered (optional).
                   9339: 
                   9340: If the third argument is undefined, sections are gathered for any role. 
                   9341: If the fourth argument is undefined, sections are gathered for any status.
                   9342: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9343:  
1.374     raeburn  9344: Returns section hash (keys are section IDs, values are
                   9345: number of users in each section), subject to the
1.419     raeburn  9346: optional roles filter, optional status filter 
1.233     raeburn  9347: 
                   9348: =cut
                   9349: 
                   9350: ###############################################
                   9351: sub get_sections {
1.419     raeburn  9352:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9353:     if (!defined($cdom) || !defined($cnum)) {
                   9354:         my $cid =  $env{'request.course.id'};
                   9355: 
                   9356: 	return if (!defined($cid));
                   9357: 
                   9358:         $cdom = $env{'course.'.$cid.'.domain'};
                   9359:         $cnum = $env{'course.'.$cid.'.num'};
                   9360:     }
                   9361: 
                   9362:     my %sectioncount;
1.419     raeburn  9363:     my $now = time;
1.240     albertel 9364: 
1.1075.2.33  raeburn  9365:     my $check_students = 1;
                   9366:     my $only_students = 0;
                   9367:     if (ref($possible_roles) eq 'ARRAY') {
                   9368:         if (grep(/^st$/,@{$possible_roles})) {
                   9369:             if (@{$possible_roles} == 1) {
                   9370:                 $only_students = 1;
                   9371:             }
                   9372:         } else {
                   9373:             $check_students = 0;
                   9374:         }
                   9375:     }
                   9376: 
                   9377:     if ($check_students) {
1.276     albertel 9378: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9379: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9380: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9381:         my $start_index = &Apache::loncoursedata::CL_START();
                   9382:         my $end_index = &Apache::loncoursedata::CL_END();
                   9383:         my $status;
1.366     albertel 9384: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9385: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9386: 				                     $data->[$status_index],
                   9387:                                                      $data->[$start_index],
                   9388:                                                      $data->[$end_index]);
                   9389:             if ($stu_status eq 'Active') {
                   9390:                 $status = 'active';
                   9391:             } elsif ($end < $now) {
                   9392:                 $status = 'previous';
                   9393:             } elsif ($start > $now) {
                   9394:                 $status = 'future';
                   9395:             } 
                   9396: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9397:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9398:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9399: 		    $sectioncount{$section}++;
                   9400:                 }
1.240     albertel 9401: 	    }
                   9402: 	}
                   9403:     }
1.1075.2.33  raeburn  9404:     if ($only_students) {
                   9405:         return %sectioncount;
                   9406:     }
1.240     albertel 9407:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9408:     foreach my $user (sort(keys(%courseroles))) {
                   9409: 	if ($user !~ /^(\w{2})/) { next; }
                   9410: 	my ($role) = ($user =~ /^(\w{2})/);
                   9411: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9412: 	my ($section,$status);
1.240     albertel 9413: 	if ($role eq 'cr' &&
                   9414: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9415: 	    $section=$1;
                   9416: 	}
                   9417: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9418: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9419:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9420:         if ($end == -1 && $start == -1) {
                   9421:             next; #deleted role
                   9422:         }
                   9423:         if (!defined($possible_status)) { 
                   9424:             $sectioncount{$section}++;
                   9425:         } else {
                   9426:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9427:                 $status = 'active';
                   9428:             } elsif ($end < $now) {
                   9429:                 $status = 'future';
                   9430:             } elsif ($start > $now) {
                   9431:                 $status = 'previous';
                   9432:             }
                   9433:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9434:                 $sectioncount{$section}++;
                   9435:             }
                   9436:         }
1.233     raeburn  9437:     }
1.366     albertel 9438:     return %sectioncount;
1.233     raeburn  9439: }
                   9440: 
1.274     raeburn  9441: ###############################################
1.294     raeburn  9442: 
                   9443: =pod
1.405     albertel 9444: 
                   9445: =item * &get_course_users()
                   9446: 
1.275     raeburn  9447: Retrieves usernames:domains for users in the specified course
                   9448: with specific role(s), and access status. 
                   9449: 
                   9450: Incoming parameters:
1.277     albertel 9451: 1. course domain
                   9452: 2. course number
                   9453: 3. access status: users must have - either active, 
1.275     raeburn  9454: previous, future, or all.
1.277     albertel 9455: 4. reference to array of permissible roles
1.288     raeburn  9456: 5. reference to array of section restrictions (optional)
                   9457: 6. reference to results object (hash of hashes).
                   9458: 7. reference to optional userdata hash
1.609     raeburn  9459: 8. reference to optional statushash
1.630     raeburn  9460: 9. flag if privileged users (except those set to unhide in
                   9461:    course settings) should be excluded    
1.609     raeburn  9462: Keys of top level results hash are roles.
1.275     raeburn  9463: Keys of inner hashes are username:domain, with 
                   9464: values set to access type.
1.288     raeburn  9465: Optional userdata hash returns an array with arguments in the 
                   9466: same order as loncoursedata::get_classlist() for student data.
                   9467: 
1.609     raeburn  9468: Optional statushash returns
                   9469: 
1.288     raeburn  9470: Entries for end, start, section and status are blank because
                   9471: of the possibility of multiple values for non-student roles.
                   9472: 
1.275     raeburn  9473: =cut
1.405     albertel 9474: 
1.275     raeburn  9475: ###############################################
1.405     albertel 9476: 
1.275     raeburn  9477: sub get_course_users {
1.630     raeburn  9478:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9479:     my %idx = ();
1.419     raeburn  9480:     my %seclists;
1.288     raeburn  9481: 
                   9482:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9483:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9484:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9485:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9486:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9487:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9488:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9489:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9490: 
1.290     albertel 9491:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9492:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9493:         my $now = time;
1.277     albertel 9494:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9495:             my $match = 0;
1.412     raeburn  9496:             my $secmatch = 0;
1.419     raeburn  9497:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9498:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9499:             if ($section eq '') {
                   9500:                 $section = 'none';
                   9501:             }
1.291     albertel 9502:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9503:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9504:                     $secmatch = 1;
                   9505:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9506:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9507:                         $secmatch = 1;
                   9508:                     }
                   9509:                 } else {  
1.419     raeburn  9510: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9511: 		        $secmatch = 1;
                   9512:                     }
1.290     albertel 9513: 		}
1.412     raeburn  9514:                 if (!$secmatch) {
                   9515:                     next;
                   9516:                 }
1.419     raeburn  9517:             }
1.275     raeburn  9518:             if (defined($$types{'active'})) {
1.288     raeburn  9519:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9520:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9521:                     $match = 1;
1.275     raeburn  9522:                 }
                   9523:             }
                   9524:             if (defined($$types{'previous'})) {
1.609     raeburn  9525:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9526:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9527:                     $match = 1;
1.275     raeburn  9528:                 }
                   9529:             }
                   9530:             if (defined($$types{'future'})) {
1.609     raeburn  9531:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9532:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9533:                     $match = 1;
1.275     raeburn  9534:                 }
                   9535:             }
1.609     raeburn  9536:             if ($match) {
                   9537:                 push(@{$seclists{$student}},$section);
                   9538:                 if (ref($userdata) eq 'HASH') {
                   9539:                     $$userdata{$student} = $$classlist{$student};
                   9540:                 }
                   9541:                 if (ref($statushash) eq 'HASH') {
                   9542:                     $statushash->{$student}{'st'}{$section} = $status;
                   9543:                 }
1.288     raeburn  9544:             }
1.275     raeburn  9545:         }
                   9546:     }
1.412     raeburn  9547:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9548:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9549:         my $now = time;
1.609     raeburn  9550:         my %displaystatus = ( previous => 'Expired',
                   9551:                               active   => 'Active',
                   9552:                               future   => 'Future',
                   9553:                             );
1.1075.2.36  raeburn  9554:         my (%nothide,@possdoms);
1.630     raeburn  9555:         if ($hidepriv) {
                   9556:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9557:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9558:                 if ($user !~ /:/) {
                   9559:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9560:                 } else {
                   9561:                     $nothide{$user} = 1;
                   9562:                 }
                   9563:             }
1.1075.2.36  raeburn  9564:             my @possdoms = ($cdom);
                   9565:             if ($coursehash{'checkforpriv'}) {
                   9566:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9567:             }
1.630     raeburn  9568:         }
1.439     raeburn  9569:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9570:             my $match = 0;
1.412     raeburn  9571:             my $secmatch = 0;
1.439     raeburn  9572:             my $status;
1.412     raeburn  9573:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9574:             $user =~ s/:$//;
1.439     raeburn  9575:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9576:             if ($end == -1 || $start == -1) {
                   9577:                 next;
                   9578:             }
                   9579:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9580:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9581:                 my ($uname,$udom) = split(/:/,$user);
                   9582:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9583:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9584:                         $secmatch = 1;
                   9585:                     } elsif ($usec eq '') {
1.420     albertel 9586:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9587:                             $secmatch = 1;
                   9588:                         }
                   9589:                     } else {
                   9590:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9591:                             $secmatch = 1;
                   9592:                         }
                   9593:                     }
                   9594:                     if (!$secmatch) {
                   9595:                         next;
                   9596:                     }
1.288     raeburn  9597:                 }
1.419     raeburn  9598:                 if ($usec eq '') {
                   9599:                     $usec = 'none';
                   9600:                 }
1.275     raeburn  9601:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9602:                     if ($hidepriv) {
1.1075.2.36  raeburn  9603:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9604:                             (!$nothide{$uname.':'.$udom})) {
                   9605:                             next;
                   9606:                         }
                   9607:                     }
1.503     raeburn  9608:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9609:                         $status = 'previous';
                   9610:                     } elsif ($start > $now) {
                   9611:                         $status = 'future';
                   9612:                     } else {
                   9613:                         $status = 'active';
                   9614:                     }
1.277     albertel 9615:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9616:                         if ($status eq $type) {
1.420     albertel 9617:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9618:                                 push(@{$$users{$role}{$user}},$type);
                   9619:                             }
1.288     raeburn  9620:                             $match = 1;
                   9621:                         }
                   9622:                     }
1.419     raeburn  9623:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9624:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9625: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9626:                         }
1.420     albertel 9627:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9628:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9629:                         }
1.609     raeburn  9630:                         if (ref($statushash) eq 'HASH') {
                   9631:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9632:                         }
1.275     raeburn  9633:                     }
                   9634:                 }
                   9635:             }
                   9636:         }
1.290     albertel 9637:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9638:             if ((defined($cdom)) && (defined($cnum))) {
                   9639:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9640:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9641:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9642:                     next if ($owner eq '');
                   9643:                     my ($ownername,$ownerdom);
                   9644:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9645:                         $ownername = $1;
                   9646:                         $ownerdom = $2;
                   9647:                     } else {
                   9648:                         $ownername = $owner;
                   9649:                         $ownerdom = $cdom;
                   9650:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9651:                     }
                   9652:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9653:                     if (defined($userdata) && 
1.609     raeburn  9654: 			!exists($$userdata{$owner})) {
                   9655: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9656:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9657:                             push(@{$seclists{$owner}},'none');
                   9658:                         }
                   9659:                         if (ref($statushash) eq 'HASH') {
                   9660:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9661:                         }
1.290     albertel 9662: 		    }
1.279     raeburn  9663:                 }
                   9664:             }
                   9665:         }
1.419     raeburn  9666:         foreach my $user (keys(%seclists)) {
                   9667:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9668:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9669:         }
1.275     raeburn  9670:     }
                   9671:     return;
                   9672: }
                   9673: 
1.288     raeburn  9674: sub get_user_info {
                   9675:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9676:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9677: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9678:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9679:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9680:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9681:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9682:     return;
                   9683: }
1.275     raeburn  9684: 
1.472     raeburn  9685: ###############################################
                   9686: 
                   9687: =pod
                   9688: 
                   9689: =item * &get_user_quota()
                   9690: 
1.1075.2.41  raeburn  9691: Retrieves quota assigned for storage of user files.
                   9692: Default is to report quota for portfolio files.
1.472     raeburn  9693: 
                   9694: Incoming parameters:
                   9695: 1. user's username
                   9696: 2. user's domain
1.1075.2.41  raeburn  9697: 3. quota name - portfolio, author, or course
                   9698:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  9699: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  9700:    course
1.472     raeburn  9701: 
                   9702: Returns:
1.1075.2.58  raeburn  9703: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9704: 2. (Optional) Type of setting: custom or default
                   9705:    (individually assigned or default for user's 
                   9706:    institutional status).
                   9707: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9708:    or student - types as defined in localenroll::inst_usertypes 
                   9709:    for user's domain, which determines default quota for user.
                   9710: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9711: 
                   9712: If a value has been stored in the user's environment, 
1.536     raeburn  9713: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  9714: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9715: 
                   9716: =cut
                   9717: 
                   9718: ###############################################
                   9719: 
                   9720: 
                   9721: sub get_user_quota {
1.1075.2.42  raeburn  9722:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9723:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9724:     if (!defined($udom)) {
                   9725:         $udom = $env{'user.domain'};
                   9726:     }
                   9727:     if (!defined($uname)) {
                   9728:         $uname = $env{'user.name'};
                   9729:     }
                   9730:     if (($udom eq '' || $uname eq '') ||
                   9731:         ($udom eq 'public') && ($uname eq 'public')) {
                   9732:         $quota = 0;
1.536     raeburn  9733:         $quotatype = 'default';
                   9734:         $defquota = 0; 
1.472     raeburn  9735:     } else {
1.536     raeburn  9736:         my $inststatus;
1.1075.2.41  raeburn  9737:         if ($quotaname eq 'course') {
                   9738:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9739:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9740:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9741:             } else {
                   9742:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9743:                 $quota = $cenv{'internal.uploadquota'};
                   9744:             }
1.536     raeburn  9745:         } else {
1.1075.2.41  raeburn  9746:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9747:                 if ($quotaname eq 'author') {
                   9748:                     $quota = $env{'environment.authorquota'};
                   9749:                 } else {
                   9750:                     $quota = $env{'environment.portfolioquota'};
                   9751:                 }
                   9752:                 $inststatus = $env{'environment.inststatus'};
                   9753:             } else {
                   9754:                 my %userenv = 
                   9755:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9756:                                          'authorquota','inststatus'],$udom,$uname);
                   9757:                 my ($tmp) = keys(%userenv);
                   9758:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9759:                     if ($quotaname eq 'author') {
                   9760:                         $quota = $userenv{'authorquota'};
                   9761:                     } else {
                   9762:                         $quota = $userenv{'portfolioquota'};
                   9763:                     }
                   9764:                     $inststatus = $userenv{'inststatus'};
                   9765:                 } else {
                   9766:                     undef(%userenv);
                   9767:                 }
                   9768:             }
                   9769:         }
                   9770:         if ($quota eq '' || wantarray) {
                   9771:             if ($quotaname eq 'course') {
                   9772:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  9773:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   9774:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  9775:                     $defquota = $domdefs{$crstype.'quota'};
                   9776:                 }
                   9777:                 if ($defquota eq '') {
                   9778:                     $defquota = 500;
                   9779:                 }
1.1075.2.41  raeburn  9780:             } else {
                   9781:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9782:             }
                   9783:             if ($quota eq '') {
                   9784:                 $quota = $defquota;
                   9785:                 $quotatype = 'default';
                   9786:             } else {
                   9787:                 $quotatype = 'custom';
                   9788:             }
1.472     raeburn  9789:         }
                   9790:     }
1.536     raeburn  9791:     if (wantarray) {
                   9792:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9793:     } else {
                   9794:         return $quota;
                   9795:     }
1.472     raeburn  9796: }
                   9797: 
                   9798: ###############################################
                   9799: 
                   9800: =pod
                   9801: 
                   9802: =item * &default_quota()
                   9803: 
1.536     raeburn  9804: Retrieves default quota assigned for storage of user portfolio files,
                   9805: given an (optional) user's institutional status.
1.472     raeburn  9806: 
                   9807: Incoming parameters:
1.1075.2.42  raeburn  9808: 
1.472     raeburn  9809: 1. domain
1.536     raeburn  9810: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9811:    status types (e.g., faculty, staff, student etc.)
                   9812:    which apply to the user for whom the default is being retrieved.
                   9813:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9814:    default quota will be returned.
                   9815: 3.  quota name - portfolio, author, or course
                   9816:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9817: 
                   9818: Returns:
1.1075.2.42  raeburn  9819: 
1.1075.2.58  raeburn  9820: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9821: 2. (Optional) institutional type which determined the value of the
                   9822:    default quota.
1.472     raeburn  9823: 
                   9824: If a value has been stored in the domain's configuration db,
                   9825: it will return that, otherwise it returns 20 (for backwards 
                   9826: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9827: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9828: 
1.536     raeburn  9829: If the user's status includes multiple types (e.g., staff and student),
                   9830: the largest default quota which applies to the user determines the
                   9831: default quota returned.
                   9832: 
1.472     raeburn  9833: =cut
                   9834: 
                   9835: ###############################################
                   9836: 
                   9837: 
                   9838: sub default_quota {
1.1075.2.41  raeburn  9839:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9840:     my ($defquota,$settingstatus);
                   9841:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9842:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9843:     my $key = 'defaultquota';
                   9844:     if ($quotaname eq 'author') {
                   9845:         $key = 'authorquota';
                   9846:     }
1.622     raeburn  9847:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9848:         if ($inststatus ne '') {
1.765     raeburn  9849:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9850:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9851:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9852:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9853:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9854:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9855:                             $settingstatus = $item;
1.1075.2.41  raeburn  9856:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9857:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9858:                             $settingstatus = $item;
                   9859:                         }
                   9860:                     }
1.1075.2.41  raeburn  9861:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9862:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9863:                         if ($defquota eq '') {
                   9864:                             $defquota = $quotahash{'quotas'}{$item};
                   9865:                             $settingstatus = $item;
                   9866:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9867:                             $defquota = $quotahash{'quotas'}{$item};
                   9868:                             $settingstatus = $item;
                   9869:                         }
1.536     raeburn  9870:                     }
                   9871:                 }
                   9872:             }
                   9873:         }
                   9874:         if ($defquota eq '') {
1.1075.2.41  raeburn  9875:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9876:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9877:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9878:                 $defquota = $quotahash{'quotas'}{'default'};
                   9879:             }
1.536     raeburn  9880:             $settingstatus = 'default';
1.1075.2.42  raeburn  9881:             if ($defquota eq '') {
                   9882:                 if ($quotaname eq 'author') {
                   9883:                     $defquota = 500;
                   9884:                 }
                   9885:             }
1.536     raeburn  9886:         }
                   9887:     } else {
                   9888:         $settingstatus = 'default';
1.1075.2.41  raeburn  9889:         if ($quotaname eq 'author') {
                   9890:             $defquota = 500;
                   9891:         } else {
                   9892:             $defquota = 20;
                   9893:         }
1.536     raeburn  9894:     }
                   9895:     if (wantarray) {
                   9896:         return ($defquota,$settingstatus);
1.472     raeburn  9897:     } else {
1.536     raeburn  9898:         return $defquota;
1.472     raeburn  9899:     }
                   9900: }
                   9901: 
1.1075.2.41  raeburn  9902: ###############################################
                   9903: 
                   9904: =pod
                   9905: 
1.1075.2.42  raeburn  9906: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9907: 
                   9908: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9909: of existing file within authoring space will cause quota for the authoring
                   9910: space to be exceeded.
                   9911: 
                   9912: Same, if upload of a file directly to a course/community via Course Editor
                   9913: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9914: 
1.1075.2.61  raeburn  9915: Inputs: 7 
1.1075.2.42  raeburn  9916: 1. username or coursenum
1.1075.2.41  raeburn  9917: 2. domain
1.1075.2.42  raeburn  9918: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9919: 4. filename of file for which action is being requested
                   9920: 5. filesize (kB) of file
                   9921: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9922: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9923: 
                   9924: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9925:          otherwise return null.
                   9926: 
1.1075.2.42  raeburn  9927: =back
                   9928: 
1.1075.2.41  raeburn  9929: =cut
                   9930: 
1.1075.2.42  raeburn  9931: sub excess_filesize_warning {
1.1075.2.59  raeburn  9932:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9933:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9934:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9935:     if ($context eq 'author') {
                   9936:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9937:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9938:     } else {
                   9939:         foreach my $subdir ('docs','supplemental') {
                   9940:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9941:         }
                   9942:     }
1.1075.2.41  raeburn  9943:     $disk_quota = int($disk_quota * 1000);
                   9944:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9945:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9946:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9947:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9948:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9949:                             $disk_quota,$current_disk_usage).
                   9950:                '</p>';
                   9951:     }
                   9952:     return;
                   9953: }
                   9954: 
                   9955: ###############################################
                   9956: 
                   9957: 
1.384     raeburn  9958: sub get_secgrprole_info {
                   9959:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9960:     my %sections_count = &get_sections($cdom,$cnum);
                   9961:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9962:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9963:     my @groups = sort(keys(%curr_groups));
                   9964:     my $allroles = [];
                   9965:     my $rolehash;
                   9966:     my $accesshash = {
                   9967:                      active => 'Currently has access',
                   9968:                      future => 'Will have future access',
                   9969:                      previous => 'Previously had access',
                   9970:                   };
                   9971:     if ($needroles) {
                   9972:         $rolehash = {'all' => 'all'};
1.385     albertel 9973:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9974: 	if (&Apache::lonnet::error(%user_roles)) {
                   9975: 	    undef(%user_roles);
                   9976: 	}
                   9977:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9978:             my ($role)=split(/\:/,$item,2);
                   9979:             if ($role eq 'cr') { next; }
                   9980:             if ($role =~ /^cr/) {
                   9981:                 $$rolehash{$role} = (split('/',$role))[3];
                   9982:             } else {
                   9983:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9984:             }
                   9985:         }
                   9986:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9987:             push(@{$allroles},$key);
                   9988:         }
                   9989:         push (@{$allroles},'st');
                   9990:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9991:     }
                   9992:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9993: }
                   9994: 
1.555     raeburn  9995: sub user_picker {
1.1075.2.127  raeburn  9996:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  9997:     my $currdom = $dom;
1.1075.2.114  raeburn  9998:     my @alldoms = &Apache::lonnet::all_domains();
                   9999:     if (@alldoms == 1) {
                   10000:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10001:                                                ['directorysrch'],$alldoms[0]);
                   10002:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10003:         my $showdom = $domdesc;
                   10004:         if ($showdom eq '') {
                   10005:             $showdom = $dom;
                   10006:         }
                   10007:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10008:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10009:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10010:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10011:             }
                   10012:         }
                   10013:     }
1.555     raeburn  10014:     my %curr_selected = (
                   10015:                         srchin => 'dom',
1.580     raeburn  10016:                         srchby => 'lastname',
1.555     raeburn  10017:                       );
                   10018:     my $srchterm;
1.625     raeburn  10019:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10020:         if ($srch->{'srchby'} ne '') {
                   10021:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10022:         }
                   10023:         if ($srch->{'srchin'} ne '') {
                   10024:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10025:         }
                   10026:         if ($srch->{'srchtype'} ne '') {
                   10027:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10028:         }
                   10029:         if ($srch->{'srchdomain'} ne '') {
                   10030:             $currdom = $srch->{'srchdomain'};
                   10031:         }
                   10032:         $srchterm = $srch->{'srchterm'};
                   10033:     }
1.1075.2.98  raeburn  10034:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10035:                     'usr'       => 'Search criteria',
1.563     raeburn  10036:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10037:                     'uname'     => 'username',
                   10038:                     'lastname'  => 'last name',
1.555     raeburn  10039:                     'lastfirst' => 'last name, first name',
1.558     albertel 10040:                     'crs'       => 'in this course',
1.576     raeburn  10041:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10042:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10043:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10044:                     'exact'     => 'is',
                   10045:                     'contains'  => 'contains',
1.569     raeburn  10046:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  10047:                                        );
                   10048:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10049:                     'youm'      => "You must include some text to search for.",
                   10050:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10051:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10052:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10053:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10054:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10055:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10056:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10057:                                        );
1.1075.2.98  raeburn  10058:     &html_escape(\%html_lt);
                   10059:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  10060:     my $domform;
1.1075.2.126  raeburn  10061:     my $allow_blank = 1;
1.1075.2.115  raeburn  10062:     if ($fixeddom) {
1.1075.2.126  raeburn  10063:         $allow_blank = 0;
                   10064:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  10065:     } else {
1.1075.2.126  raeburn  10066:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  10067:     }
1.563     raeburn  10068:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10069: 
                   10070:     my @srchins = ('crs','dom','alc','instd');
                   10071: 
                   10072:     foreach my $option (@srchins) {
                   10073:         # FIXME 'alc' option unavailable until 
                   10074:         #       loncreateuser::print_user_query_page()
                   10075:         #       has been completed.
                   10076:         next if ($option eq 'alc');
1.880     raeburn  10077:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10078:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  10079:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10080:         if ($curr_selected{'srchin'} eq $option) {
                   10081:             $srchinsel .= ' 
1.1075.2.98  raeburn  10082:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10083:         } else {
                   10084:             $srchinsel .= '
1.1075.2.98  raeburn  10085:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10086:         }
1.555     raeburn  10087:     }
1.563     raeburn  10088:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10089: 
                   10090:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10091:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10092:         if ($curr_selected{'srchby'} eq $option) {
                   10093:             $srchbysel .= '
1.1075.2.98  raeburn  10094:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10095:         } else {
                   10096:             $srchbysel .= '
1.1075.2.98  raeburn  10097:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10098:          }
                   10099:     }
                   10100:     $srchbysel .= "\n  </select>\n";
                   10101: 
                   10102:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10103:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10104:         if ($curr_selected{'srchtype'} eq $option) {
                   10105:             $srchtypesel .= '
1.1075.2.98  raeburn  10106:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10107:         } else {
                   10108:             $srchtypesel .= '
1.1075.2.98  raeburn  10109:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10110:         }
                   10111:     }
                   10112:     $srchtypesel .= "\n  </select>\n";
                   10113: 
1.558     albertel 10114:     my ($newuserscript,$new_user_create);
1.994     raeburn  10115:     my $context_dom = $env{'request.role.domain'};
                   10116:     if ($context eq 'requestcrs') {
                   10117:         if ($env{'form.coursedom'} ne '') { 
                   10118:             $context_dom = $env{'form.coursedom'};
                   10119:         }
                   10120:     }
1.556     raeburn  10121:     if ($forcenewuser) {
1.576     raeburn  10122:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10123:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10124:                 if ($cancreate) {
                   10125:                     $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>';
                   10126:                 } else {
1.799     bisitz   10127:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10128:                     my %usertypetext = (
                   10129:                         official   => 'institutional',
                   10130:                         unofficial => 'non-institutional',
                   10131:                     );
1.799     bisitz   10132:                     $new_user_create = '<p class="LC_warning">'
                   10133:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10134:                                       .' '
                   10135:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10136:                                           ,'<a href="'.$helplink.'">','</a>')
                   10137:                                       .'</p><br />';
1.627     raeburn  10138:                 }
1.576     raeburn  10139:             }
                   10140:         }
                   10141: 
1.556     raeburn  10142:         $newuserscript = <<"ENDSCRIPT";
                   10143: 
1.570     raeburn  10144: function setSearch(createnew,callingForm) {
1.556     raeburn  10145:     if (createnew == 1) {
1.570     raeburn  10146:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10147:             if (callingForm.srchby.options[i].value == 'uname') {
                   10148:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10149:             }
                   10150:         }
1.570     raeburn  10151:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10152:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10153: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10154:             }
                   10155:         }
1.570     raeburn  10156:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10157:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10158:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10159:             }
                   10160:         }
1.570     raeburn  10161:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10162:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10163:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10164:             }
                   10165:         }
                   10166:     }
                   10167: }
                   10168: ENDSCRIPT
1.558     albertel 10169: 
1.556     raeburn  10170:     }
                   10171: 
1.555     raeburn  10172:     my $output = <<"END_BLOCK";
1.556     raeburn  10173: <script type="text/javascript">
1.824     bisitz   10174: // <![CDATA[
1.570     raeburn  10175: function validateEntry(callingForm) {
1.558     albertel 10176: 
1.556     raeburn  10177:     var checkok = 1;
1.558     albertel 10178:     var srchin;
1.570     raeburn  10179:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10180: 	if ( callingForm.srchin[i].checked ) {
                   10181: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10182: 	}
                   10183:     }
                   10184: 
1.570     raeburn  10185:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10186:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10187:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10188:     var srchterm =  callingForm.srchterm.value;
                   10189:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10190:     var msg = "";
                   10191: 
                   10192:     if (srchterm == "") {
                   10193:         checkok = 0;
1.1075.2.98  raeburn  10194:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10195:     }
                   10196: 
1.569     raeburn  10197:     if (srchtype== 'begins') {
                   10198:         if (srchterm.length < 2) {
                   10199:             checkok = 0;
1.1075.2.98  raeburn  10200:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10201:         }
                   10202:     }
                   10203: 
1.556     raeburn  10204:     if (srchtype== 'contains') {
                   10205:         if (srchterm.length < 3) {
                   10206:             checkok = 0;
1.1075.2.98  raeburn  10207:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10208:         }
                   10209:     }
                   10210:     if (srchin == 'instd') {
                   10211:         if (srchdomain == '') {
                   10212:             checkok = 0;
1.1075.2.98  raeburn  10213:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10214:         }
                   10215:     }
                   10216:     if (srchin == 'dom') {
                   10217:         if (srchdomain == '') {
                   10218:             checkok = 0;
1.1075.2.98  raeburn  10219:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10220:         }
                   10221:     }
                   10222:     if (srchby == 'lastfirst') {
                   10223:         if (srchterm.indexOf(",") == -1) {
                   10224:             checkok = 0;
1.1075.2.98  raeburn  10225:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10226:         }
                   10227:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10228:             checkok = 0;
1.1075.2.98  raeburn  10229:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10230:         }
                   10231:     }
                   10232:     if (checkok == 0) {
1.1075.2.98  raeburn  10233:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10234:         return;
                   10235:     }
                   10236:     if (checkok == 1) {
1.570     raeburn  10237:         callingForm.submit();
1.556     raeburn  10238:     }
                   10239: }
                   10240: 
                   10241: $newuserscript
                   10242: 
1.824     bisitz   10243: // ]]>
1.556     raeburn  10244: </script>
1.558     albertel 10245: 
                   10246: $new_user_create
                   10247: 
1.555     raeburn  10248: END_BLOCK
1.558     albertel 10249: 
1.876     raeburn  10250:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  10251:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10252:                $domform.
                   10253:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  10254:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10255:                $srchbysel.
                   10256:                $srchtypesel. 
                   10257:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10258:                $srchinsel.
                   10259:                &Apache::lonhtmlcommon::row_closure(1). 
                   10260:                &Apache::lonhtmlcommon::end_pick_box().
                   10261:                '<br />';
1.1075.2.114  raeburn  10262:     return ($output,1);
1.555     raeburn  10263: }
                   10264: 
1.612     raeburn  10265: sub user_rule_check {
1.615     raeburn  10266:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  10267:     my ($response,%inst_response);
1.612     raeburn  10268:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  10269:         if (keys(%{$usershash}) > 1) {
                   10270:             my (%by_username,%by_id,%userdoms);
                   10271:             my $checkid;
1.612     raeburn  10272:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  10273:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10274:                     $checkid = 1;
                   10275:                 }
                   10276:             }
                   10277:             foreach my $user (keys(%{$usershash})) {
                   10278:                 my ($uname,$udom) = split(/:/,$user);
                   10279:                 if ($checkid) {
                   10280:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10281:                         if ($usershash->{$user}->{'id'} ne '') {
                   10282:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   10283:                             $userdoms{$udom} = 1;
                   10284:                             if (ref($inst_results) eq 'HASH') {
                   10285:                                 $inst_results->{$uname.':'.$udom} = {};
                   10286:                             }
                   10287:                         }
                   10288:                     }
                   10289:                 } else {
                   10290:                     $by_username{$udom}{$uname} = 1;
                   10291:                     $userdoms{$udom} = 1;
                   10292:                     if (ref($inst_results) eq 'HASH') {
                   10293:                         $inst_results->{$uname.':'.$udom} = {};
                   10294:                     }
                   10295:                 }
                   10296:             }
                   10297:             foreach my $udom (keys(%userdoms)) {
                   10298:                 if (!$got_rules->{$udom}) {
                   10299:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10300:                                                              ['usercreation'],$udom);
                   10301:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10302:                         foreach my $item ('username','id') {
                   10303:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10304:                                 $$curr_rules{$udom}{$item} =
                   10305:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   10306:                             }
                   10307:                         }
                   10308:                     }
                   10309:                     $got_rules->{$udom} = 1;
                   10310:                 }
                   10311:             }
                   10312:             if ($checkid) {
                   10313:                 foreach my $udom (keys(%by_id)) {
                   10314:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10315:                     if ($outcome eq 'ok') {
                   10316:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10317:                             my $uname = $by_id{$udom}{$id};
                   10318:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10319:                         }
                   10320:                         if (ref($results) eq 'HASH') {
                   10321:                             foreach my $uname (keys(%{$results})) {
                   10322:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10323:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10324:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10325:                                 }
                   10326:                             }
                   10327:                         }
                   10328:                     }
1.612     raeburn  10329:                 }
1.615     raeburn  10330:             } else {
1.1075.2.99  raeburn  10331:                 foreach my $udom (keys(%by_username)) {
                   10332:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10333:                     if ($outcome eq 'ok') {
                   10334:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10335:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10336:                         }
                   10337:                         if (ref($results) eq 'HASH') {
                   10338:                             foreach my $uname (keys(%{$results})) {
                   10339:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10340:                             }
                   10341:                         }
                   10342:                     }
                   10343:                 }
1.612     raeburn  10344:             }
1.1075.2.99  raeburn  10345:         } elsif (keys(%{$usershash}) == 1) {
                   10346:             my $user = (keys(%{$usershash}))[0];
                   10347:             my ($uname,$udom) = split(/:/,$user);
                   10348:             if (($udom ne '') && ($uname ne '')) {
                   10349:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10350:                     if (ref($checks) eq 'HASH') {
                   10351:                         if (defined($checks->{'username'})) {
                   10352:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   10353:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10354:                         } elsif (defined($checks->{'id'})) {
                   10355:                             if ($usershash->{$user}->{'id'} ne '') {
                   10356:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10357:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10358:                                                                   $usershash->{$user}->{'id'});
                   10359:                             } else {
                   10360:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10361:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10362:                             }
                   10363:                         }
                   10364:                     } else {
                   10365:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10366:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10367:                        return;
                   10368:                     }
                   10369:                     if (!$got_rules->{$udom}) {
                   10370:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10371:                                                                  ['usercreation'],$udom);
                   10372:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10373:                             foreach my $item ('username','id') {
                   10374:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10375:                                    $$curr_rules{$udom}{$item} =
                   10376:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10377:                                 }
                   10378:                             }
1.585     raeburn  10379:                         }
1.1075.2.99  raeburn  10380:                         $got_rules->{$udom} = 1;
1.585     raeburn  10381:                     }
                   10382:                 }
1.1075.2.99  raeburn  10383:             } else {
                   10384:                 return;
                   10385:             }
                   10386:         } else {
                   10387:             return;
                   10388:         }
                   10389:         foreach my $user (keys(%{$usershash})) {
                   10390:             my ($uname,$udom) = split(/:/,$user);
                   10391:             next if (($udom eq '') || ($uname eq ''));
                   10392:             my $id;
                   10393:             if (ref($inst_results) eq 'HASH') {
                   10394:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10395:                     $id = $inst_results->{$user}->{'id'};
                   10396:                 }
                   10397:             }
                   10398:             if ($id eq '') {
                   10399:                 if (ref($usershash->{$user})) {
                   10400:                     $id = $usershash->{$user}->{'id'};
                   10401:                 }
1.585     raeburn  10402:             }
1.612     raeburn  10403:             foreach my $item (keys(%{$checks})) {
                   10404:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10405:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10406:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  10407:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10408:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10409:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10410:                                 if ($rule_check{$rule}) {
                   10411:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  10412:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10413:                                         if (ref($inst_results) eq 'HASH') {
                   10414:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10415:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10416:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  10417:                                                 } elsif ($item eq 'id') {
                   10418:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10419:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10420:                                                     }
1.615     raeburn  10421:                                                 }
1.612     raeburn  10422:                                             }
                   10423:                                         }
1.615     raeburn  10424:                                     }
                   10425:                                     last;
1.585     raeburn  10426:                                 }
                   10427:                             }
                   10428:                         }
                   10429:                     }
                   10430:                 }
                   10431:             }
                   10432:         }
                   10433:     }
1.612     raeburn  10434:     return;
                   10435: }
                   10436: 
                   10437: sub user_rule_formats {
                   10438:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10439:     my %text = ( 
                   10440:                  'username' => 'Usernames',
                   10441:                  'id'       => 'IDs',
                   10442:                );
                   10443:     my $output;
                   10444:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10445:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10446:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  10447:             $output = '<br />'.
                   10448:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10449:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10450:                       ' <ul>';
1.612     raeburn  10451:             foreach my $rule (@{$ruleorder}) {
                   10452:                 if (ref($curr_rules) eq 'ARRAY') {
                   10453:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10454:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10455:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10456:                                         $rules->{$rule}{'desc'}.'</li>';
                   10457:                         }
                   10458:                     }
                   10459:                 }
                   10460:             }
                   10461:             $output .= '</ul>';
                   10462:         }
                   10463:     }
                   10464:     return $output;
                   10465: }
                   10466: 
                   10467: sub instrule_disallow_msg {
1.615     raeburn  10468:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10469:     my $response;
                   10470:     my %text = (
                   10471:                   item   => 'username',
                   10472:                   items  => 'usernames',
                   10473:                   match  => 'matches',
                   10474:                   do     => 'does',
                   10475:                   action => 'a username',
                   10476:                   one    => 'one',
                   10477:                );
                   10478:     if ($count > 1) {
                   10479:         $text{'item'} = 'usernames';
                   10480:         $text{'match'} ='match';
                   10481:         $text{'do'} = 'do';
                   10482:         $text{'action'} = 'usernames',
                   10483:         $text{'one'} = 'ones';
                   10484:     }
                   10485:     if ($checkitem eq 'id') {
                   10486:         $text{'items'} = 'IDs';
                   10487:         $text{'item'} = 'ID';
                   10488:         $text{'action'} = 'an ID';
1.615     raeburn  10489:         if ($count > 1) {
                   10490:             $text{'item'} = 'IDs';
                   10491:             $text{'action'} = 'IDs';
                   10492:         }
1.612     raeburn  10493:     }
1.674     bisitz   10494:     $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  10495:     if ($mode eq 'upload') {
                   10496:         if ($checkitem eq 'username') {
                   10497:             $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'}.");
                   10498:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10499:             $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  10500:         }
1.669     raeburn  10501:     } elsif ($mode eq 'selfcreate') {
                   10502:         if ($checkitem eq 'id') {
                   10503:             $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.");
                   10504:         }
1.615     raeburn  10505:     } else {
                   10506:         if ($checkitem eq 'username') {
                   10507:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10508:         } elsif ($checkitem eq 'id') {
                   10509:             $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.");
                   10510:         }
1.612     raeburn  10511:     }
                   10512:     return $response;
1.585     raeburn  10513: }
                   10514: 
1.624     raeburn  10515: sub personal_data_fieldtitles {
                   10516:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10517:                         id => 'Student/Employee ID',
                   10518:                         permanentemail => 'E-mail address',
                   10519:                         lastname => 'Last Name',
                   10520:                         firstname => 'First Name',
                   10521:                         middlename => 'Middle Name',
                   10522:                         generation => 'Generation',
                   10523:                         gen => 'Generation',
1.765     raeburn  10524:                         inststatus => 'Affiliation',
1.624     raeburn  10525:                    );
                   10526:     return %fieldtitles;
                   10527: }
                   10528: 
1.642     raeburn  10529: sub sorted_inst_types {
                   10530:     my ($dom) = @_;
1.1075.2.70  raeburn  10531:     my ($usertypes,$order);
                   10532:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10533:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10534:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10535:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10536:     } else {
                   10537:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10538:     }
1.642     raeburn  10539:     my $othertitle = &mt('All users');
                   10540:     if ($env{'request.course.id'}) {
1.668     raeburn  10541:         $othertitle  = &mt('Any users');
1.642     raeburn  10542:     }
                   10543:     my @types;
                   10544:     if (ref($order) eq 'ARRAY') {
                   10545:         @types = @{$order};
                   10546:     }
                   10547:     if (@types == 0) {
                   10548:         if (ref($usertypes) eq 'HASH') {
                   10549:             @types = sort(keys(%{$usertypes}));
                   10550:         }
                   10551:     }
                   10552:     if (keys(%{$usertypes}) > 0) {
                   10553:         $othertitle = &mt('Other users');
                   10554:     }
                   10555:     return ($othertitle,$usertypes,\@types);
                   10556: }
                   10557: 
1.645     raeburn  10558: sub get_institutional_codes {
1.1075.2.157  raeburn  10559:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  10560: # Get complete list of course sections to update
                   10561:     my @currsections = ();
                   10562:     my @currxlists = ();
1.1075.2.157  raeburn  10563:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  10564:     my $coursecode = $$settings{'internal.coursecode'};
1.1075.2.157  raeburn  10565:     my $crskey = $crs.':'.$coursecode;
                   10566:     @{$unclutteredsec{$crskey}} = ();
                   10567:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  10568: 
                   10569:     if ($$settings{'internal.sectionnums'} ne '') {
                   10570:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10571:     }
                   10572: 
                   10573:     if ($$settings{'internal.crosslistings'} ne '') {
                   10574:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10575:     }
                   10576: 
                   10577:     if (@currxlists > 0) {
1.1075.2.157  raeburn  10578:         foreach my $xl (@currxlists) {
                   10579:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  10580:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  10581:                     push(@{$allcourses},$1);
1.645     raeburn  10582:                     $$LC_code{$1} = $2;
                   10583:                 }
                   10584:             }
                   10585:         }
                   10586:     }
1.1075.2.157  raeburn  10587: 
1.645     raeburn  10588:     if (@currsections > 0) {
1.1075.2.157  raeburn  10589:         foreach my $sec (@currsections) {
                   10590:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   10591:                 my $instsec = $1;
1.645     raeburn  10592:                 my $lc_sec = $2;
1.1075.2.157  raeburn  10593:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   10594:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   10595:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   10596:                 }
                   10597:             }
                   10598:         }
                   10599:     }
                   10600: 
                   10601:     if (@{$unclutteredsec{$crskey}} > 0) {
                   10602:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   10603:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   10604:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   10605:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   10606:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1075.2.119  raeburn  10607:                     push(@{$allcourses},$sec);
1.1075.2.157  raeburn  10608:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  10609:                 }
                   10610:             }
                   10611:         }
                   10612:     }
                   10613:     return;
                   10614: }
                   10615: 
1.971     raeburn  10616: sub get_standard_codeitems {
                   10617:     return ('Year','Semester','Department','Number','Section');
                   10618: }
                   10619: 
1.112     bowersj2 10620: =pod
                   10621: 
1.780     raeburn  10622: =head1 Slot Helpers
                   10623: 
                   10624: =over 4
                   10625: 
                   10626: =item * sorted_slots()
                   10627: 
1.1040    raeburn  10628: Sorts an array of slot names in order of an optional sort key,
                   10629: default sort is by slot start time (earliest first). 
1.780     raeburn  10630: 
                   10631: Inputs:
                   10632: 
                   10633: =over 4
                   10634: 
                   10635: slotsarr  - Reference to array of unsorted slot names.
                   10636: 
                   10637: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10638: 
1.1040    raeburn  10639: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10640: 
1.549     albertel 10641: =back
                   10642: 
1.780     raeburn  10643: Returns:
                   10644: 
                   10645: =over 4
                   10646: 
1.1040    raeburn  10647: sorted   - An array of slot names sorted by a specified sort key 
                   10648:            (default sort key is start time of the slot).
1.780     raeburn  10649: 
                   10650: =back
                   10651: 
                   10652: =cut
                   10653: 
                   10654: 
                   10655: sub sorted_slots {
1.1040    raeburn  10656:     my ($slotsarr,$slots,$sortkey) = @_;
                   10657:     if ($sortkey eq '') {
                   10658:         $sortkey = 'starttime';
                   10659:     }
1.780     raeburn  10660:     my @sorted;
                   10661:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10662:         @sorted =
                   10663:             sort {
                   10664:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10665:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10666:                      }
                   10667:                      if (ref($slots->{$a})) { return -1;}
                   10668:                      if (ref($slots->{$b})) { return 1;}
                   10669:                      return 0;
                   10670:                  } @{$slotsarr};
                   10671:     }
                   10672:     return @sorted;
                   10673: }
                   10674: 
1.1040    raeburn  10675: =pod
                   10676: 
                   10677: =item * get_future_slots()
                   10678: 
                   10679: Inputs:
                   10680: 
                   10681: =over 4
                   10682: 
                   10683: cnum - course number
                   10684: 
                   10685: cdom - course domain
                   10686: 
                   10687: now - current UNIX time
                   10688: 
                   10689: symb - optional symb
                   10690: 
                   10691: =back
                   10692: 
                   10693: Returns:
                   10694: 
                   10695: =over 4
                   10696: 
                   10697: sorted_reservable - ref to array of student_schedulable slots currently 
                   10698:                     reservable, ordered by end date of reservation period.
                   10699: 
                   10700: reservable_now - ref to hash of student_schedulable slots currently
                   10701:                  reservable.
                   10702: 
                   10703:     Keys in inner hash are:
                   10704:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  10705:     (b) endreserve: end date of reservation period.
                   10706:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10707:         selected.
1.1040    raeburn  10708: 
                   10709: sorted_future - ref to array of student_schedulable slots reservable in
                   10710:                 the future, ordered by start date of reservation period.
                   10711: 
                   10712: future_reservable - ref to hash of student_schedulable slots reservable
                   10713:                     in the future.
                   10714: 
                   10715:     Keys in inner hash are:
                   10716:     (a) symb: either blank or symb to which slot use is restricted.
                   10717:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  10718:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10719:         selected.
1.1040    raeburn  10720: 
                   10721: =back
                   10722: 
                   10723: =cut
                   10724: 
                   10725: sub get_future_slots {
                   10726:     my ($cnum,$cdom,$now,$symb) = @_;
                   10727:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10728:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10729:     foreach my $slot (keys(%slots)) {
                   10730:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10731:         if ($symb) {
                   10732:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10733:                      ($slots{$slot}->{'symb'} ne $symb));
                   10734:         }
                   10735:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10736:             ($slots{$slot}->{'endtime'} > $now)) {
                   10737:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10738:                 my $userallowed = 0;
                   10739:                 if ($slots{$slot}->{'allowedsections'}) {
                   10740:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10741:                     if (!defined($env{'request.role.sec'})
                   10742:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10743:                         $userallowed=1;
                   10744:                     } else {
                   10745:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10746:                             $userallowed=1;
                   10747:                         }
                   10748:                     }
                   10749:                     unless ($userallowed) {
                   10750:                         if (defined($env{'request.course.groups'})) {
                   10751:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10752:                             foreach my $group (@groups) {
                   10753:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10754:                                     $userallowed=1;
                   10755:                                     last;
                   10756:                                 }
                   10757:                             }
                   10758:                         }
                   10759:                     }
                   10760:                 }
                   10761:                 if ($slots{$slot}->{'allowedusers'}) {
                   10762:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10763:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10764:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10765:                         $userallowed = 1;
                   10766:                     }
                   10767:                 }
                   10768:                 next unless($userallowed);
                   10769:             }
                   10770:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10771:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10772:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  10773:             my $uniqueperiod;
                   10774:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10775:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10776:             }
1.1040    raeburn  10777:             if (($startreserve < $now) &&
                   10778:                 (!$endreserve || $endreserve > $now)) {
                   10779:                 my $lastres = $endreserve;
                   10780:                 if (!$lastres) {
                   10781:                     $lastres = $slots{$slot}->{'starttime'};
                   10782:                 }
                   10783:                 $reservable_now{$slot} = {
                   10784:                                            symb       => $symb,
1.1075.2.104  raeburn  10785:                                            endreserve => $lastres,
                   10786:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  10787:                                          };
                   10788:             } elsif (($startreserve > $now) &&
                   10789:                      (!$endreserve || $endreserve > $startreserve)) {
                   10790:                 $future_reservable{$slot} = {
                   10791:                                               symb         => $symb,
1.1075.2.104  raeburn  10792:                                               startreserve => $startreserve,
                   10793:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10794:                                             };
                   10795:             }
                   10796:         }
                   10797:     }
                   10798:     my @unsorted_reservable = keys(%reservable_now);
                   10799:     if (@unsorted_reservable > 0) {
                   10800:         @sorted_reservable = 
                   10801:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10802:     }
                   10803:     my @unsorted_future = keys(%future_reservable);
                   10804:     if (@unsorted_future > 0) {
                   10805:         @sorted_future =
                   10806:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10807:     }
                   10808:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10809: }
1.780     raeburn  10810: 
                   10811: =pod
                   10812: 
1.1057    foxr     10813: =back
                   10814: 
1.549     albertel 10815: =head1 HTTP Helpers
                   10816: 
                   10817: =over 4
                   10818: 
1.648     raeburn  10819: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10820: 
1.258     albertel 10821: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10822: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10823: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10824: 
                   10825: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10826: $possible_names is an ref to an array of form element names.  As an example:
                   10827: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10828: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10829: 
                   10830: =cut
1.1       albertel 10831: 
1.6       albertel 10832: sub get_unprocessed_cgi {
1.25      albertel 10833:   my ($query,$possible_names)= @_;
1.26      matthew  10834:   # $Apache::lonxml::debug=1;
1.356     albertel 10835:   foreach my $pair (split(/&/,$query)) {
                   10836:     my ($name, $value) = split(/=/,$pair);
1.369     www      10837:     $name = &unescape($name);
1.25      albertel 10838:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10839:       $value =~ tr/+/ /;
                   10840:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10841:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10842:     }
1.16      harris41 10843:   }
1.6       albertel 10844: }
                   10845: 
1.112     bowersj2 10846: =pod
                   10847: 
1.648     raeburn  10848: =item * &cacheheader() 
1.112     bowersj2 10849: 
                   10850: returns cache-controlling header code
                   10851: 
                   10852: =cut
                   10853: 
1.7       albertel 10854: sub cacheheader {
1.258     albertel 10855:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10856:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10857:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10858:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10859:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10860:     return $output;
1.7       albertel 10861: }
                   10862: 
1.112     bowersj2 10863: =pod
                   10864: 
1.648     raeburn  10865: =item * &no_cache($r) 
1.112     bowersj2 10866: 
                   10867: specifies header code to not have cache
                   10868: 
                   10869: =cut
                   10870: 
1.9       albertel 10871: sub no_cache {
1.216     albertel 10872:     my ($r) = @_;
                   10873:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10874: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10875:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10876:     $r->no_cache(1);
                   10877:     $r->header_out("Expires" => $date);
                   10878:     $r->header_out("Pragma" => "no-cache");
1.123     www      10879: }
                   10880: 
                   10881: sub content_type {
1.181     albertel 10882:     my ($r,$type,$charset) = @_;
1.299     foxr     10883:     if ($r) {
                   10884: 	#  Note that printout.pl calls this with undef for $r.
                   10885: 	&no_cache($r);
                   10886:     }
1.258     albertel 10887:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10888:     unless ($charset) {
                   10889: 	$charset=&Apache::lonlocal::current_encoding;
                   10890:     }
                   10891:     if ($charset) { $type.='; charset='.$charset; }
                   10892:     if ($r) {
                   10893: 	$r->content_type($type);
                   10894:     } else {
                   10895: 	print("Content-type: $type\n\n");
                   10896:     }
1.9       albertel 10897: }
1.25      albertel 10898: 
1.112     bowersj2 10899: =pod
                   10900: 
1.648     raeburn  10901: =item * &add_to_env($name,$value) 
1.112     bowersj2 10902: 
1.258     albertel 10903: adds $name to the %env hash with value
1.112     bowersj2 10904: $value, if $name already exists, the entry is converted to an array
                   10905: reference and $value is added to the array.
                   10906: 
                   10907: =cut
                   10908: 
1.25      albertel 10909: sub add_to_env {
                   10910:   my ($name,$value)=@_;
1.258     albertel 10911:   if (defined($env{$name})) {
                   10912:     if (ref($env{$name})) {
1.25      albertel 10913:       #already have multiple values
1.258     albertel 10914:       push(@{ $env{$name} },$value);
1.25      albertel 10915:     } else {
                   10916:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10917:       my $first=$env{$name};
                   10918:       undef($env{$name});
                   10919:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10920:     }
                   10921:   } else {
1.258     albertel 10922:     $env{$name}=$value;
1.25      albertel 10923:   }
1.31      albertel 10924: }
1.149     albertel 10925: 
                   10926: =pod
                   10927: 
1.648     raeburn  10928: =item * &get_env_multiple($name) 
1.149     albertel 10929: 
1.258     albertel 10930: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10931: values may be defined and end up as an array ref.
                   10932: 
                   10933: returns an array of values
                   10934: 
                   10935: =cut
                   10936: 
                   10937: sub get_env_multiple {
                   10938:     my ($name) = @_;
                   10939:     my @values;
1.258     albertel 10940:     if (defined($env{$name})) {
1.149     albertel 10941:         # exists is it an array
1.258     albertel 10942:         if (ref($env{$name})) {
                   10943:             @values=@{ $env{$name} };
1.149     albertel 10944:         } else {
1.258     albertel 10945:             $values[0]=$env{$name};
1.149     albertel 10946:         }
                   10947:     }
                   10948:     return(@values);
                   10949: }
                   10950: 
1.660     raeburn  10951: sub ask_for_embedded_content {
                   10952:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10953:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  10954:         %currsubfile,%unused,$rem);
1.1071    raeburn  10955:     my $counter = 0;
                   10956:     my $numnew = 0;
1.987     raeburn  10957:     my $numremref = 0;
                   10958:     my $numinvalid = 0;
                   10959:     my $numpathchg = 0;
                   10960:     my $numexisting = 0;
1.1071    raeburn  10961:     my $numunused = 0;
                   10962:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10963:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10964:     my $heading = &mt('Upload embedded files');
                   10965:     my $buttontext = &mt('Upload');
                   10966: 
1.1075.2.11  raeburn  10967:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10968:         if ($actionurl eq '/adm/dependencies') {
                   10969:             $navmap = Apache::lonnavmaps::navmap->new();
                   10970:         }
                   10971:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10972:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10973:     }
1.1075.2.35  raeburn  10974:     if (($actionurl eq '/adm/portfolio') ||
                   10975:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10976:         my $current_path='/';
                   10977:         if ($env{'form.currentpath'}) {
                   10978:             $current_path = $env{'form.currentpath'};
                   10979:         }
                   10980:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10981:             $udom = $cdom;
                   10982:             $uname = $cnum;
1.984     raeburn  10983:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10984:         } else {
                   10985:             $udom = $env{'user.domain'};
                   10986:             $uname = $env{'user.name'};
                   10987:             $url = '/userfiles/portfolio';
                   10988:         }
1.987     raeburn  10989:         $toplevel = $url.'/';
1.984     raeburn  10990:         $url .= $current_path;
                   10991:         $getpropath = 1;
1.987     raeburn  10992:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10993:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10994:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10995:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10996:         $toplevel = $url;
1.984     raeburn  10997:         if ($rest ne '') {
1.987     raeburn  10998:             $url .= $rest;
                   10999:         }
                   11000:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11001:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11002:             $url = $args->{'docs_url'};
                   11003:             $toplevel = $url;
1.1075.2.11  raeburn  11004:             if ($args->{'context'} eq 'paste') {
                   11005:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11006:                 ($path) =
                   11007:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11008:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11009:                 $fileloc =~ s{^/}{};
                   11010:             }
1.1071    raeburn  11011:         }
                   11012:     } elsif ($actionurl eq '/adm/dependencies') {
                   11013:         if ($env{'request.course.id'} ne '') {
                   11014:             if (ref($args) eq 'HASH') {
                   11015:                 $url = $args->{'docs_url'};
                   11016:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  11017:                 $toplevel = $url;
                   11018:                 unless ($toplevel =~ m{^/}) {
                   11019:                     $toplevel = "/$url";
                   11020:                 }
1.1075.2.11  raeburn  11021:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  11022:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11023:                     $path = $1;
                   11024:                 } else {
                   11025:                     ($path) =
                   11026:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11027:                 }
1.1075.2.79  raeburn  11028:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11029:                     $fileloc = $toplevel;
                   11030:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11031:                     my ($udom,$uname,$fname) =
                   11032:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11033:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11034:                 } else {
                   11035:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11036:                 }
1.1071    raeburn  11037:                 $fileloc =~ s{^/}{};
                   11038:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11039:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11040:             }
1.987     raeburn  11041:         }
1.1075.2.35  raeburn  11042:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11043:         $udom = $cdom;
                   11044:         $uname = $cnum;
                   11045:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11046:         $toplevel = $url;
                   11047:         $path = $url;
                   11048:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11049:         $fileloc =~ s{^/}{};
                   11050:     }
                   11051:     foreach my $file (keys(%{$allfiles})) {
                   11052:         my $embed_file;
                   11053:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11054:             $embed_file = $1;
                   11055:         } else {
                   11056:             $embed_file = $file;
                   11057:         }
1.1075.2.55  raeburn  11058:         my ($absolutepath,$cleaned_file);
                   11059:         if ($embed_file =~ m{^\w+://}) {
                   11060:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  11061:             $newfiles{$cleaned_file} = 1;
                   11062:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11063:         } else {
1.1075.2.55  raeburn  11064:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11065:             if ($embed_file =~ m{^/}) {
                   11066:                 $absolutepath = $embed_file;
                   11067:             }
1.1075.2.47  raeburn  11068:             if ($cleaned_file =~ m{/}) {
                   11069:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11070:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11071:                 my $item = $fname;
                   11072:                 if ($path ne '') {
                   11073:                     $item = $path.'/'.$fname;
                   11074:                     $subdependencies{$path}{$fname} = 1;
                   11075:                 } else {
                   11076:                     $dependencies{$item} = 1;
                   11077:                 }
                   11078:                 if ($absolutepath) {
                   11079:                     $mapping{$item} = $absolutepath;
                   11080:                 } else {
                   11081:                     $mapping{$item} = $embed_file;
                   11082:                 }
                   11083:             } else {
                   11084:                 $dependencies{$embed_file} = 1;
                   11085:                 if ($absolutepath) {
1.1075.2.47  raeburn  11086:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11087:                 } else {
1.1075.2.47  raeburn  11088:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11089:                 }
                   11090:             }
1.984     raeburn  11091:         }
                   11092:     }
1.1071    raeburn  11093:     my $dirptr = 16384;
1.984     raeburn  11094:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11095:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  11096:         if (($actionurl eq '/adm/portfolio') ||
                   11097:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  11098:             my ($sublistref,$listerror) =
                   11099:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11100:             if (ref($sublistref) eq 'ARRAY') {
                   11101:                 foreach my $line (@{$sublistref}) {
                   11102:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11103:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11104:                 }
1.984     raeburn  11105:             }
1.987     raeburn  11106:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11107:             if (opendir(my $dir,$url.'/'.$path)) {
                   11108:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11109:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11110:             }
1.1075.2.11  raeburn  11111:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11112:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  11113:                   ($args->{'context'} eq 'paste')) ||
                   11114:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11115:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  11116:                 my $dir;
                   11117:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11118:                     $dir = $fileloc;
                   11119:                 } else {
                   11120:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11121:                 }
1.1071    raeburn  11122:                 if ($dir ne '') {
                   11123:                     my ($sublistref,$listerror) =
                   11124:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11125:                     if (ref($sublistref) eq 'ARRAY') {
                   11126:                         foreach my $line (@{$sublistref}) {
                   11127:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11128:                                 undef,$mtime)=split(/\&/,$line,12);
                   11129:                             unless (($testdir&$dirptr) ||
                   11130:                                     ($file_name =~ /^\.\.?$/)) {
                   11131:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11132:                             }
                   11133:                         }
                   11134:                     }
                   11135:                 }
1.984     raeburn  11136:             }
                   11137:         }
                   11138:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11139:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11140:                 my $item = $path.'/'.$file;
                   11141:                 unless ($mapping{$item} eq $item) {
                   11142:                     $pathchanges{$item} = 1;
                   11143:                 }
                   11144:                 $existing{$item} = 1;
                   11145:                 $numexisting ++;
                   11146:             } else {
                   11147:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11148:             }
                   11149:         }
1.1071    raeburn  11150:         if ($actionurl eq '/adm/dependencies') {
                   11151:             foreach my $path (keys(%currsubfile)) {
                   11152:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11153:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11154:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  11155:                              next if (($rem ne '') &&
                   11156:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11157:                                        (ref($navmap) &&
                   11158:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11159:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11160:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11161:                              $unused{$path.'/'.$file} = 1; 
                   11162:                          }
                   11163:                     }
                   11164:                 }
                   11165:             }
                   11166:         }
1.984     raeburn  11167:     }
1.987     raeburn  11168:     my %currfile;
1.1075.2.35  raeburn  11169:     if (($actionurl eq '/adm/portfolio') ||
                   11170:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11171:         my ($dirlistref,$listerror) =
                   11172:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11173:         if (ref($dirlistref) eq 'ARRAY') {
                   11174:             foreach my $line (@{$dirlistref}) {
                   11175:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11176:                 $currfile{$file_name} = 1;
                   11177:             }
1.984     raeburn  11178:         }
1.987     raeburn  11179:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11180:         if (opendir(my $dir,$url)) {
1.987     raeburn  11181:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11182:             map {$currfile{$_} = 1;} @dir_list;
                   11183:         }
1.1075.2.11  raeburn  11184:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11185:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  11186:               ($args->{'context'} eq 'paste')) ||
                   11187:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11188:         if ($env{'request.course.id'} ne '') {
                   11189:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11190:             if ($dir ne '') {
                   11191:                 my ($dirlistref,$listerror) =
                   11192:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11193:                 if (ref($dirlistref) eq 'ARRAY') {
                   11194:                     foreach my $line (@{$dirlistref}) {
                   11195:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11196:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11197:                         unless (($testdir&$dirptr) ||
                   11198:                                 ($file_name =~ /^\.\.?$/)) {
                   11199:                             $currfile{$file_name} = [$size,$mtime];
                   11200:                         }
                   11201:                     }
                   11202:                 }
                   11203:             }
                   11204:         }
1.984     raeburn  11205:     }
                   11206:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11207:         if (exists($currfile{$file})) {
1.987     raeburn  11208:             unless ($mapping{$file} eq $file) {
                   11209:                 $pathchanges{$file} = 1;
                   11210:             }
                   11211:             $existing{$file} = 1;
                   11212:             $numexisting ++;
                   11213:         } else {
1.984     raeburn  11214:             $newfiles{$file} = 1;
                   11215:         }
                   11216:     }
1.1071    raeburn  11217:     foreach my $file (keys(%currfile)) {
                   11218:         unless (($file eq $filename) ||
                   11219:                 ($file eq $filename.'.bak') ||
                   11220:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  11221:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  11222:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11223:                     next if (($rem ne '') &&
                   11224:                              (($env{"httpref.$rem".$file} ne '') ||
                   11225:                               (ref($navmap) &&
                   11226:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11227:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11228:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11229:                 }
1.1075.2.11  raeburn  11230:             }
1.1071    raeburn  11231:             $unused{$file} = 1;
                   11232:         }
                   11233:     }
1.1075.2.11  raeburn  11234:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11235:         ($args->{'context'} eq 'paste')) {
                   11236:         $counter = scalar(keys(%existing));
                   11237:         $numpathchg = scalar(keys(%pathchanges));
                   11238:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  11239:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   11240:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11241:         $counter = scalar(keys(%existing));
                   11242:         $numpathchg = scalar(keys(%pathchanges));
                   11243:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  11244:     }
1.984     raeburn  11245:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11246:         if ($actionurl eq '/adm/dependencies') {
                   11247:             next if ($embed_file =~ m{^\w+://});
                   11248:         }
1.660     raeburn  11249:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11250:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11251:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11252:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  11253:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11254:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11255:         }
1.1075.2.35  raeburn  11256:         $upload_output .= '</td>';
1.1071    raeburn  11257:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  11258:             $upload_output.='<td align="right">'.
                   11259:                             '<span class="LC_info LC_fontsize_medium">'.
                   11260:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11261:             $numremref++;
1.660     raeburn  11262:         } elsif ($args->{'error_on_invalid_names'}
                   11263:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  11264:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11265:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11266:             $numinvalid++;
1.660     raeburn  11267:         } else {
1.1075.2.35  raeburn  11268:             $upload_output .= '<td>'.
                   11269:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11270:                                                      $embed_file,\%mapping,
1.1071    raeburn  11271:                                                      $allfiles,$codebase,'upload');
                   11272:             $counter ++;
                   11273:             $numnew ++;
1.987     raeburn  11274:         }
                   11275:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11276:     }
                   11277:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11278:         if ($actionurl eq '/adm/dependencies') {
                   11279:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11280:             $modify_output .= &start_data_table_row().
                   11281:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11282:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11283:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11284:                               '<td>'.$size.'</td>'.
                   11285:                               '<td>'.$mtime.'</td>'.
                   11286:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11287:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11288:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11289:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11290:                               &embedded_file_element('upload_embedded',$counter,
                   11291:                                                      $embed_file,\%mapping,
                   11292:                                                      $allfiles,$codebase,'modify').
                   11293:                               '</div></td>'.
                   11294:                               &end_data_table_row()."\n";
                   11295:             $counter ++;
                   11296:         } else {
                   11297:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11298:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11299:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11300:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11301:                               &Apache::loncommon::end_data_table_row()."\n";
                   11302:         }
                   11303:     }
                   11304:     my $delidx = $counter;
                   11305:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11306:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11307:         $delete_output .= &start_data_table_row().
                   11308:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11309:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11310:                           '<td>'.$size.'</td>'.
                   11311:                           '<td>'.$mtime.'</td>'.
                   11312:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11313:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11314:                           &embedded_file_element('upload_embedded',$delidx,
                   11315:                                                  $oldfile,\%mapping,$allfiles,
                   11316:                                                  $codebase,'delete').'</td>'.
                   11317:                           &end_data_table_row()."\n"; 
                   11318:         $numunused ++;
                   11319:         $delidx ++;
1.987     raeburn  11320:     }
                   11321:     if ($upload_output) {
                   11322:         $upload_output = &start_data_table().
                   11323:                          $upload_output.
                   11324:                          &end_data_table()."\n";
                   11325:     }
1.1071    raeburn  11326:     if ($modify_output) {
                   11327:         $modify_output = &start_data_table().
                   11328:                          &start_data_table_header_row().
                   11329:                          '<th>'.&mt('File').'</th>'.
                   11330:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11331:                          '<th>'.&mt('Modified').'</th>'.
                   11332:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11333:                          &end_data_table_header_row().
                   11334:                          $modify_output.
                   11335:                          &end_data_table()."\n";
                   11336:     }
                   11337:     if ($delete_output) {
                   11338:         $delete_output = &start_data_table().
                   11339:                          &start_data_table_header_row().
                   11340:                          '<th>'.&mt('File').'</th>'.
                   11341:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11342:                          '<th>'.&mt('Modified').'</th>'.
                   11343:                          '<th>'.&mt('Delete?').'</th>'.
                   11344:                          &end_data_table_header_row().
                   11345:                          $delete_output.
                   11346:                          &end_data_table()."\n";
                   11347:     }
1.987     raeburn  11348:     my $applies = 0;
                   11349:     if ($numremref) {
                   11350:         $applies ++;
                   11351:     }
                   11352:     if ($numinvalid) {
                   11353:         $applies ++;
                   11354:     }
                   11355:     if ($numexisting) {
                   11356:         $applies ++;
                   11357:     }
1.1071    raeburn  11358:     if ($counter || $numunused) {
1.987     raeburn  11359:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11360:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11361:                   $state.'<h3>'.$heading.'</h3>'; 
                   11362:         if ($actionurl eq '/adm/dependencies') {
                   11363:             if ($numnew) {
                   11364:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11365:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11366:                            $upload_output.'<br />'."\n";
                   11367:             }
                   11368:             if ($numexisting) {
                   11369:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11370:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11371:                            $modify_output.'<br />'."\n";
                   11372:                            $buttontext = &mt('Save changes');
                   11373:             }
                   11374:             if ($numunused) {
                   11375:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11376:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11377:                            $delete_output.'<br />'."\n";
                   11378:                            $buttontext = &mt('Save changes');
                   11379:             }
                   11380:         } else {
                   11381:             $output .= $upload_output.'<br />'."\n";
                   11382:         }
                   11383:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11384:                    $counter.'" />'."\n";
                   11385:         if ($actionurl eq '/adm/dependencies') { 
                   11386:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11387:                        $numnew.'" />'."\n";
                   11388:         } elsif ($actionurl eq '') {
1.987     raeburn  11389:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11390:         }
                   11391:     } elsif ($applies) {
                   11392:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11393:         if ($applies > 1) {
                   11394:             $output .=  
1.1075.2.35  raeburn  11395:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11396:             if ($numremref) {
                   11397:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11398:             }
                   11399:             if ($numinvalid) {
                   11400:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11401:             }
                   11402:             if ($numexisting) {
                   11403:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11404:             }
                   11405:             $output .= '</ul><br />';
                   11406:         } elsif ($numremref) {
                   11407:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11408:         } elsif ($numinvalid) {
                   11409:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11410:         } elsif ($numexisting) {
                   11411:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11412:         }
                   11413:         $output .= $upload_output.'<br />';
                   11414:     }
                   11415:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11416:     $chgcount = $counter;
1.987     raeburn  11417:     if (keys(%pathchanges) > 0) {
                   11418:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11419:             if ($counter) {
1.987     raeburn  11420:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11421:                                                   $embed_file,\%mapping,
1.1071    raeburn  11422:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11423:             } else {
                   11424:                 $pathchange_output .= 
                   11425:                     &start_data_table_row().
                   11426:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11427:                     $chgcount.'" checked="checked" /></td>'.
                   11428:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11429:                     '<td>'.$embed_file.
                   11430:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11431:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11432:                     '</td>'.&end_data_table_row();
1.660     raeburn  11433:             }
1.987     raeburn  11434:             $numpathchg ++;
                   11435:             $chgcount ++;
1.660     raeburn  11436:         }
                   11437:     }
1.1075.2.35  raeburn  11438:     if (($counter) || ($numunused)) {
1.987     raeburn  11439:         if ($numpathchg) {
                   11440:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11441:                        $numpathchg.'" />'."\n";
                   11442:         }
                   11443:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11444:             ($actionurl eq '/adm/imsimport')) {
                   11445:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11446:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11447:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11448:         } elsif ($actionurl eq '/adm/dependencies') {
                   11449:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11450:         }
1.1075.2.35  raeburn  11451:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11452:     } elsif ($numpathchg) {
                   11453:         my %pathchange = ();
                   11454:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11455:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11456:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  11457:         }
1.987     raeburn  11458:     }
1.1071    raeburn  11459:     return ($output,$counter,$numpathchg);
1.987     raeburn  11460: }
                   11461: 
1.1075.2.47  raeburn  11462: =pod
                   11463: 
                   11464: =item * clean_path($name)
                   11465: 
                   11466: Performs clean-up of directories, subdirectories and filename in an
                   11467: embedded object, referenced in an HTML file which is being uploaded
                   11468: to a course or portfolio, where
                   11469: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11470: checked.
                   11471: 
                   11472: Clean-up is similar to replacements in lonnet::clean_filename()
                   11473: except each / between sub-directory and next level is preserved.
                   11474: 
                   11475: =cut
                   11476: 
                   11477: sub clean_path {
                   11478:     my ($embed_file) = @_;
                   11479:     $embed_file =~s{^/+}{};
                   11480:     my @contents;
                   11481:     if ($embed_file =~ m{/}) {
                   11482:         @contents = split(/\//,$embed_file);
                   11483:     } else {
                   11484:         @contents = ($embed_file);
                   11485:     }
                   11486:     my $lastidx = scalar(@contents)-1;
                   11487:     for (my $i=0; $i<=$lastidx; $i++) {
                   11488:         $contents[$i]=~s{\\}{/}g;
                   11489:         $contents[$i]=~s/\s+/\_/g;
                   11490:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11491:         if ($i == $lastidx) {
                   11492:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11493:         }
                   11494:     }
                   11495:     if ($lastidx > 0) {
                   11496:         return join('/',@contents);
                   11497:     } else {
                   11498:         return $contents[0];
                   11499:     }
                   11500: }
                   11501: 
1.987     raeburn  11502: sub embedded_file_element {
1.1071    raeburn  11503:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11504:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11505:                    (ref($codebase) eq 'HASH'));
                   11506:     my $output;
1.1071    raeburn  11507:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11508:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11509:     }
                   11510:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11511:                &escape($embed_file).'" />';
                   11512:     unless (($context eq 'upload_embedded') && 
                   11513:             ($mapping->{$embed_file} eq $embed_file)) {
                   11514:         $output .='
                   11515:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11516:     }
                   11517:     my $attrib;
                   11518:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11519:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11520:     }
                   11521:     $output .=
                   11522:         "\n\t\t".
                   11523:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11524:         $attrib.'" />';
                   11525:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11526:         $output .=
                   11527:             "\n\t\t".
                   11528:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11529:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11530:     }
1.987     raeburn  11531:     return $output;
1.660     raeburn  11532: }
                   11533: 
1.1071    raeburn  11534: sub get_dependency_details {
                   11535:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11536:     my ($size,$mtime,$showsize,$showmtime);
                   11537:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11538:         if ($embed_file =~ m{/}) {
                   11539:             my ($path,$fname) = split(/\//,$embed_file);
                   11540:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11541:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11542:             }
                   11543:         } else {
                   11544:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11545:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11546:             }
                   11547:         }
                   11548:         $showsize = $size/1024.0;
                   11549:         $showsize = sprintf("%.1f",$showsize);
                   11550:         if ($mtime > 0) {
                   11551:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11552:         }
                   11553:     }
                   11554:     return ($showsize,$showmtime);
                   11555: }
                   11556: 
                   11557: sub ask_embedded_js {
                   11558:     return <<"END";
                   11559: <script type="text/javascript"">
                   11560: // <![CDATA[
                   11561: function toggleBrowse(counter) {
                   11562:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11563:     var fileid = document.getElementById('embedded_item_'+counter);
                   11564:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11565:     if (chkboxid.checked == true) {
                   11566:         uploaddivid.style.display='block';
                   11567:     } else {
                   11568:         uploaddivid.style.display='none';
                   11569:         fileid.value = '';
                   11570:     }
                   11571: }
                   11572: // ]]>
                   11573: </script>
                   11574: 
                   11575: END
                   11576: }
                   11577: 
1.661     raeburn  11578: sub upload_embedded {
                   11579:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11580:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11581:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11582:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11583:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11584:         my $orig_uploaded_filename =
                   11585:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11586:         foreach my $type ('orig','ref','attrib','codebase') {
                   11587:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11588:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11589:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11590:             }
                   11591:         }
1.661     raeburn  11592:         my ($path,$fname) =
                   11593:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11594:         # no path, whole string is fname
                   11595:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11596:         $fname = &Apache::lonnet::clean_filename($fname);
                   11597:         # See if there is anything left
                   11598:         next if ($fname eq '');
                   11599: 
                   11600:         # Check if file already exists as a file or directory.
                   11601:         my ($state,$msg);
                   11602:         if ($context eq 'portfolio') {
                   11603:             my $port_path = $dirpath;
                   11604:             if ($group ne '') {
                   11605:                 $port_path = "groups/$group/$port_path";
                   11606:             }
1.987     raeburn  11607:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11608:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11609:                                               $dir_root,$port_path,$disk_quota,
                   11610:                                               $current_disk_usage,$uname,$udom);
                   11611:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11612:                 || $state eq 'file_locked') {
1.661     raeburn  11613:                 $output .= $msg;
                   11614:                 next;
                   11615:             }
                   11616:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11617:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11618:             if ($state eq 'exists') {
                   11619:                 $output .= $msg;
                   11620:                 next;
                   11621:             }
                   11622:         }
                   11623:         # Check if extension is valid
                   11624:         if (($fname =~ /\.(\w+)$/) &&
                   11625:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  11626:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11627:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11628:             next;
                   11629:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11630:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11631:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11632:             next;
                   11633:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  11634:             $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  11635:             next;
                   11636:         }
                   11637:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  11638:         my $subdir = $path;
                   11639:         $subdir =~ s{/+$}{};
1.661     raeburn  11640:         if ($context eq 'portfolio') {
1.984     raeburn  11641:             my $result;
                   11642:             if ($state eq 'existingfile') {
                   11643:                 $result=
                   11644:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  11645:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11646:             } else {
1.984     raeburn  11647:                 $result=
                   11648:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11649:                                                     $dirpath.
1.1075.2.35  raeburn  11650:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11651:                 if ($result !~ m|^/uploaded/|) {
                   11652:                     $output .= '<span class="LC_error">'
                   11653:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11654:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11655:                                .'</span><br />';
                   11656:                     next;
                   11657:                 } else {
1.987     raeburn  11658:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11659:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11660:                 }
1.661     raeburn  11661:             }
1.1075.2.35  raeburn  11662:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   11663:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11664:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11665:             my $result =
1.1075.2.35  raeburn  11666:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11667:             if ($result !~ m|^/uploaded/|) {
                   11668:                 $output .= '<span class="LC_error">'
                   11669:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11670:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11671:                            .'</span><br />';
                   11672:                     next;
                   11673:             } else {
                   11674:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11675:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  11676:                 if ($context eq 'syllabus') {
                   11677:                     &Apache::lonnet::make_public_indefinitely($result);
                   11678:                 }
1.987     raeburn  11679:             }
1.661     raeburn  11680:         } else {
                   11681: # Save the file
                   11682:             my $target = $env{'form.embedded_item_'.$i};
                   11683:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11684:             my $dest = $fullpath.$fname;
                   11685:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11686:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11687:             my $count;
                   11688:             my $filepath = $dir_root;
1.1027    raeburn  11689:             foreach my $subdir (@parts) {
                   11690:                 $filepath .= "/$subdir";
                   11691:                 if (!-e $filepath) {
1.661     raeburn  11692:                     mkdir($filepath,0770);
                   11693:                 }
                   11694:             }
                   11695:             my $fh;
                   11696:             if (!open($fh,'>'.$dest)) {
                   11697:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11698:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11699:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11700:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11701:                            '</span><br />';
                   11702:             } else {
                   11703:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11704:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11705:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11706:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11707:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11708:                               '</span><br />';
                   11709:                 } else {
1.987     raeburn  11710:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11711:                                $url.'</span>').'<br />';
                   11712:                     unless ($context eq 'testbank') {
                   11713:                         $footer .= &mt('View embedded file: [_1]',
                   11714:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11715:                     }
                   11716:                 }
                   11717:                 close($fh);
                   11718:             }
                   11719:         }
                   11720:         if ($env{'form.embedded_ref_'.$i}) {
                   11721:             $pathchange{$i} = 1;
                   11722:         }
                   11723:     }
                   11724:     if ($output) {
                   11725:         $output = '<p>'.$output.'</p>';
                   11726:     }
                   11727:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11728:     $returnflag = 'ok';
1.1071    raeburn  11729:     my $numpathchgs = scalar(keys(%pathchange));
                   11730:     if ($numpathchgs > 0) {
1.987     raeburn  11731:         if ($context eq 'portfolio') {
                   11732:             $output .= '<p>'.&mt('or').'</p>';
                   11733:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11734:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11735:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11736:             $returnflag = 'modify_orightml';
                   11737:         }
                   11738:     }
1.1071    raeburn  11739:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11740: }
                   11741: 
                   11742: sub modify_html_form {
                   11743:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11744:     my $end = 0;
                   11745:     my $modifyform;
                   11746:     if ($context eq 'upload_embedded') {
                   11747:         return unless (ref($pathchange) eq 'HASH');
                   11748:         if ($env{'form.number_embedded_items'}) {
                   11749:             $end += $env{'form.number_embedded_items'};
                   11750:         }
                   11751:         if ($env{'form.number_pathchange_items'}) {
                   11752:             $end += $env{'form.number_pathchange_items'};
                   11753:         }
                   11754:         if ($end) {
                   11755:             for (my $i=0; $i<$end; $i++) {
                   11756:                 if ($i < $env{'form.number_embedded_items'}) {
                   11757:                     next unless($pathchange->{$i});
                   11758:                 }
                   11759:                 $modifyform .=
                   11760:                     &start_data_table_row().
                   11761:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11762:                     'checked="checked" /></td>'.
                   11763:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11764:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11765:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11766:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11767:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11768:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11769:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11770:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11771:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11772:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11773:                     &end_data_table_row();
1.1071    raeburn  11774:             }
1.987     raeburn  11775:         }
                   11776:     } else {
                   11777:         $modifyform = $pathchgtable;
                   11778:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11779:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11780:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11781:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11782:         }
                   11783:     }
                   11784:     if ($modifyform) {
1.1071    raeburn  11785:         if ($actionurl eq '/adm/dependencies') {
                   11786:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11787:         }
1.987     raeburn  11788:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11789:                '<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".
                   11790:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11791:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11792:                '</ol></p>'."\n".'<p>'.
                   11793:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11794:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11795:                &start_data_table()."\n".
                   11796:                &start_data_table_header_row().
                   11797:                '<th>'.&mt('Change?').'</th>'.
                   11798:                '<th>'.&mt('Current reference').'</th>'.
                   11799:                '<th>'.&mt('Required reference').'</th>'.
                   11800:                &end_data_table_header_row()."\n".
                   11801:                $modifyform.
                   11802:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11803:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11804:                '</form>'."\n";
                   11805:     }
                   11806:     return;
                   11807: }
                   11808: 
                   11809: sub modify_html_refs {
1.1075.2.35  raeburn  11810:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11811:     my $container;
                   11812:     if ($context eq 'portfolio') {
                   11813:         $container = $env{'form.container'};
                   11814:     } elsif ($context eq 'coursedoc') {
                   11815:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11816:     } elsif ($context eq 'manage_dependencies') {
                   11817:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11818:         $container = "/$container";
1.1075.2.35  raeburn  11819:     } elsif ($context eq 'syllabus') {
                   11820:         $container = $url;
1.987     raeburn  11821:     } else {
1.1027    raeburn  11822:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11823:     }
                   11824:     my (%allfiles,%codebase,$output,$content);
                   11825:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  11826:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  11827:         if (wantarray) {
                   11828:             return ('',0,0); 
                   11829:         } else {
                   11830:             return;
                   11831:         }
                   11832:     }
                   11833:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11834:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11835:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11836:             if (wantarray) {
                   11837:                 return ('',0,0);
                   11838:             } else {
                   11839:                 return;
                   11840:             }
                   11841:         } 
1.987     raeburn  11842:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11843:         if ($content eq '-1') {
                   11844:             if (wantarray) {
                   11845:                 return ('',0,0);
                   11846:             } else {
                   11847:                 return;
                   11848:             }
                   11849:         }
1.987     raeburn  11850:     } else {
1.1071    raeburn  11851:         unless ($container =~ /^\Q$dir_root\E/) {
                   11852:             if (wantarray) {
                   11853:                 return ('',0,0);
                   11854:             } else {
                   11855:                 return;
                   11856:             }
                   11857:         } 
1.1075.2.128  raeburn  11858:         if (open(my $fh,'<',$container)) {
1.987     raeburn  11859:             $content = join('', <$fh>);
                   11860:             close($fh);
                   11861:         } else {
1.1071    raeburn  11862:             if (wantarray) {
                   11863:                 return ('',0,0);
                   11864:             } else {
                   11865:                 return;
                   11866:             }
1.987     raeburn  11867:         }
                   11868:     }
                   11869:     my ($count,$codebasecount) = (0,0);
                   11870:     my $mm = new File::MMagic;
                   11871:     my $mime_type = $mm->checktype_contents($content);
                   11872:     if ($mime_type eq 'text/html') {
                   11873:         my $parse_result = 
                   11874:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11875:                                                     \%codebase,\$content);
                   11876:         if ($parse_result eq 'ok') {
                   11877:             foreach my $i (@changes) {
                   11878:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11879:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11880:                 if ($allfiles{$ref}) {
                   11881:                     my $newname =  $orig;
                   11882:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11883:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11884:                     if ($attrib_regexp =~ /:/) {
                   11885:                         $attrib_regexp =~ s/\:/|/g;
                   11886:                     }
                   11887:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11888:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11889:                         $count += $numchg;
1.1075.2.35  raeburn  11890:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  11891:                         delete($allfiles{$ref});
1.987     raeburn  11892:                     }
                   11893:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11894:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11895:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11896:                         $codebasecount ++;
                   11897:                     }
                   11898:                 }
                   11899:             }
1.1075.2.35  raeburn  11900:             my $skiprewrites;
1.987     raeburn  11901:             if ($count || $codebasecount) {
                   11902:                 my $saveresult;
1.1071    raeburn  11903:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11904:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11905:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11906:                     if ($url eq $container) {
                   11907:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11908:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11909:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11910:                                             $fname.'</span>').'</p>';
1.987     raeburn  11911:                     } else {
                   11912:                          $output = '<p class="LC_error">'.
                   11913:                                    &mt('Error: update failed for: [_1].',
                   11914:                                    '<span class="LC_filename">'.
                   11915:                                    $container.'</span>').'</p>';
                   11916:                     }
1.1075.2.35  raeburn  11917:                     if ($context eq 'syllabus') {
                   11918:                         unless ($saveresult eq 'ok') {
                   11919:                             $skiprewrites = 1;
                   11920:                         }
                   11921:                     }
1.987     raeburn  11922:                 } else {
1.1075.2.128  raeburn  11923:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  11924:                         print $fh $content;
                   11925:                         close($fh);
                   11926:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11927:                                   $count,'<span class="LC_filename">'.
                   11928:                                   $container.'</span>').'</p>';
1.661     raeburn  11929:                     } else {
1.987     raeburn  11930:                          $output = '<p class="LC_error">'.
                   11931:                                    &mt('Error: could not update [_1].',
                   11932:                                    '<span class="LC_filename">'.
                   11933:                                    $container.'</span>').'</p>';
1.661     raeburn  11934:                     }
                   11935:                 }
                   11936:             }
1.1075.2.35  raeburn  11937:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11938:                 my ($actionurl,$state);
                   11939:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11940:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11941:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11942:                                               \%codebase,
                   11943:                                               {'context' => 'rewrites',
                   11944:                                                'ignore_remote_references' => 1,});
                   11945:                 if (ref($mapping) eq 'HASH') {
                   11946:                     my $rewrites = 0;
                   11947:                     foreach my $key (keys(%{$mapping})) {
                   11948:                         next if ($key =~ m{^https?://});
                   11949:                         my $ref = $mapping->{$key};
                   11950:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11951:                         my $attrib;
                   11952:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11953:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11954:                         }
                   11955:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11956:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11957:                             $rewrites += $numchg;
                   11958:                         }
                   11959:                     }
                   11960:                     if ($rewrites) {
                   11961:                         my $saveresult;
                   11962:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11963:                         if ($url eq $container) {
                   11964:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11965:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11966:                                             $count,'<span class="LC_filename">'.
                   11967:                                             $fname.'</span>').'</p>';
                   11968:                         } else {
                   11969:                             $output .= '<p class="LC_error">'.
                   11970:                                        &mt('Error: could not update links in [_1].',
                   11971:                                        '<span class="LC_filename">'.
                   11972:                                        $container.'</span>').'</p>';
                   11973: 
                   11974:                         }
                   11975:                     }
                   11976:                 }
                   11977:             }
1.987     raeburn  11978:         } else {
                   11979:             &logthis('Failed to parse '.$container.
                   11980:                      ' to modify references: '.$parse_result);
1.661     raeburn  11981:         }
                   11982:     }
1.1071    raeburn  11983:     if (wantarray) {
                   11984:         return ($output,$count,$codebasecount);
                   11985:     } else {
                   11986:         return $output;
                   11987:     }
1.661     raeburn  11988: }
                   11989: 
                   11990: sub check_for_existing {
                   11991:     my ($path,$fname,$element) = @_;
                   11992:     my ($state,$msg);
                   11993:     if (-d $path.'/'.$fname) {
                   11994:         $state = 'exists';
                   11995:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11996:     } elsif (-e $path.'/'.$fname) {
                   11997:         $state = 'exists';
                   11998:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11999:     }
                   12000:     if ($state eq 'exists') {
                   12001:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12002:     }
                   12003:     return ($state,$msg);
                   12004: }
                   12005: 
                   12006: sub check_for_upload {
                   12007:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12008:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12009:     my $filesize = length($env{'form.'.$element});
                   12010:     if (!$filesize) {
                   12011:         my $msg = '<span class="LC_error">'.
                   12012:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12013:                       '<span class="LC_filename">'.$fname.'</span>',
                   12014:                       $filesize).'<br />'.
1.1007    raeburn  12015:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12016:                   '</span>';
                   12017:         return ('zero_bytes',$msg);
                   12018:     }
                   12019:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12020:     my $getpropath = 1;
1.1021    raeburn  12021:     my ($dirlistref,$listerror) =
                   12022:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12023:     my $found_file = 0;
                   12024:     my $locked_file = 0;
1.991     raeburn  12025:     my @lockers;
                   12026:     my $navmap;
                   12027:     if ($env{'request.course.id'}) {
                   12028:         $navmap = Apache::lonnavmaps::navmap->new();
                   12029:     }
1.1021    raeburn  12030:     if (ref($dirlistref) eq 'ARRAY') {
                   12031:         foreach my $line (@{$dirlistref}) {
                   12032:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12033:             if ($file_name eq $fname){
                   12034:                 $file_name = $path.$file_name;
                   12035:                 if ($group ne '') {
                   12036:                     $file_name = $group.$file_name;
                   12037:                 }
                   12038:                 $found_file = 1;
                   12039:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12040:                     foreach my $lock (@lockers) {
                   12041:                         if (ref($lock) eq 'ARRAY') {
                   12042:                             my ($symb,$crsid) = @{$lock};
                   12043:                             if ($crsid eq $env{'request.course.id'}) {
                   12044:                                 if (ref($navmap)) {
                   12045:                                     my $res = $navmap->getBySymb($symb);
                   12046:                                     foreach my $part (@{$res->parts()}) { 
                   12047:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12048:                                         unless (($slot_status == $res->RESERVED) ||
                   12049:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12050:                                             $locked_file = 1;
                   12051:                                         }
1.991     raeburn  12052:                                     }
1.1021    raeburn  12053:                                 } else {
                   12054:                                     $locked_file = 1;
1.991     raeburn  12055:                                 }
                   12056:                             } else {
                   12057:                                 $locked_file = 1;
                   12058:                             }
                   12059:                         }
1.1021    raeburn  12060:                    }
                   12061:                 } else {
                   12062:                     my @info = split(/\&/,$rest);
                   12063:                     my $currsize = $info[6]/1000;
                   12064:                     if ($currsize < $filesize) {
                   12065:                         my $extra = $filesize - $currsize;
                   12066:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  12067:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12068:                                       &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  12069:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12070:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12071:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12072:                             return ('will_exceed_quota',$msg);
                   12073:                         }
1.984     raeburn  12074:                     }
                   12075:                 }
1.661     raeburn  12076:             }
                   12077:         }
                   12078:     }
                   12079:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  12080:         my $msg = '<p class="LC_warning">'.
                   12081:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   12082:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12083:         return ('will_exceed_quota',$msg);
                   12084:     } elsif ($found_file) {
                   12085:         if ($locked_file) {
1.1075.2.69  raeburn  12086:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12087:             $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  12088:             $msg .= '</p>';
1.661     raeburn  12089:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12090:             return ('file_locked',$msg);
                   12091:         } else {
1.1075.2.69  raeburn  12092:             my $msg = '<p class="LC_error">';
1.984     raeburn  12093:             $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  12094:             $msg .= '</p>';
1.984     raeburn  12095:             return ('existingfile',$msg);
1.661     raeburn  12096:         }
                   12097:     }
                   12098: }
                   12099: 
1.987     raeburn  12100: sub check_for_traversal {
                   12101:     my ($path,$url,$toplevel) = @_;
                   12102:     my @parts=split(/\//,$path);
                   12103:     my $cleanpath;
                   12104:     my $fullpath = $url;
                   12105:     for (my $i=0;$i<@parts;$i++) {
                   12106:         next if ($parts[$i] eq '.');
                   12107:         if ($parts[$i] eq '..') {
                   12108:             $fullpath =~ s{([^/]+/)$}{};
                   12109:         } else {
                   12110:             $fullpath .= $parts[$i].'/';
                   12111:         }
                   12112:     }
                   12113:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12114:         $cleanpath = $1;
                   12115:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12116:         my $curr_toprel = $1;
                   12117:         my @parts = split(/\//,$curr_toprel);
                   12118:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12119:         my @urlparts = split(/\//,$url_toprel);
                   12120:         my $doubledots;
                   12121:         my $startdiff = -1;
                   12122:         for (my $i=0; $i<@urlparts; $i++) {
                   12123:             if ($startdiff == -1) {
                   12124:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12125:                     $startdiff = $i;
                   12126:                     $doubledots .= '../';
                   12127:                 }
                   12128:             } else {
                   12129:                 $doubledots .= '../';
                   12130:             }
                   12131:         }
                   12132:         if ($startdiff > -1) {
                   12133:             $cleanpath = $doubledots;
                   12134:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12135:                 $cleanpath .= $parts[$i].'/';
                   12136:             }
                   12137:         }
                   12138:     }
                   12139:     $cleanpath =~ s{(/)$}{};
                   12140:     return $cleanpath;
                   12141: }
1.31      albertel 12142: 
1.1053    raeburn  12143: sub is_archive_file {
                   12144:     my ($mimetype) = @_;
                   12145:     if (($mimetype eq 'application/octet-stream') ||
                   12146:         ($mimetype eq 'application/x-stuffit') ||
                   12147:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12148:         return 1;
                   12149:     }
                   12150:     return;
                   12151: }
                   12152: 
                   12153: sub decompress_form {
1.1065    raeburn  12154:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12155:     my %lt = &Apache::lonlocal::texthash (
                   12156:         this => 'This file is an archive file.',
1.1067    raeburn  12157:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12158:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12159:         youm => 'You may wish to extract its contents.',
                   12160:         extr => 'Extract contents',
1.1067    raeburn  12161:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12162:         proa => 'Process automatically?',
1.1053    raeburn  12163:         yes  => 'Yes',
                   12164:         no   => 'No',
1.1067    raeburn  12165:         fold => 'Title for folder containing movie',
                   12166:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12167:     );
1.1065    raeburn  12168:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12169:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12170:     my $info = &list_archive_contents($fileloc,\@paths);
                   12171:     if (@paths) {
                   12172:         foreach my $path (@paths) {
                   12173:             $path =~ s{^/}{};
1.1067    raeburn  12174:             if ($path =~ m{^([^/]+)/$}) {
                   12175:                 $topdir = $1;
                   12176:             }
1.1065    raeburn  12177:             if ($path =~ m{^([^/]+)/}) {
                   12178:                 $toplevel{$1} = $path;
                   12179:             } else {
                   12180:                 $toplevel{$path} = $path;
                   12181:             }
                   12182:         }
                   12183:     }
1.1067    raeburn  12184:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  12185:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12186:                         "$topdir/media/",
                   12187:                         "$topdir/media/$topdir.mp4",
                   12188:                         "$topdir/media/FirstFrame.png",
                   12189:                         "$topdir/media/player.swf",
                   12190:                         "$topdir/media/swfobject.js",
                   12191:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  12192:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  12193:                          "$topdir/$topdir.mp4",
                   12194:                          "$topdir/$topdir\_config.xml",
                   12195:                          "$topdir/$topdir\_controller.swf",
                   12196:                          "$topdir/$topdir\_embed.css",
                   12197:                          "$topdir/$topdir\_First_Frame.png",
                   12198:                          "$topdir/$topdir\_player.html",
                   12199:                          "$topdir/$topdir\_Thumbnails.png",
                   12200:                          "$topdir/playerProductInstall.swf",
                   12201:                          "$topdir/scripts/",
                   12202:                          "$topdir/scripts/config_xml.js",
                   12203:                          "$topdir/scripts/handlebars.js",
                   12204:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12205:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12206:                          "$topdir/scripts/modernizr.js",
                   12207:                          "$topdir/scripts/player-min.js",
                   12208:                          "$topdir/scripts/swfobject.js",
                   12209:                          "$topdir/skins/",
                   12210:                          "$topdir/skins/configuration_express.xml",
                   12211:                          "$topdir/skins/express_show/",
                   12212:                          "$topdir/skins/express_show/player-min.css",
                   12213:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  12214:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12215:                          "$topdir/$topdir.mp4",
                   12216:                          "$topdir/$topdir\_config.xml",
                   12217:                          "$topdir/$topdir\_controller.swf",
                   12218:                          "$topdir/$topdir\_embed.css",
                   12219:                          "$topdir/$topdir\_First_Frame.png",
                   12220:                          "$topdir/$topdir\_player.html",
                   12221:                          "$topdir/$topdir\_Thumbnails.png",
                   12222:                          "$topdir/playerProductInstall.swf",
                   12223:                          "$topdir/scripts/",
                   12224:                          "$topdir/scripts/config_xml.js",
                   12225:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12226:                          "$topdir/skins/",
                   12227:                          "$topdir/skins/configuration_express.xml",
                   12228:                          "$topdir/skins/express_show/",
                   12229:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12230:                          "$topdir/skins/express_show/spritesheet.png",
                   12231:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  12232:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12233:         if (@diffs == 0) {
1.1075.2.59  raeburn  12234:             $is_camtasia = 6;
                   12235:         } else {
1.1075.2.81  raeburn  12236:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  12237:             if (@diffs == 0) {
                   12238:                 $is_camtasia = 8;
1.1075.2.81  raeburn  12239:             } else {
                   12240:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12241:                 if (@diffs == 0) {
                   12242:                     $is_camtasia = 8;
                   12243:                 }
1.1075.2.59  raeburn  12244:             }
1.1067    raeburn  12245:         }
                   12246:     }
                   12247:     my $output;
                   12248:     if ($is_camtasia) {
                   12249:         $output = <<"ENDCAM";
                   12250: <script type="text/javascript" language="Javascript">
                   12251: // <![CDATA[
                   12252: 
                   12253: function camtasiaToggle() {
                   12254:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12255:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  12256:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12257:                 document.getElementById('camtasia_titles').style.display='block';
                   12258:             } else {
                   12259:                 document.getElementById('camtasia_titles').style.display='none';
                   12260:             }
                   12261:         }
                   12262:     }
                   12263:     return;
                   12264: }
                   12265: 
                   12266: // ]]>
                   12267: </script>
                   12268: <p>$lt{'camt'}</p>
                   12269: ENDCAM
1.1065    raeburn  12270:     } else {
1.1067    raeburn  12271:         $output = '<p>'.$lt{'this'};
                   12272:         if ($info eq '') {
                   12273:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12274:         } else {
                   12275:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12276:                        '<div><pre>'.$info.'</pre></div>';
                   12277:         }
1.1065    raeburn  12278:     }
1.1067    raeburn  12279:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12280:     my $duplicates;
                   12281:     my $num = 0;
                   12282:     if (ref($dirlist) eq 'ARRAY') {
                   12283:         foreach my $item (@{$dirlist}) {
                   12284:             if (ref($item) eq 'ARRAY') {
                   12285:                 if (exists($toplevel{$item->[0]})) {
                   12286:                     $duplicates .= 
                   12287:                         &start_data_table_row().
                   12288:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12289:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12290:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12291:                         'value="1" />'.&mt('Yes').'</label>'.
                   12292:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12293:                         '<td>'.$item->[0].'</td>';
                   12294:                     if ($item->[2]) {
                   12295:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12296:                     } else {
                   12297:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12298:                     }
                   12299:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12300:                                    '<td>'.
                   12301:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12302:                                    '</td>'.
                   12303:                                    &end_data_table_row();
                   12304:                     $num ++;
                   12305:                 }
                   12306:             }
                   12307:         }
                   12308:     }
                   12309:     my $itemcount;
                   12310:     if (@paths > 0) {
                   12311:         $itemcount = scalar(@paths);
                   12312:     } else {
                   12313:         $itemcount = 1;
                   12314:     }
1.1067    raeburn  12315:     if ($is_camtasia) {
                   12316:         $output .= $lt{'auto'}.'<br />'.
                   12317:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  12318:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12319:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12320:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12321:                    $lt{'no'}.'</label></span><br />'.
                   12322:                    '<div id="camtasia_titles" style="display:block">'.
                   12323:                    &Apache::lonhtmlcommon::start_pick_box().
                   12324:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12325:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12326:                    &Apache::lonhtmlcommon::row_closure().
                   12327:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12328:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12329:                    &Apache::lonhtmlcommon::row_closure(1).
                   12330:                    &Apache::lonhtmlcommon::end_pick_box().
                   12331:                    '</div>';
                   12332:     }
1.1065    raeburn  12333:     $output .= 
                   12334:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12335:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12336:         "\n";
1.1065    raeburn  12337:     if ($duplicates ne '') {
                   12338:         $output .= '<p><span class="LC_warning">'.
                   12339:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12340:                    &start_data_table().
                   12341:                    &start_data_table_header_row().
                   12342:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12343:                    '<th>'.&mt('Name').'</th>'.
                   12344:                    '<th>'.&mt('Type').'</th>'.
                   12345:                    '<th>'.&mt('Size').'</th>'.
                   12346:                    '<th>'.&mt('Last modified').'</th>'.
                   12347:                    &end_data_table_header_row().
                   12348:                    $duplicates.
                   12349:                    &end_data_table().
                   12350:                    '</p>';
                   12351:     }
1.1067    raeburn  12352:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12353:     if (ref($hiddenelements) eq 'HASH') {
                   12354:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12355:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12356:         }
                   12357:     }
                   12358:     $output .= <<"END";
1.1067    raeburn  12359: <br />
1.1053    raeburn  12360: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12361: </form>
                   12362: $noextract
                   12363: END
                   12364:     return $output;
                   12365: }
                   12366: 
1.1065    raeburn  12367: sub decompression_utility {
                   12368:     my ($program) = @_;
                   12369:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12370:     my $location;
                   12371:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12372:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12373:                          '/usr/sbin/') {
                   12374:             if (-x $dir.$program) {
                   12375:                 $location = $dir.$program;
                   12376:                 last;
                   12377:             }
                   12378:         }
                   12379:     }
                   12380:     return $location;
                   12381: }
                   12382: 
                   12383: sub list_archive_contents {
                   12384:     my ($file,$pathsref) = @_;
                   12385:     my (@cmd,$output);
                   12386:     my $needsregexp;
                   12387:     if ($file =~ /\.zip$/) {
                   12388:         @cmd = (&decompression_utility('unzip'),"-l");
                   12389:         $needsregexp = 1;
                   12390:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12391:              ($file =~ /\.tgz$/)) {
                   12392:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12393:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12394:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12395:     } elsif ($file =~ m|\.tar$|) {
                   12396:         @cmd = (&decompression_utility('tar'),"-tf");
                   12397:     }
                   12398:     if (@cmd) {
                   12399:         undef($!);
                   12400:         undef($@);
                   12401:         if (open(my $fh,"-|", @cmd, $file)) {
                   12402:             while (my $line = <$fh>) {
                   12403:                 $output .= $line;
                   12404:                 chomp($line);
                   12405:                 my $item;
                   12406:                 if ($needsregexp) {
                   12407:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12408:                 } else {
                   12409:                     $item = $line;
                   12410:                 }
                   12411:                 if ($item ne '') {
                   12412:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12413:                         push(@{$pathsref},$item);
                   12414:                     } 
                   12415:                 }
                   12416:             }
                   12417:             close($fh);
                   12418:         }
                   12419:     }
                   12420:     return $output;
                   12421: }
                   12422: 
1.1053    raeburn  12423: sub decompress_uploaded_file {
                   12424:     my ($file,$dir) = @_;
                   12425:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12426:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12427:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12428:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12429:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12430:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12431:     my $decompressed = $env{'cgi.decompressed'};
                   12432:     &Apache::lonnet::delenv('cgi.file');
                   12433:     &Apache::lonnet::delenv('cgi.dir');
                   12434:     &Apache::lonnet::delenv('cgi.decompressed');
                   12435:     return ($decompressed,$result);
                   12436: }
                   12437: 
1.1055    raeburn  12438: sub process_decompression {
                   12439:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1075.2.128  raeburn  12440:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12441:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12442:                &mt('Unexpected file path.').'</p>'."\n";
                   12443:     }
                   12444:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12445:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12446:                &mt('Unexpected course context.').'</p>'."\n";
                   12447:     }
                   12448:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
                   12449:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12450:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12451:     }
1.1055    raeburn  12452:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  12453:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  12454:         $error = &mt('Filename not a supported archive file type.').
                   12455:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12456:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12457:     } else {
                   12458:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12459:         if ($docuhome eq 'no_host') {
                   12460:             $error = &mt('Could not determine home server for course.');
                   12461:         } else {
                   12462:             my @ids=&Apache::lonnet::current_machine_ids();
                   12463:             my $currdir = "$dir_root/$destination";
                   12464:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12465:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12466:                        "$dir_root/$destination";
                   12467:             } else {
                   12468:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12469:                        "$dir_root/$docudom/$docuname/$destination";
                   12470:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12471:                     $error = &mt('Archive file not found.');
                   12472:                 }
                   12473:             }
1.1065    raeburn  12474:             my (@to_overwrite,@to_skip);
                   12475:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12476:                 my $total = $env{'form.archive_overwrite_total'};
                   12477:                 for (my $i=0; $i<$total; $i++) {
                   12478:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12479:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12480:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12481:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12482:                     }
                   12483:                 }
                   12484:             }
                   12485:             my $numskip = scalar(@to_skip);
1.1075.2.128  raeburn  12486:             my $numoverwrite = scalar(@to_overwrite);
                   12487:             if (($numskip) && (!$numoverwrite)) {
1.1065    raeburn  12488:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12489:             } elsif ($dir eq '') {
1.1055    raeburn  12490:                 $error = &mt('Directory containing archive file unavailable.');
                   12491:             } elsif (!$error) {
1.1065    raeburn  12492:                 my ($decompressed,$display);
1.1075.2.128  raeburn  12493:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12494:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12495:                     mkdir("$dir/$tempdir",0755);
1.1075.2.128  raeburn  12496:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   12497:                         ($decompressed,$display) =
                   12498:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   12499:                         foreach my $item (@to_skip) {
                   12500:                             if (($item ne '') && ($item !~ /\.\./)) {
                   12501:                                 if (-f "$dir/$tempdir/$item") {
                   12502:                                     unlink("$dir/$tempdir/$item");
                   12503:                                 } elsif (-d "$dir/$tempdir/$item") {
                   12504:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
                   12505:                                 }
                   12506:                             }
                   12507:                         }
                   12508:                         foreach my $item (@to_overwrite) {
                   12509:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   12510:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   12511:                                     if (-f "$dir/$item") {
                   12512:                                         unlink("$dir/$item");
                   12513:                                     } elsif (-d "$dir/$item") {
                   12514:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
                   12515:                                     }
                   12516:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   12517:                                 }
1.1065    raeburn  12518:                             }
                   12519:                         }
1.1075.2.128  raeburn  12520:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
                   12521:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
                   12522:                         }
1.1065    raeburn  12523:                     }
                   12524:                 } else {
                   12525:                     ($decompressed,$display) = 
                   12526:                         &decompress_uploaded_file($file,$dir);
                   12527:                 }
1.1055    raeburn  12528:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12529:                     $output = '<p class="LC_info">'.
                   12530:                               &mt('Files extracted successfully from archive.').
                   12531:                               '</p>'."\n";
1.1055    raeburn  12532:                     my ($warning,$result,@contents);
                   12533:                     my ($newdirlistref,$newlisterror) =
                   12534:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12535:                                                  $docuname,1);
                   12536:                     my (%is_dir,%changes,@newitems);
                   12537:                     my $dirptr = 16384;
1.1065    raeburn  12538:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12539:                         foreach my $dir_line (@{$newdirlistref}) {
                   12540:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1075.2.128  raeburn  12541:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
1.1055    raeburn  12542:                                 push(@newitems,$item);
                   12543:                                 if ($dirptr&$testdir) {
                   12544:                                     $is_dir{$item} = 1;
                   12545:                                 }
                   12546:                                 $changes{$item} = 1;
                   12547:                             }
                   12548:                         }
                   12549:                     }
                   12550:                     if (keys(%changes) > 0) {
                   12551:                         foreach my $item (sort(@newitems)) {
                   12552:                             if ($changes{$item}) {
                   12553:                                 push(@contents,$item);
                   12554:                             }
                   12555:                         }
                   12556:                     }
                   12557:                     if (@contents > 0) {
1.1067    raeburn  12558:                         my $wantform;
                   12559:                         unless ($env{'form.autoextract_camtasia'}) {
                   12560:                             $wantform = 1;
                   12561:                         }
1.1056    raeburn  12562:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12563:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12564:                                                                 $currdir,\%is_dir,
                   12565:                                                                 \%children,\%parent,
1.1056    raeburn  12566:                                                                 \@contents,\%dirorder,
                   12567:                                                                 \%titles,$wantform);
1.1055    raeburn  12568:                         if ($datatable ne '') {
                   12569:                             $output .= &archive_options_form('decompressed',$datatable,
                   12570:                                                              $count,$hiddenelem);
1.1065    raeburn  12571:                             my $startcount = 6;
1.1055    raeburn  12572:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12573:                                                            \%titles,\%children);
1.1055    raeburn  12574:                         }
1.1067    raeburn  12575:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  12576:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12577:                             my %displayed;
                   12578:                             my $total = 1;
                   12579:                             $env{'form.archive_directory'} = [];
                   12580:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12581:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12582:                                 $path =~ s{/$}{};
                   12583:                                 my $item;
                   12584:                                 if ($path ne '') {
                   12585:                                     $item = "$path/$titles{$i}";
                   12586:                                 } else {
                   12587:                                     $item = $titles{$i};
                   12588:                                 }
                   12589:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12590:                                 if ($item eq $contents[0]) {
                   12591:                                     push(@{$env{'form.archive_directory'}},$i);
                   12592:                                     $env{'form.archive_'.$i} = 'display';
                   12593:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12594:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  12595:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12596:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  12597:                                     $env{'form.archive_'.$i} = 'display';
                   12598:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12599:                                     $displayed{'web'} = $i;
                   12600:                                 } else {
1.1075.2.59  raeburn  12601:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12602:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12603:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12604:                                         push(@{$env{'form.archive_directory'}},$i);
                   12605:                                     }
                   12606:                                     $env{'form.archive_'.$i} = 'dependency';
                   12607:                                 }
                   12608:                                 $total ++;
                   12609:                             }
                   12610:                             for (my $i=1; $i<$total; $i++) {
                   12611:                                 next if ($i == $displayed{'web'});
                   12612:                                 next if ($i == $displayed{'folder'});
                   12613:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12614:                             }
                   12615:                             $env{'form.phase'} = 'decompress_cleanup';
                   12616:                             $env{'form.archivedelete'} = 1;
                   12617:                             $env{'form.archive_count'} = $total-1;
                   12618:                             $output .=
                   12619:                                 &process_extracted_files('coursedocs',$docudom,
                   12620:                                                          $docuname,$destination,
                   12621:                                                          $dir_root,$hiddenelem);
                   12622:                         }
1.1055    raeburn  12623:                     } else {
                   12624:                         $warning = &mt('No new items extracted from archive file.');
                   12625:                     }
                   12626:                 } else {
                   12627:                     $output = $display;
                   12628:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12629:                 }
                   12630:             }
                   12631:         }
                   12632:     }
                   12633:     if ($error) {
                   12634:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12635:                    $error.'</p>'."\n";
                   12636:     }
                   12637:     if ($warning) {
                   12638:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12639:     }
                   12640:     return $output;
                   12641: }
                   12642: 
                   12643: sub get_extracted {
1.1056    raeburn  12644:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12645:         $titles,$wantform) = @_;
1.1055    raeburn  12646:     my $count = 0;
                   12647:     my $depth = 0;
                   12648:     my $datatable;
1.1056    raeburn  12649:     my @hierarchy;
1.1055    raeburn  12650:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12651:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12652:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12653:     foreach my $item (@{$contents}) {
                   12654:         $count ++;
1.1056    raeburn  12655:         @{$dirorder->{$count}} = @hierarchy;
                   12656:         $titles->{$count} = $item;
1.1055    raeburn  12657:         &archive_hierarchy($depth,$count,$parent,$children);
                   12658:         if ($wantform) {
                   12659:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12660:                                        $currdir,$depth,$count);
                   12661:         }
                   12662:         if ($is_dir->{$item}) {
                   12663:             $depth ++;
1.1056    raeburn  12664:             push(@hierarchy,$count);
                   12665:             $parent->{$depth} = $count;
1.1055    raeburn  12666:             $datatable .=
                   12667:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12668:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12669:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12670:             $depth --;
1.1056    raeburn  12671:             pop(@hierarchy);
1.1055    raeburn  12672:         }
                   12673:     }
                   12674:     return ($count,$datatable);
                   12675: }
                   12676: 
                   12677: sub recurse_extracted_archive {
1.1056    raeburn  12678:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12679:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12680:     my $result='';
1.1056    raeburn  12681:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12682:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12683:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12684:         return $result;
                   12685:     }
                   12686:     my $dirptr = 16384;
                   12687:     my ($newdirlistref,$newlisterror) =
                   12688:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12689:     if (ref($newdirlistref) eq 'ARRAY') {
                   12690:         foreach my $dir_line (@{$newdirlistref}) {
                   12691:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12692:             unless ($item =~ /^\.+$/) {
                   12693:                 $$count ++;
1.1056    raeburn  12694:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12695:                 $titles->{$$count} = $item;
1.1055    raeburn  12696:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12697: 
1.1055    raeburn  12698:                 my $is_dir;
                   12699:                 if ($dirptr&$testdir) {
                   12700:                     $is_dir = 1;
                   12701:                 }
                   12702:                 if ($wantform) {
                   12703:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12704:                 }
                   12705:                 if ($is_dir) {
                   12706:                     $$depth ++;
1.1056    raeburn  12707:                     push(@{$hierarchy},$$count);
                   12708:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12709:                     $result .=
                   12710:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12711:                                                    $docuname,$depth,$count,
1.1056    raeburn  12712:                                                    $hierarchy,$dirorder,$children,
                   12713:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12714:                     $$depth --;
1.1056    raeburn  12715:                     pop(@{$hierarchy});
1.1055    raeburn  12716:                 }
                   12717:             }
                   12718:         }
                   12719:     }
                   12720:     return $result;
                   12721: }
                   12722: 
                   12723: sub archive_hierarchy {
                   12724:     my ($depth,$count,$parent,$children) =@_;
                   12725:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12726:         if (exists($parent->{$depth})) {
                   12727:              $children->{$parent->{$depth}} .= $count.':';
                   12728:         }
                   12729:     }
                   12730:     return;
                   12731: }
                   12732: 
                   12733: sub archive_row {
                   12734:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12735:     my ($name) = ($item =~ m{([^/]+)$});
                   12736:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12737:                                        'display'    => 'Add as file',
1.1055    raeburn  12738:                                        'dependency' => 'Include as dependency',
                   12739:                                        'discard'    => 'Discard',
                   12740:                                       );
                   12741:     if ($is_dir) {
1.1059    raeburn  12742:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12743:     }
1.1056    raeburn  12744:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12745:     my $offset = 0;
1.1055    raeburn  12746:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12747:         $offset ++;
1.1065    raeburn  12748:         if ($action ne 'display') {
                   12749:             $offset ++;
                   12750:         }  
1.1055    raeburn  12751:         $output .= '<td><span class="LC_nobreak">'.
                   12752:                    '<label><input type="radio" name="archive_'.$count.
                   12753:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12754:         my $text = $choices{$action};
                   12755:         if ($is_dir) {
                   12756:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12757:             if ($action eq 'display') {
1.1059    raeburn  12758:                 $text = &mt('Add as folder');
1.1055    raeburn  12759:             }
1.1056    raeburn  12760:         } else {
                   12761:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12762: 
                   12763:         }
                   12764:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12765:         if ($action eq 'dependency') {
                   12766:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12767:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12768:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12769:                        '<option value=""></option>'."\n".
                   12770:                        '</select>'."\n".
                   12771:                        '</div>';
1.1059    raeburn  12772:         } elsif ($action eq 'display') {
                   12773:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12774:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12775:                        '</div>';
1.1055    raeburn  12776:         }
1.1056    raeburn  12777:         $output .= '</td>';
1.1055    raeburn  12778:     }
                   12779:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12780:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12781:     for (my $i=0; $i<$depth; $i++) {
                   12782:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12783:     }
                   12784:     if ($is_dir) {
                   12785:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12786:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12787:     } else {
                   12788:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12789:     }
                   12790:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12791:                &end_data_table_row();
                   12792:     return $output;
                   12793: }
                   12794: 
                   12795: sub archive_options_form {
1.1065    raeburn  12796:     my ($form,$display,$count,$hiddenelem) = @_;
                   12797:     my %lt = &Apache::lonlocal::texthash(
                   12798:                perm => 'Permanently remove archive file?',
                   12799:                hows => 'How should each extracted item be incorporated in the course?',
                   12800:                cont => 'Content actions for all',
                   12801:                addf => 'Add as folder/file',
                   12802:                incd => 'Include as dependency for a displayed file',
                   12803:                disc => 'Discard',
                   12804:                no   => 'No',
                   12805:                yes  => 'Yes',
                   12806:                save => 'Save',
                   12807:     );
                   12808:     my $output = <<"END";
                   12809: <form name="$form" method="post" action="">
                   12810: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12811: <label>
                   12812:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12813: </label>
                   12814: &nbsp;
                   12815: <label>
                   12816:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12817: </span>
                   12818: </p>
                   12819: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12820: <br />$lt{'hows'}
                   12821: <div class="LC_columnSection">
                   12822:   <fieldset>
                   12823:     <legend>$lt{'cont'}</legend>
                   12824:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12825:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12826:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12827:   </fieldset>
                   12828: </div>
                   12829: END
                   12830:     return $output.
1.1055    raeburn  12831:            &start_data_table()."\n".
1.1065    raeburn  12832:            $display."\n".
1.1055    raeburn  12833:            &end_data_table()."\n".
                   12834:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12835:            $hiddenelem.
1.1065    raeburn  12836:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12837:            '</form>';
                   12838: }
                   12839: 
                   12840: sub archive_javascript {
1.1056    raeburn  12841:     my ($startcount,$numitems,$titles,$children) = @_;
                   12842:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12843:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12844:     my $scripttag = <<START;
                   12845: <script type="text/javascript">
                   12846: // <![CDATA[
                   12847: 
                   12848: function checkAll(form,prefix) {
                   12849:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12850:     for (var i=0; i < form.elements.length; i++) {
                   12851:         var id = form.elements[i].id;
                   12852:         if ((id != '') && (id != undefined)) {
                   12853:             if (idstr.test(id)) {
                   12854:                 if (form.elements[i].type == 'radio') {
                   12855:                     form.elements[i].checked = true;
1.1056    raeburn  12856:                     var nostart = i-$startcount;
1.1059    raeburn  12857:                     var offset = nostart%7;
                   12858:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12859:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12860:                 }
                   12861:             }
                   12862:         }
                   12863:     }
                   12864: }
                   12865: 
                   12866: function propagateCheck(form,count) {
                   12867:     if (count > 0) {
1.1059    raeburn  12868:         var startelement = $startcount + ((count-1) * 7);
                   12869:         for (var j=1; j<6; j++) {
                   12870:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12871:                 var item = startelement + j; 
                   12872:                 if (form.elements[item].type == 'radio') {
                   12873:                     if (form.elements[item].checked) {
                   12874:                         containerCheck(form,count,j);
                   12875:                         break;
                   12876:                     }
1.1055    raeburn  12877:                 }
                   12878:             }
                   12879:         }
                   12880:     }
                   12881: }
                   12882: 
                   12883: numitems = $numitems
1.1056    raeburn  12884: var titles = new Array(numitems);
                   12885: var parents = new Array(numitems);
1.1055    raeburn  12886: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12887:     parents[i] = new Array;
1.1055    raeburn  12888: }
1.1059    raeburn  12889: var maintitle = '$maintitle';
1.1055    raeburn  12890: 
                   12891: START
                   12892: 
1.1056    raeburn  12893:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12894:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12895:         for (my $i=0; $i<@contents; $i ++) {
                   12896:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12897:         }
                   12898:     }
                   12899: 
1.1056    raeburn  12900:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12901:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12902:     }
                   12903: 
1.1055    raeburn  12904:     $scripttag .= <<END;
                   12905: 
                   12906: function containerCheck(form,count,offset) {
                   12907:     if (count > 0) {
1.1056    raeburn  12908:         dependencyCheck(form,count,offset);
1.1059    raeburn  12909:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12910:         form.elements[item].checked = true;
                   12911:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12912:             if (parents[count].length > 0) {
                   12913:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12914:                     containerCheck(form,parents[count][j],offset);
                   12915:                 }
                   12916:             }
                   12917:         }
                   12918:     }
                   12919: }
                   12920: 
                   12921: function dependencyCheck(form,count,offset) {
                   12922:     if (count > 0) {
1.1059    raeburn  12923:         var chosen = (offset+$startcount)+7*(count-1);
                   12924:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12925:         var currtype = form.elements[depitem].type;
                   12926:         if (form.elements[chosen].value == 'dependency') {
                   12927:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12928:             form.elements[depitem].options.length = 0;
                   12929:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  12930:             for (var i=1; i<=numitems; i++) {
                   12931:                 if (i == count) {
                   12932:                     continue;
                   12933:                 }
1.1059    raeburn  12934:                 var startelement = $startcount + (i-1) * 7;
                   12935:                 for (var j=1; j<6; j++) {
                   12936:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12937:                         var item = startelement + j;
                   12938:                         if (form.elements[item].type == 'radio') {
                   12939:                             if (form.elements[item].checked) {
                   12940:                                 if (form.elements[item].value == 'display') {
                   12941:                                     var n = form.elements[depitem].options.length;
                   12942:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12943:                                 }
                   12944:                             }
                   12945:                         }
                   12946:                     }
                   12947:                 }
                   12948:             }
                   12949:         } else {
                   12950:             document.getElementById('arc_depon_'+count).style.display='none';
                   12951:             form.elements[depitem].options.length = 0;
                   12952:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12953:         }
1.1059    raeburn  12954:         titleCheck(form,count,offset);
1.1056    raeburn  12955:     }
                   12956: }
                   12957: 
                   12958: function propagateSelect(form,count,offset) {
                   12959:     if (count > 0) {
1.1065    raeburn  12960:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12961:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12962:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12963:             if (parents[count].length > 0) {
                   12964:                 for (var j=0; j<parents[count].length; j++) {
                   12965:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12966:                 }
                   12967:             }
                   12968:         }
                   12969:     }
                   12970: }
1.1056    raeburn  12971: 
                   12972: function containerSelect(form,count,offset,picked) {
                   12973:     if (count > 0) {
1.1065    raeburn  12974:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12975:         if (form.elements[item].type == 'radio') {
                   12976:             if (form.elements[item].value == 'dependency') {
                   12977:                 if (form.elements[item+1].type == 'select-one') {
                   12978:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12979:                         if (form.elements[item+1].options[i].value == picked) {
                   12980:                             form.elements[item+1].selectedIndex = i;
                   12981:                             break;
                   12982:                         }
                   12983:                     }
                   12984:                 }
                   12985:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12986:                     if (parents[count].length > 0) {
                   12987:                         for (var j=0; j<parents[count].length; j++) {
                   12988:                             containerSelect(form,parents[count][j],offset,picked);
                   12989:                         }
                   12990:                     }
                   12991:                 }
                   12992:             }
                   12993:         }
                   12994:     }
                   12995: }
                   12996: 
1.1059    raeburn  12997: function titleCheck(form,count,offset) {
                   12998:     if (count > 0) {
                   12999:         var chosen = (offset+$startcount)+7*(count-1);
                   13000:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13001:         var currtype = form.elements[depitem].type;
                   13002:         if (form.elements[chosen].value == 'display') {
                   13003:             document.getElementById('arc_title_'+count).style.display='block';
                   13004:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13005:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13006:             }
                   13007:         } else {
                   13008:             document.getElementById('arc_title_'+count).style.display='none';
                   13009:             if (currtype == 'text') { 
                   13010:                 document.getElementById('archive_title_'+count).value='';
                   13011:             }
                   13012:         }
                   13013:     }
                   13014:     return;
                   13015: }
                   13016: 
1.1055    raeburn  13017: // ]]>
                   13018: </script>
                   13019: END
                   13020:     return $scripttag;
                   13021: }
                   13022: 
                   13023: sub process_extracted_files {
1.1067    raeburn  13024:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13025:     my $numitems = $env{'form.archive_count'};
1.1075.2.128  raeburn  13026:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  13027:     my @ids=&Apache::lonnet::current_machine_ids();
                   13028:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13029:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13030:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13031:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13032:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13033:         $pathtocheck = "$dir_root/$destination";
                   13034:         $dir = $dir_root;
                   13035:         $ishome = 1;
                   13036:     } else {
                   13037:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13038:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1075.2.128  raeburn  13039:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  13040:     }
                   13041:     my $currdir = "$dir_root/$destination";
                   13042:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13043:     if ($env{'form.folderpath'}) {
                   13044:         my @items = split('&',$env{'form.folderpath'});
                   13045:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  13046:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13047:             $containers{'0'}='page';
                   13048:         } else {
                   13049:             $containers{'0'}='sequence';
                   13050:         }
1.1055    raeburn  13051:     }
                   13052:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13053:     if ($numitems) {
                   13054:         for (my $i=1; $i<=$numitems; $i++) {
                   13055:             my $path = $env{'form.archive_content_'.$i};
                   13056:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13057:                 my $item = $1;
                   13058:                 $toplevelitems{$item} = $i;
                   13059:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13060:                     $is_dir{$item} = 1;
                   13061:                 }
                   13062:             }
                   13063:         }
                   13064:     }
1.1067    raeburn  13065:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13066:     if (keys(%toplevelitems) > 0) {
                   13067:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13068:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13069:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13070:     }
1.1066    raeburn  13071:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13072:     if ($numitems) {
                   13073:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  13074:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13075:             my $path = $env{'form.archive_content_'.$i};
                   13076:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13077:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13078:                     if ($prefix ne '' && $path ne '') {
                   13079:                         if (-e $prefix.$path) {
1.1066    raeburn  13080:                             if ((@archdirs > 0) && 
                   13081:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13082:                                 $todeletedir{$prefix.$path} = 1;
                   13083:                             } else {
                   13084:                                 $todelete{$prefix.$path} = 1;
                   13085:                             }
1.1055    raeburn  13086:                         }
                   13087:                     }
                   13088:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13089:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13090:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13091:                     $docstitle = $env{'form.archive_title_'.$i};
                   13092:                     if ($docstitle eq '') {
                   13093:                         $docstitle = $title;
                   13094:                     }
1.1055    raeburn  13095:                     $outer = 0;
1.1056    raeburn  13096:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13097:                         if (@{$dirorder{$i}} > 0) {
                   13098:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13099:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13100:                                     $outer = $item;
                   13101:                                     last;
                   13102:                                 }
                   13103:                             }
                   13104:                         }
                   13105:                     }
                   13106:                     my ($errtext,$fatal) = 
                   13107:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13108:                                                '/'.$folders{$outer}.'.'.
                   13109:                                                $containers{$outer});
                   13110:                     next if ($fatal);
                   13111:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13112:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13113:                             $mapinner{$i} = time;
1.1055    raeburn  13114:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13115:                             $containers{$i} = 'sequence';
                   13116:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13117:                                       $folders{$i}.'.'.$containers{$i};
                   13118:                             my $newidx = &LONCAPA::map::getresidx();
                   13119:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13120:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13121:                             push(@LONCAPA::map::order,$newidx);
                   13122:                             my ($outtext,$errtext) =
                   13123:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13124:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  13125:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13126:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13127:                             unless ($errtext) {
1.1075.2.128  raeburn  13128:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13129:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
                   13130:                                             '</li>'."\n";
1.1067    raeburn  13131:                             }
1.1055    raeburn  13132:                         }
                   13133:                     } else {
                   13134:                         if ($context eq 'coursedocs') {
                   13135:                             my $newidx=&LONCAPA::map::getresidx();
                   13136:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13137:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13138:                                       $title;
1.1075.2.128  raeburn  13139:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   13140:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13141:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
1.1067    raeburn  13142:                                 }
1.1075.2.128  raeburn  13143:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13144:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13145:                                 }
                   13146:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13147:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   13148:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   13149:                                         unless ($ishome) {
                   13150:                                             my $fetch = "$newdest{$i}/$title";
                   13151:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   13152:                                             $prompttofetch{$fetch} = 1;
                   13153:                                         }
                   13154:                                    }
                   13155:                                 }
                   13156:                                 $LONCAPA::map::resources[$newidx]=
                   13157:                                     $docstitle.':'.$url.':false:normal:res';
                   13158:                                 push(@LONCAPA::map::order, $newidx);
                   13159:                                 my ($outtext,$errtext)=
                   13160:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13161:                                                             $docuname.'/'.$folders{$outer}.
                   13162:                                                             '.'.$containers{$outer},1,1);
                   13163:                                 unless ($errtext) {
                   13164:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13165:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   13166:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   13167:                                                    '</li>'."\n";
                   13168:                                     }
1.1067    raeburn  13169:                                 }
1.1075.2.128  raeburn  13170:                             } else {
                   13171:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13172:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1067    raeburn  13173:                             }
1.1055    raeburn  13174:                         }
                   13175:                     }
1.1075.2.11  raeburn  13176:                 }
                   13177:             } else {
1.1075.2.128  raeburn  13178:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13179:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1075.2.11  raeburn  13180:             }
                   13181:         }
                   13182:         for (my $i=1; $i<=$numitems; $i++) {
                   13183:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13184:             my $path = $env{'form.archive_content_'.$i};
                   13185:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13186:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13187:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13188:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13189:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13190:                         my ($itemidx,$fullpath,$relpath);
                   13191:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13192:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13193:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  13194:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13195:                                     $itemidx = $j;
1.1056    raeburn  13196:                                 }
                   13197:                             }
1.1075.2.11  raeburn  13198:                         }
                   13199:                         if ($itemidx eq '') {
                   13200:                             $itemidx =  0;
                   13201:                         }
                   13202:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13203:                             if ($mapinner{$referrer{$i}}) {
                   13204:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13205:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13206:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13207:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13208:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13209:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13210:                                             if (!-e $fullpath) {
                   13211:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13212:                                             }
                   13213:                                         }
1.1075.2.11  raeburn  13214:                                     } else {
                   13215:                                         last;
1.1056    raeburn  13216:                                     }
1.1075.2.11  raeburn  13217:                                 }
                   13218:                             }
                   13219:                         } elsif ($newdest{$referrer{$i}}) {
                   13220:                             $fullpath = $newdest{$referrer{$i}};
                   13221:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13222:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13223:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13224:                                     last;
                   13225:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13226:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13227:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13228:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13229:                                         if (!-e $fullpath) {
                   13230:                                             mkdir($fullpath,0755);
1.1056    raeburn  13231:                                         }
                   13232:                                     }
1.1075.2.11  raeburn  13233:                                 } else {
                   13234:                                     last;
1.1056    raeburn  13235:                                 }
1.1075.2.11  raeburn  13236:                             }
                   13237:                         }
                   13238:                         if ($fullpath ne '') {
                   13239:                             if (-e "$prefix$path") {
1.1075.2.128  raeburn  13240:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13241:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13242:                                 }
1.1075.2.11  raeburn  13243:                             }
                   13244:                             if (-e "$fullpath/$title") {
                   13245:                                 my $showpath;
                   13246:                                 if ($relpath ne '') {
                   13247:                                     $showpath = "$relpath/$title";
                   13248:                                 } else {
                   13249:                                     $showpath = "/$title";
1.1056    raeburn  13250:                                 }
1.1075.2.128  raeburn  13251:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13252:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13253:                                            '</li>'."\n";
                   13254:                                 unless ($ishome) {
                   13255:                                     my $fetch = "$fullpath/$title";
                   13256:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13257:                                     $prompttofetch{$fetch} = 1;
                   13258:                                 }
1.1055    raeburn  13259:                             }
                   13260:                         }
                   13261:                     }
1.1075.2.11  raeburn  13262:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13263:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1075.2.128  raeburn  13264:                                     &HTML::Entities::encode($path,'<>&"'),
                   13265:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13266:                                 '<br />';
1.1055    raeburn  13267:                 }
                   13268:             } else {
1.1075.2.128  raeburn  13269:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13270:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13271:             }
                   13272:         }
                   13273:         if (keys(%todelete)) {
                   13274:             foreach my $key (keys(%todelete)) {
                   13275:                 unlink($key);
1.1066    raeburn  13276:             }
                   13277:         }
                   13278:         if (keys(%todeletedir)) {
                   13279:             foreach my $key (keys(%todeletedir)) {
                   13280:                 rmdir($key);
                   13281:             }
                   13282:         }
                   13283:         foreach my $dir (sort(keys(%is_dir))) {
                   13284:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13285:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13286:             }
                   13287:         }
1.1067    raeburn  13288:         if ($result ne '') {
                   13289:             $output .= '<ul>'."\n".
                   13290:                        $result."\n".
                   13291:                        '</ul>';
                   13292:         }
                   13293:         unless ($ishome) {
                   13294:             my $replicationfail;
                   13295:             foreach my $item (keys(%prompttofetch)) {
                   13296:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13297:                 unless ($fetchresult eq 'ok') {
                   13298:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13299:                 }
                   13300:             }
                   13301:             if ($replicationfail) {
                   13302:                 $output .= '<p class="LC_error">'.
                   13303:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13304:                            $replicationfail.
                   13305:                            '</ul></p>';
                   13306:             }
                   13307:         }
1.1055    raeburn  13308:     } else {
                   13309:         $warning = &mt('No items found in archive.');
                   13310:     }
                   13311:     if ($error) {
                   13312:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13313:                    $error.'</p>'."\n";
                   13314:     }
                   13315:     if ($warning) {
                   13316:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13317:     }
                   13318:     return $output;
                   13319: }
                   13320: 
1.1066    raeburn  13321: sub cleanup_empty_dirs {
                   13322:     my ($path) = @_;
                   13323:     if (($path ne '') && (-d $path)) {
                   13324:         if (opendir(my $dirh,$path)) {
                   13325:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13326:             my $numitems = 0;
                   13327:             foreach my $item (@dircontents) {
                   13328:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  13329:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13330:                     if (-e "$path/$item") {
                   13331:                         $numitems ++;
                   13332:                     }
                   13333:                 } else {
                   13334:                     $numitems ++;
                   13335:                 }
                   13336:             }
                   13337:             if ($numitems == 0) {
                   13338:                 rmdir($path);
                   13339:             }
                   13340:             closedir($dirh);
                   13341:         }
                   13342:     }
                   13343:     return;
                   13344: }
                   13345: 
1.41      ng       13346: =pod
1.45      matthew  13347: 
1.1075.2.56  raeburn  13348: =item * &get_folder_hierarchy()
1.1068    raeburn  13349: 
                   13350: Provides hierarchy of names of folders/sub-folders containing the current
                   13351: item,
                   13352: 
                   13353: Inputs: 3
                   13354:      - $navmap - navmaps object
                   13355: 
                   13356:      - $map - url for map (either the trigger itself, or map containing
                   13357:                            the resource, which is the trigger).
                   13358: 
                   13359:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13360: 
                   13361: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13362: 
                   13363: =cut
                   13364: 
                   13365: sub get_folder_hierarchy {
                   13366:     my ($navmap,$map,$showitem) = @_;
                   13367:     my @pathitems;
                   13368:     if (ref($navmap)) {
                   13369:         my $mapres = $navmap->getResourceByUrl($map);
                   13370:         if (ref($mapres)) {
                   13371:             my $pcslist = $mapres->map_hierarchy();
                   13372:             if ($pcslist ne '') {
                   13373:                 my @pcs = split(/,/,$pcslist);
                   13374:                 foreach my $pc (@pcs) {
                   13375:                     if ($pc == 1) {
1.1075.2.38  raeburn  13376:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13377:                     } else {
                   13378:                         my $res = $navmap->getByMapPc($pc);
                   13379:                         if (ref($res)) {
                   13380:                             my $title = $res->compTitle();
                   13381:                             $title =~ s/\W+/_/g;
                   13382:                             if ($title ne '') {
                   13383:                                 push(@pathitems,$title);
                   13384:                             }
                   13385:                         }
                   13386:                     }
                   13387:                 }
                   13388:             }
1.1071    raeburn  13389:             if ($showitem) {
                   13390:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  13391:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13392:                 } else {
                   13393:                     my $maptitle = $mapres->compTitle();
                   13394:                     $maptitle =~ s/\W+/_/g;
                   13395:                     if ($maptitle ne '') {
                   13396:                         push(@pathitems,$maptitle);
                   13397:                     }
1.1068    raeburn  13398:                 }
                   13399:             }
                   13400:         }
                   13401:     }
                   13402:     return @pathitems;
                   13403: }
                   13404: 
                   13405: =pod
                   13406: 
1.1015    raeburn  13407: =item * &get_turnedin_filepath()
                   13408: 
                   13409: Determines path in a user's portfolio file for storage of files uploaded
                   13410: to a specific essayresponse or dropbox item.
                   13411: 
                   13412: Inputs: 3 required + 1 optional.
                   13413: $symb is symb for resource, $uname and $udom are for current user (required).
                   13414: $caller is optional (can be "submission", if routine is called when storing
                   13415: an upoaded file when "Submit Answer" button was pressed).
                   13416: 
                   13417: Returns array containing $path and $multiresp. 
                   13418: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13419: than one file upload item.  Callers of routine should append partid as a 
                   13420: subdirectory to $path in cases where $multiresp is 1.
                   13421: 
                   13422: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13423: 
                   13424: =cut
                   13425: 
                   13426: sub get_turnedin_filepath {
                   13427:     my ($symb,$uname,$udom,$caller) = @_;
                   13428:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13429:     my $turnindir;
                   13430:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13431:     $turnindir = $userhash{'turnindir'};
                   13432:     my ($path,$multiresp);
                   13433:     if ($turnindir eq '') {
                   13434:         if ($caller eq 'submission') {
                   13435:             $turnindir = &mt('turned in');
                   13436:             $turnindir =~ s/\W+/_/g;
                   13437:             my %newhash = (
                   13438:                             'turnindir' => $turnindir,
                   13439:                           );
                   13440:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13441:         }
                   13442:     }
                   13443:     if ($turnindir ne '') {
                   13444:         $path = '/'.$turnindir.'/';
                   13445:         my ($multipart,$turnin,@pathitems);
                   13446:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13447:         if (defined($navmap)) {
                   13448:             my $mapres = $navmap->getResourceByUrl($map);
                   13449:             if (ref($mapres)) {
                   13450:                 my $pcslist = $mapres->map_hierarchy();
                   13451:                 if ($pcslist ne '') {
                   13452:                     foreach my $pc (split(/,/,$pcslist)) {
                   13453:                         my $res = $navmap->getByMapPc($pc);
                   13454:                         if (ref($res)) {
                   13455:                             my $title = $res->compTitle();
                   13456:                             $title =~ s/\W+/_/g;
                   13457:                             if ($title ne '') {
1.1075.2.48  raeburn  13458:                                 if (($pc > 1) && (length($title) > 12)) {
                   13459:                                     $title = substr($title,0,12);
                   13460:                                 }
1.1015    raeburn  13461:                                 push(@pathitems,$title);
                   13462:                             }
                   13463:                         }
                   13464:                     }
                   13465:                 }
                   13466:                 my $maptitle = $mapres->compTitle();
                   13467:                 $maptitle =~ s/\W+/_/g;
                   13468:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  13469:                     if (length($maptitle) > 12) {
                   13470:                         $maptitle = substr($maptitle,0,12);
                   13471:                     }
1.1015    raeburn  13472:                     push(@pathitems,$maptitle);
                   13473:                 }
                   13474:                 unless ($env{'request.state'} eq 'construct') {
                   13475:                     my $res = $navmap->getBySymb($symb);
                   13476:                     if (ref($res)) {
                   13477:                         my $partlist = $res->parts();
                   13478:                         my $totaluploads = 0;
                   13479:                         if (ref($partlist) eq 'ARRAY') {
                   13480:                             foreach my $part (@{$partlist}) {
                   13481:                                 my @types = $res->responseType($part);
                   13482:                                 my @ids = $res->responseIds($part);
                   13483:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13484:                                     if ($types[$i] eq 'essay') {
                   13485:                                         my $partid = $part.'_'.$ids[$i];
                   13486:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13487:                                             $totaluploads ++;
                   13488:                                         }
                   13489:                                     }
                   13490:                                 }
                   13491:                             }
                   13492:                             if ($totaluploads > 1) {
                   13493:                                 $multiresp = 1;
                   13494:                             }
                   13495:                         }
                   13496:                     }
                   13497:                 }
                   13498:             } else {
                   13499:                 return;
                   13500:             }
                   13501:         } else {
                   13502:             return;
                   13503:         }
                   13504:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13505:         $restitle =~ s/\W+/_/g;
                   13506:         if ($restitle eq '') {
                   13507:             $restitle = ($resurl =~ m{/[^/]+$});
                   13508:             if ($restitle eq '') {
                   13509:                 $restitle = time;
                   13510:             }
                   13511:         }
1.1075.2.48  raeburn  13512:         if (length($restitle) > 12) {
                   13513:             $restitle = substr($restitle,0,12);
                   13514:         }
1.1015    raeburn  13515:         push(@pathitems,$restitle);
                   13516:         $path .= join('/',@pathitems);
                   13517:     }
                   13518:     return ($path,$multiresp);
                   13519: }
                   13520: 
                   13521: =pod
                   13522: 
1.464     albertel 13523: =back
1.41      ng       13524: 
1.112     bowersj2 13525: =head1 CSV Upload/Handling functions
1.38      albertel 13526: 
1.41      ng       13527: =over 4
                   13528: 
1.648     raeburn  13529: =item * &upfile_store($r)
1.41      ng       13530: 
                   13531: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13532: needs $env{'form.upfile'}
1.41      ng       13533: returns $datatoken to be put into hidden field
                   13534: 
                   13535: =cut
1.31      albertel 13536: 
                   13537: sub upfile_store {
                   13538:     my $r=shift;
1.258     albertel 13539:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13540:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13541:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13542:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13543: 
1.1075.2.128  raeburn  13544:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   13545:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   13546:                                      time.'_'.$$);
                   13547:     return if ($datatoken eq '');
                   13548: 
1.31      albertel 13549:     {
1.158     raeburn  13550:         my $datafile = $r->dir_config('lonDaemons').
                   13551:                            '/tmp/'.$datatoken.'.tmp';
1.1075.2.128  raeburn  13552:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 13553:             print $fh $env{'form.upfile'};
1.158     raeburn  13554:             close($fh);
                   13555:         }
1.31      albertel 13556:     }
                   13557:     return $datatoken;
                   13558: }
                   13559: 
1.56      matthew  13560: =pod
                   13561: 
1.1075.2.128  raeburn  13562: =item * &load_tmp_file($r,$datatoken)
1.41      ng       13563: 
                   13564: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1075.2.128  raeburn  13565: $datatoken is the name to assign to the temporary file.
1.258     albertel 13566: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13567: 
                   13568: =cut
1.31      albertel 13569: 
                   13570: sub load_tmp_file {
1.1075.2.128  raeburn  13571:     my ($r,$datatoken) = @_;
                   13572:     return if ($datatoken eq '');
1.31      albertel 13573:     my @studentdata=();
                   13574:     {
1.158     raeburn  13575:         my $studentfile = $r->dir_config('lonDaemons').
1.1075.2.128  raeburn  13576:                               '/tmp/'.$datatoken.'.tmp';
                   13577:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  13578:             @studentdata=<$fh>;
                   13579:             close($fh);
                   13580:         }
1.31      albertel 13581:     }
1.258     albertel 13582:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13583: }
                   13584: 
1.1075.2.128  raeburn  13585: sub valid_datatoken {
                   13586:     my ($datatoken) = @_;
1.1075.2.131  raeburn  13587:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1075.2.128  raeburn  13588:         return $datatoken;
                   13589:     }
                   13590:     return;
                   13591: }
                   13592: 
1.56      matthew  13593: =pod
                   13594: 
1.648     raeburn  13595: =item * &upfile_record_sep()
1.41      ng       13596: 
                   13597: Separate uploaded file into records
                   13598: returns array of records,
1.258     albertel 13599: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13600: 
                   13601: =cut
1.31      albertel 13602: 
                   13603: sub upfile_record_sep {
1.258     albertel 13604:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13605:     } else {
1.248     albertel 13606: 	my @records;
1.258     albertel 13607: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13608: 	    if ($line=~/^\s*$/) { next; }
                   13609: 	    push(@records,$line);
                   13610: 	}
                   13611: 	return @records;
1.31      albertel 13612:     }
                   13613: }
                   13614: 
1.56      matthew  13615: =pod
                   13616: 
1.648     raeburn  13617: =item * &record_sep($record)
1.41      ng       13618: 
1.258     albertel 13619: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13620: 
                   13621: =cut
                   13622: 
1.263     www      13623: sub takeleft {
                   13624:     my $index=shift;
                   13625:     return substr('0000'.$index,-4,4);
                   13626: }
                   13627: 
1.31      albertel 13628: sub record_sep {
                   13629:     my $record=shift;
                   13630:     my %components=();
1.258     albertel 13631:     if ($env{'form.upfiletype'} eq 'xml') {
                   13632:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13633:         my $i=0;
1.356     albertel 13634:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13635:             $field=~s/^(\"|\')//;
                   13636:             $field=~s/(\"|\')$//;
1.263     www      13637:             $components{&takeleft($i)}=$field;
1.31      albertel 13638:             $i++;
                   13639:         }
1.258     albertel 13640:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13641:         my $i=0;
1.356     albertel 13642:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13643:             $field=~s/^(\"|\')//;
                   13644:             $field=~s/(\"|\')$//;
1.263     www      13645:             $components{&takeleft($i)}=$field;
1.31      albertel 13646:             $i++;
                   13647:         }
                   13648:     } else {
1.561     www      13649:         my $separator=',';
1.480     banghart 13650:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13651:             $separator=';';
1.480     banghart 13652:         }
1.31      albertel 13653:         my $i=0;
1.561     www      13654: # the character we are looking for to indicate the end of a quote or a record 
                   13655:         my $looking_for=$separator;
                   13656: # do not add the characters to the fields
                   13657:         my $ignore=0;
                   13658: # we just encountered a separator (or the beginning of the record)
                   13659:         my $just_found_separator=1;
                   13660: # store the field we are working on here
                   13661:         my $field='';
                   13662: # work our way through all characters in record
                   13663:         foreach my $character ($record=~/(.)/g) {
                   13664:             if ($character eq $looking_for) {
                   13665:                if ($character ne $separator) {
                   13666: # Found the end of a quote, again looking for separator
                   13667:                   $looking_for=$separator;
                   13668:                   $ignore=1;
                   13669:                } else {
                   13670: # Found a separator, store away what we got
                   13671:                   $components{&takeleft($i)}=$field;
                   13672: 	          $i++;
                   13673:                   $just_found_separator=1;
                   13674:                   $ignore=0;
                   13675:                   $field='';
                   13676:                }
                   13677:                next;
                   13678:             }
                   13679: # single or double quotation marks after a separator indicate beginning of a quote
                   13680: # we are now looking for the end of the quote and need to ignore separators
                   13681:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13682:                $looking_for=$character;
                   13683:                next;
                   13684:             }
                   13685: # ignore would be true after we reached the end of a quote
                   13686:             if ($ignore) { next; }
                   13687:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13688:             $field.=$character;
                   13689:             $just_found_separator=0; 
1.31      albertel 13690:         }
1.561     www      13691: # catch the very last entry, since we never encountered the separator
                   13692:         $components{&takeleft($i)}=$field;
1.31      albertel 13693:     }
                   13694:     return %components;
                   13695: }
                   13696: 
1.144     matthew  13697: ######################################################
                   13698: ######################################################
                   13699: 
1.56      matthew  13700: =pod
                   13701: 
1.648     raeburn  13702: =item * &upfile_select_html()
1.41      ng       13703: 
1.144     matthew  13704: Return HTML code to select a file from the users machine and specify 
                   13705: the file type.
1.41      ng       13706: 
                   13707: =cut
                   13708: 
1.144     matthew  13709: ######################################################
                   13710: ######################################################
1.31      albertel 13711: sub upfile_select_html {
1.144     matthew  13712:     my %Types = (
                   13713:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13714:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13715:                  space => &mt('Space separated'),
                   13716:                  tab   => &mt('Tabulator separated'),
                   13717: #                 xml   => &mt('HTML/XML'),
                   13718:                  );
                   13719:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13720:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13721:     foreach my $type (sort(keys(%Types))) {
                   13722:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13723:     }
                   13724:     $Str .= "</select>\n";
                   13725:     return $Str;
1.31      albertel 13726: }
                   13727: 
1.301     albertel 13728: sub get_samples {
                   13729:     my ($records,$toget) = @_;
                   13730:     my @samples=({});
                   13731:     my $got=0;
                   13732:     foreach my $rec (@$records) {
                   13733: 	my %temp = &record_sep($rec);
                   13734: 	if (! grep(/\S/, values(%temp))) { next; }
                   13735: 	if (%temp) {
                   13736: 	    $samples[$got]=\%temp;
                   13737: 	    $got++;
                   13738: 	    if ($got == $toget) { last; }
                   13739: 	}
                   13740:     }
                   13741:     return \@samples;
                   13742: }
                   13743: 
1.144     matthew  13744: ######################################################
                   13745: ######################################################
                   13746: 
1.56      matthew  13747: =pod
                   13748: 
1.648     raeburn  13749: =item * &csv_print_samples($r,$records)
1.41      ng       13750: 
                   13751: Prints a table of sample values from each column uploaded $r is an
                   13752: Apache Request ref, $records is an arrayref from
                   13753: &Apache::loncommon::upfile_record_sep
                   13754: 
                   13755: =cut
                   13756: 
1.144     matthew  13757: ######################################################
                   13758: ######################################################
1.31      albertel 13759: sub csv_print_samples {
                   13760:     my ($r,$records) = @_;
1.662     bisitz   13761:     my $samples = &get_samples($records,5);
1.301     albertel 13762: 
1.594     raeburn  13763:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13764:               &start_data_table_header_row());
1.356     albertel 13765:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13766:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13767:     $r->print(&end_data_table_header_row());
1.301     albertel 13768:     foreach my $hash (@$samples) {
1.594     raeburn  13769: 	$r->print(&start_data_table_row());
1.356     albertel 13770: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13771: 	    $r->print('<td>');
1.356     albertel 13772: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13773: 	    $r->print('</td>');
                   13774: 	}
1.594     raeburn  13775: 	$r->print(&end_data_table_row());
1.31      albertel 13776:     }
1.594     raeburn  13777:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13778: }
                   13779: 
1.144     matthew  13780: ######################################################
                   13781: ######################################################
                   13782: 
1.56      matthew  13783: =pod
                   13784: 
1.648     raeburn  13785: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13786: 
                   13787: Prints a table to create associations between values and table columns.
1.144     matthew  13788: 
1.41      ng       13789: $r is an Apache Request ref,
                   13790: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13791: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13792: 
                   13793: =cut
                   13794: 
1.144     matthew  13795: ######################################################
                   13796: ######################################################
1.31      albertel 13797: sub csv_print_select_table {
                   13798:     my ($r,$records,$d) = @_;
1.301     albertel 13799:     my $i=0;
                   13800:     my $samples = &get_samples($records,1);
1.144     matthew  13801:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13802: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13803:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13804:               '<th>'.&mt('Column').'</th>'.
                   13805:               &end_data_table_header_row()."\n");
1.356     albertel 13806:     foreach my $array_ref (@$d) {
                   13807: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13808: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13809: 
1.875     bisitz   13810: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13811: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13812: 	$r->print('<option value="none"></option>');
1.356     albertel 13813: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13814: 	    $r->print('<option value="'.$sample.'"'.
                   13815:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13816:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13817: 	}
1.594     raeburn  13818: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13819: 	$i++;
                   13820:     }
1.594     raeburn  13821:     $r->print(&end_data_table());
1.31      albertel 13822:     $i--;
                   13823:     return $i;
                   13824: }
1.56      matthew  13825: 
1.144     matthew  13826: ######################################################
                   13827: ######################################################
                   13828: 
1.56      matthew  13829: =pod
1.31      albertel 13830: 
1.648     raeburn  13831: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13832: 
                   13833: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13834: 
                   13835: $r is an Apache Request ref,
                   13836: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13837: $d is an array of 2 element arrays (internal name, displayed name)
                   13838: 
                   13839: =cut
                   13840: 
1.144     matthew  13841: ######################################################
                   13842: ######################################################
1.31      albertel 13843: sub csv_samples_select_table {
                   13844:     my ($r,$records,$d) = @_;
                   13845:     my $i=0;
1.144     matthew  13846:     #
1.662     bisitz   13847:     my $max_samples = 5;
                   13848:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13849:     $r->print(&start_data_table().
                   13850:               &start_data_table_header_row().'<th>'.
                   13851:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13852:               &end_data_table_header_row());
1.301     albertel 13853: 
                   13854:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13855: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13856: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13857: 	foreach my $option (@$d) {
                   13858: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13859: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13860:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13861:                       $display.'</option>');
1.31      albertel 13862: 	}
                   13863: 	$r->print('</select></td><td>');
1.662     bisitz   13864: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13865: 	    if (defined($samples->[$line]{$key})) { 
                   13866: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13867: 	    }
                   13868: 	}
1.594     raeburn  13869: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13870: 	$i++;
                   13871:     }
1.594     raeburn  13872:     $r->print(&end_data_table());
1.31      albertel 13873:     $i--;
                   13874:     return($i);
1.115     matthew  13875: }
                   13876: 
1.144     matthew  13877: ######################################################
                   13878: ######################################################
                   13879: 
1.115     matthew  13880: =pod
                   13881: 
1.648     raeburn  13882: =item * &clean_excel_name($name)
1.115     matthew  13883: 
                   13884: Returns a replacement for $name which does not contain any illegal characters.
                   13885: 
                   13886: =cut
                   13887: 
1.144     matthew  13888: ######################################################
                   13889: ######################################################
1.115     matthew  13890: sub clean_excel_name {
                   13891:     my ($name) = @_;
                   13892:     $name =~ s/[:\*\?\/\\]//g;
                   13893:     if (length($name) > 31) {
                   13894:         $name = substr($name,0,31);
                   13895:     }
                   13896:     return $name;
1.25      albertel 13897: }
1.84      albertel 13898: 
1.85      albertel 13899: =pod
                   13900: 
1.648     raeburn  13901: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13902: 
                   13903: Returns either 1 or undef
                   13904: 
                   13905: 1 if the part is to be hidden, undef if it is to be shown
                   13906: 
                   13907: Arguments are:
                   13908: 
                   13909: $id the id of the part to be checked
                   13910: $symb, optional the symb of the resource to check
                   13911: $udom, optional the domain of the user to check for
                   13912: $uname, optional the username of the user to check for
                   13913: 
                   13914: =cut
1.84      albertel 13915: 
                   13916: sub check_if_partid_hidden {
                   13917:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13918:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13919: 					 $symb,$udom,$uname);
1.141     albertel 13920:     my $truth=1;
                   13921:     #if the string starts with !, then the list is the list to show not hide
                   13922:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13923:     my @hiddenlist=split(/,/,$hiddenparts);
                   13924:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13925: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13926:     }
1.141     albertel 13927:     return !$truth;
1.84      albertel 13928: }
1.127     matthew  13929: 
1.138     matthew  13930: 
                   13931: ############################################################
                   13932: ############################################################
                   13933: 
                   13934: =pod
                   13935: 
1.157     matthew  13936: =back 
                   13937: 
1.138     matthew  13938: =head1 cgi-bin script and graphing routines
                   13939: 
1.157     matthew  13940: =over 4
                   13941: 
1.648     raeburn  13942: =item * &get_cgi_id()
1.138     matthew  13943: 
                   13944: Inputs: none
                   13945: 
                   13946: Returns an id which can be used to pass environment variables
                   13947: to various cgi-bin scripts.  These environment variables will
                   13948: be removed from the users environment after a given time by
                   13949: the routine &Apache::lonnet::transfer_profile_to_env.
                   13950: 
                   13951: =cut
                   13952: 
                   13953: ############################################################
                   13954: ############################################################
1.152     albertel 13955: my $uniq=0;
1.136     matthew  13956: sub get_cgi_id {
1.154     albertel 13957:     $uniq=($uniq+1)%100000;
1.280     albertel 13958:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13959: }
                   13960: 
1.127     matthew  13961: ############################################################
                   13962: ############################################################
                   13963: 
                   13964: =pod
                   13965: 
1.648     raeburn  13966: =item * &DrawBarGraph()
1.127     matthew  13967: 
1.138     matthew  13968: Facilitates the plotting of data in a (stacked) bar graph.
                   13969: Puts plot definition data into the users environment in order for 
                   13970: graph.png to plot it.  Returns an <img> tag for the plot.
                   13971: The bars on the plot are labeled '1','2',...,'n'.
                   13972: 
                   13973: Inputs:
                   13974: 
                   13975: =over 4
                   13976: 
                   13977: =item $Title: string, the title of the plot
                   13978: 
                   13979: =item $xlabel: string, text describing the X-axis of the plot
                   13980: 
                   13981: =item $ylabel: string, text describing the Y-axis of the plot
                   13982: 
                   13983: =item $Max: scalar, the maximum Y value to use in the plot
                   13984: If $Max is < any data point, the graph will not be rendered.
                   13985: 
1.140     matthew  13986: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13987: they are plotted.  If undefined, default values will be used.
                   13988: 
1.178     matthew  13989: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13990: 
1.138     matthew  13991: =item @Values: An array of array references.  Each array reference holds data
                   13992: to be plotted in a stacked bar chart.
                   13993: 
1.239     matthew  13994: =item If the final element of @Values is a hash reference the key/value
                   13995: pairs will be added to the graph definition.
                   13996: 
1.138     matthew  13997: =back
                   13998: 
                   13999: Returns:
                   14000: 
                   14001: An <img> tag which references graph.png and the appropriate identifying
                   14002: information for the plot.
                   14003: 
1.127     matthew  14004: =cut
                   14005: 
                   14006: ############################################################
                   14007: ############################################################
1.134     matthew  14008: sub DrawBarGraph {
1.178     matthew  14009:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14010:     #
                   14011:     if (! defined($colors)) {
                   14012:         $colors = ['#33ff00', 
                   14013:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14014:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14015:                   ]; 
                   14016:     }
1.228     matthew  14017:     my $extra_settings = {};
                   14018:     if (ref($Values[-1]) eq 'HASH') {
                   14019:         $extra_settings = pop(@Values);
                   14020:     }
1.127     matthew  14021:     #
1.136     matthew  14022:     my $identifier = &get_cgi_id();
                   14023:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14024:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14025:         return '';
                   14026:     }
1.225     matthew  14027:     #
                   14028:     my @Labels;
                   14029:     if (defined($labels)) {
                   14030:         @Labels = @$labels;
                   14031:     } else {
                   14032:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  14033:             push(@Labels,$i+1);
1.225     matthew  14034:         }
                   14035:     }
                   14036:     #
1.129     matthew  14037:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14038:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14039:     my %ValuesHash;
                   14040:     my $NumSets=1;
                   14041:     foreach my $array (@Values) {
                   14042:         next if (! ref($array));
1.136     matthew  14043:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14044:             join(',',@$array);
1.129     matthew  14045:     }
1.127     matthew  14046:     #
1.136     matthew  14047:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14048:     if ($NumBars < 3) {
                   14049:         $width = 120+$NumBars*32;
1.220     matthew  14050:         $xskip = 1;
1.225     matthew  14051:         $bar_width = 30;
                   14052:     } elsif ($NumBars < 5) {
                   14053:         $width = 120+$NumBars*20;
                   14054:         $xskip = 1;
                   14055:         $bar_width = 20;
1.220     matthew  14056:     } elsif ($NumBars < 10) {
1.136     matthew  14057:         $width = 120+$NumBars*15;
                   14058:         $xskip = 1;
                   14059:         $bar_width = 15;
                   14060:     } elsif ($NumBars <= 25) {
                   14061:         $width = 120+$NumBars*11;
                   14062:         $xskip = 5;
                   14063:         $bar_width = 8;
                   14064:     } elsif ($NumBars <= 50) {
                   14065:         $width = 120+$NumBars*8;
                   14066:         $xskip = 5;
                   14067:         $bar_width = 4;
                   14068:     } else {
                   14069:         $width = 120+$NumBars*8;
                   14070:         $xskip = 5;
                   14071:         $bar_width = 4;
                   14072:     }
                   14073:     #
1.137     matthew  14074:     $Max = 1 if ($Max < 1);
                   14075:     if ( int($Max) < $Max ) {
                   14076:         $Max++;
                   14077:         $Max = int($Max);
                   14078:     }
1.127     matthew  14079:     $Title  = '' if (! defined($Title));
                   14080:     $xlabel = '' if (! defined($xlabel));
                   14081:     $ylabel = '' if (! defined($ylabel));
1.369     www      14082:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14083:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14084:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14085:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14086:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14087:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14088:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14089:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14090:     $ValuesHash{$id.'.height'}   = $height;
                   14091:     $ValuesHash{$id.'.width'}    = $width;
                   14092:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14093:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14094:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14095:     #
1.228     matthew  14096:     # Deal with other parameters
                   14097:     while (my ($key,$value) = each(%$extra_settings)) {
                   14098:         $ValuesHash{$id.'.'.$key} = $value;
                   14099:     }
                   14100:     #
1.646     raeburn  14101:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14102:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14103: }
                   14104: 
                   14105: ############################################################
                   14106: ############################################################
                   14107: 
                   14108: =pod
                   14109: 
1.648     raeburn  14110: =item * &DrawXYGraph()
1.137     matthew  14111: 
1.138     matthew  14112: Facilitates the plotting of data in an XY graph.
                   14113: Puts plot definition data into the users environment in order for 
                   14114: graph.png to plot it.  Returns an <img> tag for the plot.
                   14115: 
                   14116: Inputs:
                   14117: 
                   14118: =over 4
                   14119: 
                   14120: =item $Title: string, the title of the plot
                   14121: 
                   14122: =item $xlabel: string, text describing the X-axis of the plot
                   14123: 
                   14124: =item $ylabel: string, text describing the Y-axis of the plot
                   14125: 
                   14126: =item $Max: scalar, the maximum Y value to use in the plot
                   14127: If $Max is < any data point, the graph will not be rendered.
                   14128: 
                   14129: =item $colors: Array ref containing the hex color codes for the data to be 
                   14130: plotted in.  If undefined, default values will be used.
                   14131: 
                   14132: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14133: 
                   14134: =item $Ydata: Array ref containing Array refs.  
1.185     www      14135: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14136: 
                   14137: =item %Values: hash indicating or overriding any default values which are 
                   14138: passed to graph.png.  
                   14139: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14140: 
                   14141: =back
                   14142: 
                   14143: Returns:
                   14144: 
                   14145: An <img> tag which references graph.png and the appropriate identifying
                   14146: information for the plot.
                   14147: 
1.137     matthew  14148: =cut
                   14149: 
                   14150: ############################################################
                   14151: ############################################################
                   14152: sub DrawXYGraph {
                   14153:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14154:     #
                   14155:     # Create the identifier for the graph
                   14156:     my $identifier = &get_cgi_id();
                   14157:     my $id = 'cgi.'.$identifier;
                   14158:     #
                   14159:     $Title  = '' if (! defined($Title));
                   14160:     $xlabel = '' if (! defined($xlabel));
                   14161:     $ylabel = '' if (! defined($ylabel));
                   14162:     my %ValuesHash = 
                   14163:         (
1.369     www      14164:          $id.'.title'  => &escape($Title),
                   14165:          $id.'.xlabel' => &escape($xlabel),
                   14166:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14167:          $id.'.y_max_value'=> $Max,
                   14168:          $id.'.labels'     => join(',',@$Xlabels),
                   14169:          $id.'.PlotType'   => 'XY',
                   14170:          );
                   14171:     #
                   14172:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14173:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14174:     }
                   14175:     #
                   14176:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14177:         return '';
                   14178:     }
                   14179:     my $NumSets=1;
1.138     matthew  14180:     foreach my $array (@{$Ydata}){
1.137     matthew  14181:         next if (! ref($array));
                   14182:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14183:     }
1.138     matthew  14184:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14185:     #
                   14186:     # Deal with other parameters
                   14187:     while (my ($key,$value) = each(%Values)) {
                   14188:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14189:     }
                   14190:     #
1.646     raeburn  14191:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14192:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14193: }
                   14194: 
                   14195: ############################################################
                   14196: ############################################################
                   14197: 
                   14198: =pod
                   14199: 
1.648     raeburn  14200: =item * &DrawXYYGraph()
1.138     matthew  14201: 
                   14202: Facilitates the plotting of data in an XY graph with two Y axes.
                   14203: Puts plot definition data into the users environment in order for 
                   14204: graph.png to plot it.  Returns an <img> tag for the plot.
                   14205: 
                   14206: Inputs:
                   14207: 
                   14208: =over 4
                   14209: 
                   14210: =item $Title: string, the title of the plot
                   14211: 
                   14212: =item $xlabel: string, text describing the X-axis of the plot
                   14213: 
                   14214: =item $ylabel: string, text describing the Y-axis of the plot
                   14215: 
                   14216: =item $colors: Array ref containing the hex color codes for the data to be 
                   14217: plotted in.  If undefined, default values will be used.
                   14218: 
                   14219: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14220: 
                   14221: =item $Ydata1: The first data set
                   14222: 
                   14223: =item $Min1: The minimum value of the left Y-axis
                   14224: 
                   14225: =item $Max1: The maximum value of the left Y-axis
                   14226: 
                   14227: =item $Ydata2: The second data set
                   14228: 
                   14229: =item $Min2: The minimum value of the right Y-axis
                   14230: 
                   14231: =item $Max2: The maximum value of the left Y-axis
                   14232: 
                   14233: =item %Values: hash indicating or overriding any default values which are 
                   14234: passed to graph.png.  
                   14235: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14236: 
                   14237: =back
                   14238: 
                   14239: Returns:
                   14240: 
                   14241: An <img> tag which references graph.png and the appropriate identifying
                   14242: information for the plot.
1.136     matthew  14243: 
                   14244: =cut
                   14245: 
                   14246: ############################################################
                   14247: ############################################################
1.137     matthew  14248: sub DrawXYYGraph {
                   14249:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14250:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14251:     #
                   14252:     # Create the identifier for the graph
                   14253:     my $identifier = &get_cgi_id();
                   14254:     my $id = 'cgi.'.$identifier;
                   14255:     #
                   14256:     $Title  = '' if (! defined($Title));
                   14257:     $xlabel = '' if (! defined($xlabel));
                   14258:     $ylabel = '' if (! defined($ylabel));
                   14259:     my %ValuesHash = 
                   14260:         (
1.369     www      14261:          $id.'.title'  => &escape($Title),
                   14262:          $id.'.xlabel' => &escape($xlabel),
                   14263:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14264:          $id.'.labels' => join(',',@$Xlabels),
                   14265:          $id.'.PlotType' => 'XY',
                   14266:          $id.'.NumSets' => 2,
1.137     matthew  14267:          $id.'.two_axes' => 1,
                   14268:          $id.'.y1_max_value' => $Max1,
                   14269:          $id.'.y1_min_value' => $Min1,
                   14270:          $id.'.y2_max_value' => $Max2,
                   14271:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14272:          );
                   14273:     #
1.137     matthew  14274:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14275:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14276:     }
                   14277:     #
                   14278:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14279:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14280:         return '';
                   14281:     }
                   14282:     my $NumSets=1;
1.137     matthew  14283:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14284:         next if (! ref($array));
                   14285:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14286:     }
                   14287:     #
                   14288:     # Deal with other parameters
                   14289:     while (my ($key,$value) = each(%Values)) {
                   14290:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14291:     }
                   14292:     #
1.646     raeburn  14293:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14294:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14295: }
                   14296: 
                   14297: ############################################################
                   14298: ############################################################
                   14299: 
                   14300: =pod
                   14301: 
1.157     matthew  14302: =back 
                   14303: 
1.139     matthew  14304: =head1 Statistics helper routines?  
                   14305: 
                   14306: Bad place for them but what the hell.
                   14307: 
1.157     matthew  14308: =over 4
                   14309: 
1.648     raeburn  14310: =item * &chartlink()
1.139     matthew  14311: 
                   14312: Returns a link to the chart for a specific student.  
                   14313: 
                   14314: Inputs:
                   14315: 
                   14316: =over 4
                   14317: 
                   14318: =item $linktext: The text of the link
                   14319: 
                   14320: =item $sname: The students username
                   14321: 
                   14322: =item $sdomain: The students domain
                   14323: 
                   14324: =back
                   14325: 
1.157     matthew  14326: =back
                   14327: 
1.139     matthew  14328: =cut
                   14329: 
                   14330: ############################################################
                   14331: ############################################################
                   14332: sub chartlink {
                   14333:     my ($linktext, $sname, $sdomain) = @_;
                   14334:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14335:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14336:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14337:        '">'.$linktext.'</a>';
1.153     matthew  14338: }
                   14339: 
                   14340: #######################################################
                   14341: #######################################################
                   14342: 
                   14343: =pod
                   14344: 
                   14345: =head1 Course Environment Routines
1.157     matthew  14346: 
                   14347: =over 4
1.153     matthew  14348: 
1.648     raeburn  14349: =item * &restore_course_settings()
1.153     matthew  14350: 
1.648     raeburn  14351: =item * &store_course_settings()
1.153     matthew  14352: 
                   14353: Restores/Store indicated form parameters from the course environment.
                   14354: Will not overwrite existing values of the form parameters.
                   14355: 
                   14356: Inputs: 
                   14357: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14358: 
                   14359: a hash ref describing the data to be stored.  For example:
                   14360:    
                   14361: %Save_Parameters = ('Status' => 'scalar',
                   14362:     'chartoutputmode' => 'scalar',
                   14363:     'chartoutputdata' => 'scalar',
                   14364:     'Section' => 'array',
1.373     raeburn  14365:     'Group' => 'array',
1.153     matthew  14366:     'StudentData' => 'array',
                   14367:     'Maps' => 'array');
                   14368: 
                   14369: Returns: both routines return nothing
                   14370: 
1.631     raeburn  14371: =back
                   14372: 
1.153     matthew  14373: =cut
                   14374: 
                   14375: #######################################################
                   14376: #######################################################
                   14377: sub store_course_settings {
1.496     albertel 14378:     return &store_settings($env{'request.course.id'},@_);
                   14379: }
                   14380: 
                   14381: sub store_settings {
1.153     matthew  14382:     # save to the environment
                   14383:     # appenv the same items, just to be safe
1.300     albertel 14384:     my $udom  = $env{'user.domain'};
                   14385:     my $uname = $env{'user.name'};
1.496     albertel 14386:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14387:     my %SaveHash;
                   14388:     my %AppHash;
                   14389:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14390:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14391:         my $envname = 'environment.'.$basename;
1.258     albertel 14392:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14393:             # Save this value away
                   14394:             if ($type eq 'scalar' &&
1.258     albertel 14395:                 (! exists($env{$envname}) || 
                   14396:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14397:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14398:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14399:             } elsif ($type eq 'array') {
                   14400:                 my $stored_form;
1.258     albertel 14401:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14402:                     $stored_form = join(',',
                   14403:                                         map {
1.369     www      14404:                                             &escape($_);
1.258     albertel 14405:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14406:                 } else {
                   14407:                     $stored_form = 
1.369     www      14408:                         &escape($env{'form.'.$setting});
1.153     matthew  14409:                 }
                   14410:                 # Determine if the array contents are the same.
1.258     albertel 14411:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14412:                     $SaveHash{$basename} = $stored_form;
                   14413:                     $AppHash{$envname}   = $stored_form;
                   14414:                 }
                   14415:             }
                   14416:         }
                   14417:     }
                   14418:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14419:                                           $udom,$uname);
1.153     matthew  14420:     if ($put_result !~ /^(ok|delayed)/) {
                   14421:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14422:                                  'got error:'.$put_result);
                   14423:     }
                   14424:     # Make sure these settings stick around in this session, too
1.646     raeburn  14425:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14426:     return;
                   14427: }
                   14428: 
                   14429: sub restore_course_settings {
1.499     albertel 14430:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14431: }
                   14432: 
                   14433: sub restore_settings {
                   14434:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14435:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14436:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14437:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14438:             '.'.$setting;
1.258     albertel 14439:         if (exists($env{$envname})) {
1.153     matthew  14440:             if ($type eq 'scalar') {
1.258     albertel 14441:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14442:             } elsif ($type eq 'array') {
1.258     albertel 14443:                 $env{'form.'.$setting} = [ 
1.153     matthew  14444:                                            map { 
1.369     www      14445:                                                &unescape($_); 
1.258     albertel 14446:                                            } split(',',$env{$envname})
1.153     matthew  14447:                                            ];
                   14448:             }
                   14449:         }
                   14450:     }
1.127     matthew  14451: }
                   14452: 
1.618     raeburn  14453: #######################################################
                   14454: #######################################################
                   14455: 
                   14456: =pod
                   14457: 
                   14458: =head1 Domain E-mail Routines  
                   14459: 
                   14460: =over 4
                   14461: 
1.648     raeburn  14462: =item * &build_recipient_list()
1.618     raeburn  14463: 
1.1075.2.44  raeburn  14464: Build recipient lists for following types of e-mail:
1.766     raeburn  14465: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  14466: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14467: module change checking, student/employee ID conflict checks, as
                   14468: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14469: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14470: 
                   14471: Inputs:
1.1075.2.44  raeburn  14472: defmail (scalar - email address of default recipient),
                   14473: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14474: requestsmail, updatesmail, or idconflictsmail).
                   14475: 
1.619     raeburn  14476: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  14477: 
                   14478: origmail (scalar - email address of recipient from loncapa.conf,
                   14479: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  14480: 
1.1075.2.139  raeburn  14481: $requname username of requester (if mailing type is helpdeskmail)
                   14482: 
                   14483: $requdom domain of requester (if mailing type is helpdeskmail)
                   14484: 
                   14485: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   14486: 
1.655     raeburn  14487: Returns: comma separated list of addresses to which to send e-mail.
                   14488: 
                   14489: =back
1.618     raeburn  14490: 
                   14491: =cut
                   14492: 
                   14493: ############################################################
                   14494: ############################################################
                   14495: sub build_recipient_list {
1.1075.2.139  raeburn  14496:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  14497:     my @recipients;
1.1075.2.122  raeburn  14498:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14499:     my %domconfig =
1.1075.2.122  raeburn  14500:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14501:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14502:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14503:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14504:                 my @contacts = ('adminemail','supportemail');
                   14505:                 foreach my $item (@contacts) {
                   14506:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14507:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14508:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14509:                             push(@recipients,$addr);
                   14510:                         }
1.619     raeburn  14511:                     }
1.1075.2.122  raeburn  14512:                 }
                   14513:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14514:                 if ($mailing eq 'helpdeskmail') {
                   14515:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14516:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14517:                         my @ok_bccs;
                   14518:                         foreach my $bcc (@bccs) {
                   14519:                             $bcc =~ s/^\s+//g;
                   14520:                             $bcc =~ s/\s+$//g;
                   14521:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14522:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14523:                                     push(@ok_bccs,$bcc);
                   14524:                                 }
                   14525:                             }
                   14526:                         }
                   14527:                         if (@ok_bccs > 0) {
                   14528:                             $allbcc = join(', ',@ok_bccs);
                   14529:                         }
                   14530:                     }
                   14531:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14532:                 }
                   14533:             }
1.766     raeburn  14534:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14535:             $lastresort = $origmail;
1.618     raeburn  14536:         }
1.1075.2.139  raeburn  14537:         if ($mailing eq 'helpdeskmail') {
                   14538:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   14539:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   14540:                 my ($inststatus,$inststatus_checked);
                   14541:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   14542:                     ($env{'user.domain'} ne 'public')) {
                   14543:                     $inststatus_checked = 1;
                   14544:                     $inststatus = $env{'environment.inststatus'};
                   14545:                 }
                   14546:                 unless ($inststatus_checked) {
                   14547:                     if (($requname ne '') && ($requdom ne '')) {
                   14548:                         if (($requname =~ /^$match_username$/) &&
                   14549:                             ($requdom =~ /^$match_domain$/) &&
                   14550:                             (&Apache::lonnet::domain($requdom))) {
                   14551:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   14552:                                                                       $requdom);
                   14553:                             unless ($requhome eq 'no_host') {
                   14554:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   14555:                                 $inststatus = $userenv{'inststatus'};
                   14556:                                 $inststatus_checked = 1;
                   14557:                             }
                   14558:                         }
                   14559:                     }
                   14560:                 }
                   14561:                 unless ($inststatus_checked) {
                   14562:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   14563:                         my %srch = (srchby     => 'email',
                   14564:                                     srchdomain => $defdom,
                   14565:                                     srchterm   => $reqemail,
                   14566:                                     srchtype   => 'exact');
                   14567:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   14568:                         foreach my $uname (keys(%srch_results)) {
                   14569:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14570:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14571:                                 $inststatus_checked = 1;
                   14572:                                 last;
                   14573:                             }
                   14574:                         }
                   14575:                         unless ($inststatus_checked) {
                   14576:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   14577:                             if ($dirsrchres eq 'ok') {
                   14578:                                 foreach my $uname (keys(%srch_results)) {
                   14579:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14580:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14581:                                         $inststatus_checked = 1;
                   14582:                                         last;
                   14583:                                     }
                   14584:                                 }
                   14585:                             }
                   14586:                         }
                   14587:                     }
                   14588:                 }
                   14589:                 if ($inststatus ne '') {
                   14590:                     foreach my $status (split(/\:/,$inststatus)) {
                   14591:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   14592:                             my @contacts = ('adminemail','supportemail');
                   14593:                             foreach my $item (@contacts) {
                   14594:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   14595:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   14596:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14597:                                         push(@recipients,$addr);
                   14598:                                     }
                   14599:                                 }
                   14600:                             }
                   14601:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   14602:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   14603:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   14604:                                 my @ok_bccs;
                   14605:                                 foreach my $bcc (@bccs) {
                   14606:                                     $bcc =~ s/^\s+//g;
                   14607:                                     $bcc =~ s/\s+$//g;
                   14608:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14609:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14610:                                             push(@ok_bccs,$bcc);
                   14611:                                         }
                   14612:                                     }
                   14613:                                 }
                   14614:                                 if (@ok_bccs > 0) {
                   14615:                                     $allbcc = join(', ',@ok_bccs);
                   14616:                                 }
                   14617:                             }
                   14618:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   14619:                             last;
                   14620:                         }
                   14621:                     }
                   14622:                 }
                   14623:             }
                   14624:         }
1.619     raeburn  14625:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14626:         $lastresort = $origmail;
                   14627:     }
1.1075.2.128  raeburn  14628:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1075.2.122  raeburn  14629:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14630:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14631:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14632:             my %what = (
                   14633:                           perlvar => 1,
                   14634:                        );
                   14635:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14636:             if ($primary) {
                   14637:                 my $gotaddr;
                   14638:                 my ($result,$returnhash) =
                   14639:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14640:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14641:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14642:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14643:                         $gotaddr = 1;
                   14644:                     }
                   14645:                 }
                   14646:                 unless ($gotaddr) {
                   14647:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14648:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14649:                     unless ($uintdom eq $intdom) {
                   14650:                         my %domconfig =
                   14651:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14652:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14653:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14654:                                 my @contacts = ('adminemail','supportemail');
                   14655:                                 foreach my $item (@contacts) {
                   14656:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14657:                                         my $addr = $domconfig{'contacts'}{$item};
                   14658:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14659:                                             push(@recipients,$addr);
                   14660:                                         }
                   14661:                                     }
                   14662:                                 }
                   14663:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14664:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14665:                                 }
                   14666:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14667:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14668:                                     my @ok_bccs;
                   14669:                                     foreach my $bcc (@bccs) {
                   14670:                                         $bcc =~ s/^\s+//g;
                   14671:                                         $bcc =~ s/\s+$//g;
                   14672:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14673:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14674:                                                 push(@ok_bccs,$bcc);
                   14675:                                             }
                   14676:                                         }
                   14677:                                     }
                   14678:                                     if (@ok_bccs > 0) {
                   14679:                                         $allbcc = join(', ',@ok_bccs);
                   14680:                                     }
                   14681:                                 }
                   14682:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14683:                             }
                   14684:                         }
                   14685:                     }
                   14686:                 }
                   14687:             }
                   14688:         }
1.618     raeburn  14689:     }
1.688     raeburn  14690:     if (defined($defmail)) {
                   14691:         if ($defmail ne '') {
                   14692:             push(@recipients,$defmail);
                   14693:         }
1.618     raeburn  14694:     }
                   14695:     if ($otheremails) {
1.619     raeburn  14696:         my @others;
                   14697:         if ($otheremails =~ /,/) {
                   14698:             @others = split(/,/,$otheremails);
1.618     raeburn  14699:         } else {
1.619     raeburn  14700:             push(@others,$otheremails);
                   14701:         }
                   14702:         foreach my $addr (@others) {
                   14703:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14704:                 push(@recipients,$addr);
                   14705:             }
1.618     raeburn  14706:         }
                   14707:     }
1.1075.2.128  raeburn  14708:     if ($mailing eq 'helpdeskmail') {
1.1075.2.122  raeburn  14709:         if ((!@recipients) && ($lastresort ne '')) {
                   14710:             push(@recipients,$lastresort);
                   14711:         }
                   14712:     } elsif ($lastresort ne '') {
                   14713:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14714:             push(@recipients,$lastresort);
                   14715:         }
                   14716:     }
                   14717:     my $recipientlist = join(',',@recipients);
                   14718:     if (wantarray) {
                   14719:         return ($recipientlist,$allbcc,$addtext);
                   14720:     } else {
                   14721:         return $recipientlist;
                   14722:     }
1.618     raeburn  14723: }
                   14724: 
1.127     matthew  14725: ############################################################
                   14726: ############################################################
1.154     albertel 14727: 
1.655     raeburn  14728: =pod
                   14729: 
                   14730: =head1 Course Catalog Routines
                   14731: 
                   14732: =over 4
                   14733: 
                   14734: =item * &gather_categories()
                   14735: 
                   14736: Converts category definitions - keys of categories hash stored in  
                   14737: coursecategories in configuration.db on the primary library server in a 
                   14738: domain - to an array.  Also generates javascript and idx hash used to 
                   14739: generate Domain Coordinator interface for editing Course Categories.
                   14740: 
                   14741: Inputs:
1.663     raeburn  14742: 
1.655     raeburn  14743: categories (reference to hash of category definitions).
1.663     raeburn  14744: 
1.655     raeburn  14745: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14746:       categories and subcategories).
1.663     raeburn  14747: 
1.655     raeburn  14748: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14749:       editing Course Categories).
1.663     raeburn  14750: 
1.655     raeburn  14751: jsarray (reference to array of categories used to create Javascript arrays for
                   14752:          Domain Coordinator interface for editing Course Categories).
                   14753: 
                   14754: Returns: nothing
                   14755: 
                   14756: Side effects: populates cats, idx and jsarray. 
                   14757: 
                   14758: =cut
                   14759: 
                   14760: sub gather_categories {
                   14761:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14762:     my %counters;
                   14763:     my $num = 0;
                   14764:     foreach my $item (keys(%{$categories})) {
                   14765:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14766:         if ($container eq '' && $depth == 0) {
                   14767:             $cats->[$depth][$categories->{$item}] = $cat;
                   14768:         } else {
                   14769:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14770:         }
                   14771:         my ($escitem,$tail) = split(/:/,$item,2);
                   14772:         if ($counters{$tail} eq '') {
                   14773:             $counters{$tail} = $num;
                   14774:             $num ++;
                   14775:         }
                   14776:         if (ref($idx) eq 'HASH') {
                   14777:             $idx->{$item} = $counters{$tail};
                   14778:         }
                   14779:         if (ref($jsarray) eq 'ARRAY') {
                   14780:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14781:         }
                   14782:     }
                   14783:     return;
                   14784: }
                   14785: 
                   14786: =pod
                   14787: 
                   14788: =item * &extract_categories()
                   14789: 
                   14790: Used to generate breadcrumb trails for course categories.
                   14791: 
                   14792: Inputs:
1.663     raeburn  14793: 
1.655     raeburn  14794: categories (reference to hash of category definitions).
1.663     raeburn  14795: 
1.655     raeburn  14796: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14797:       categories and subcategories).
1.663     raeburn  14798: 
1.655     raeburn  14799: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14800: 
1.655     raeburn  14801: allitems (reference to hash - key is category key 
                   14802:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14803: 
1.655     raeburn  14804: idx (reference to hash of counters used in Domain Coordinator interface for
                   14805:       editing Course Categories).
1.663     raeburn  14806: 
1.655     raeburn  14807: jsarray (reference to array of categories used to create Javascript arrays for
                   14808:          Domain Coordinator interface for editing Course Categories).
                   14809: 
1.665     raeburn  14810: subcats (reference to hash of arrays containing all subcategories within each 
                   14811:          category, -recursive)
                   14812: 
1.1075.2.132  raeburn  14813: maxd (reference to hash used to hold max depth for all top-level categories).
                   14814: 
1.655     raeburn  14815: Returns: nothing
                   14816: 
                   14817: Side effects: populates trails and allitems hash references.
                   14818: 
                   14819: =cut
                   14820: 
                   14821: sub extract_categories {
1.1075.2.132  raeburn  14822:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  14823:     if (ref($categories) eq 'HASH') {
                   14824:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14825:         if (ref($cats->[0]) eq 'ARRAY') {
                   14826:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14827:                 my $name = $cats->[0][$i];
                   14828:                 my $item = &escape($name).'::0';
                   14829:                 my $trailstr;
                   14830:                 if ($name eq 'instcode') {
                   14831:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14832:                 } elsif ($name eq 'communities') {
                   14833:                     $trailstr = &mt('Communities');
1.655     raeburn  14834:                 } else {
                   14835:                     $trailstr = $name;
                   14836:                 }
                   14837:                 if ($allitems->{$item} eq '') {
                   14838:                     push(@{$trails},$trailstr);
                   14839:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14840:                 }
                   14841:                 my @parents = ($name);
                   14842:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14843:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14844:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14845:                         if (ref($subcats) eq 'HASH') {
                   14846:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14847:                         }
1.1075.2.132  raeburn  14848:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  14849:                     }
                   14850:                 } else {
                   14851:                     if (ref($subcats) eq 'HASH') {
                   14852:                         $subcats->{$item} = [];
1.655     raeburn  14853:                     }
1.1075.2.132  raeburn  14854:                     if (ref($maxd) eq 'HASH') {
                   14855:                         $maxd->{$name} = 1;
                   14856:                     }
1.655     raeburn  14857:                 }
                   14858:             }
                   14859:         }
                   14860:     }
                   14861:     return;
                   14862: }
                   14863: 
                   14864: =pod
                   14865: 
1.1075.2.56  raeburn  14866: =item * &recurse_categories()
1.655     raeburn  14867: 
                   14868: Recursively used to generate breadcrumb trails for course categories.
                   14869: 
                   14870: Inputs:
1.663     raeburn  14871: 
1.655     raeburn  14872: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14873:       categories and subcategories).
1.663     raeburn  14874: 
1.655     raeburn  14875: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14876: 
                   14877: category (current course category, for which breadcrumb trail is being generated).
                   14878: 
                   14879: trails (reference to array of breadcrumb trails for each category).
                   14880: 
1.655     raeburn  14881: allitems (reference to hash - key is category key
                   14882:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14883: 
1.655     raeburn  14884: parents (array containing containers directories for current category, 
                   14885:          back to top level). 
                   14886: 
                   14887: Returns: nothing
                   14888: 
                   14889: Side effects: populates trails and allitems hash references
                   14890: 
                   14891: =cut
                   14892: 
                   14893: sub recurse_categories {
1.1075.2.132  raeburn  14894:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  14895:     my $shallower = $depth - 1;
                   14896:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14897:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14898:             my $name = $cats->[$depth]{$category}[$k];
                   14899:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14900:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14901:             if ($allitems->{$item} eq '') {
                   14902:                 push(@{$trails},$trailstr);
                   14903:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14904:             }
                   14905:             my $deeper = $depth+1;
                   14906:             push(@{$parents},$category);
1.665     raeburn  14907:             if (ref($subcats) eq 'HASH') {
                   14908:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14909:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14910:                     my $higher;
                   14911:                     if ($j > 0) {
                   14912:                         $higher = &escape($parents->[$j]).':'.
                   14913:                                   &escape($parents->[$j-1]).':'.$j;
                   14914:                     } else {
                   14915:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14916:                     }
                   14917:                     push(@{$subcats->{$higher}},$subcat);
                   14918:                 }
                   14919:             }
                   14920:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1075.2.132  raeburn  14921:                                 $subcats,$maxd);
1.655     raeburn  14922:             pop(@{$parents});
                   14923:         }
                   14924:     } else {
                   14925:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.132  raeburn  14926:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  14927:         if ($allitems->{$item} eq '') {
                   14928:             push(@{$trails},$trailstr);
                   14929:             $allitems->{$item} = scalar(@{$trails})-1;
                   14930:         }
1.1075.2.132  raeburn  14931:         if (ref($maxd) eq 'HASH') {
                   14932:             if ($depth > $maxd->{$parents->[0]}) {
                   14933:                 $maxd->{$parents->[0]} = $depth;
                   14934:             }
                   14935:         }
1.655     raeburn  14936:     }
                   14937:     return;
                   14938: }
                   14939: 
1.663     raeburn  14940: =pod
                   14941: 
1.1075.2.56  raeburn  14942: =item * &assign_categories_table()
1.663     raeburn  14943: 
                   14944: Create a datatable for display of hierarchical categories in a domain,
                   14945: with checkboxes to allow a course to be categorized. 
                   14946: 
                   14947: Inputs:
                   14948: 
                   14949: cathash - reference to hash of categories defined for the domain (from
                   14950:           configuration.db)
                   14951: 
                   14952: currcat - scalar with an & separated list of categories assigned to a course. 
                   14953: 
1.919     raeburn  14954: type    - scalar contains course type (Course or Community).
                   14955: 
1.1075.2.117  raeburn  14956: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14957:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14958: 
1.663     raeburn  14959: Returns: $output (markup to be displayed) 
                   14960: 
                   14961: =cut
                   14962: 
                   14963: sub assign_categories_table {
1.1075.2.117  raeburn  14964:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  14965:     my $output;
                   14966:     if (ref($cathash) eq 'HASH') {
1.1075.2.132  raeburn  14967:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   14968:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  14969:         $maxdepth = scalar(@cats);
                   14970:         if (@cats > 0) {
                   14971:             my $itemcount = 0;
                   14972:             if (ref($cats[0]) eq 'ARRAY') {
                   14973:                 my @currcategories;
                   14974:                 if ($currcat ne '') {
                   14975:                     @currcategories = split('&',$currcat);
                   14976:                 }
1.919     raeburn  14977:                 my $table;
1.663     raeburn  14978:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14979:                     my $parent = $cats[0][$i];
1.919     raeburn  14980:                     next if ($parent eq 'instcode');
                   14981:                     if ($type eq 'Community') {
                   14982:                         next unless ($parent eq 'communities');
                   14983:                     } else {
                   14984:                         next if ($parent eq 'communities');
                   14985:                     }
1.663     raeburn  14986:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14987:                     my $item = &escape($parent).'::0';
                   14988:                     my $checked = '';
                   14989:                     if (@currcategories > 0) {
                   14990:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14991:                             $checked = ' checked="checked"';
1.663     raeburn  14992:                         }
                   14993:                     }
1.919     raeburn  14994:                     my $parent_title = $parent;
                   14995:                     if ($parent eq 'communities') {
                   14996:                         $parent_title = &mt('Communities');
                   14997:                     }
                   14998:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14999:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  15000:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15001:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15002:                     my $depth = 1;
                   15003:                     push(@path,$parent);
1.1075.2.117  raeburn  15004:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15005:                     pop(@path);
1.919     raeburn  15006:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15007:                     $itemcount ++;
                   15008:                 }
1.919     raeburn  15009:                 if ($itemcount) {
                   15010:                     $output = &Apache::loncommon::start_data_table().
                   15011:                               $table.
                   15012:                               &Apache::loncommon::end_data_table();
                   15013:                 }
1.663     raeburn  15014:             }
                   15015:         }
                   15016:     }
                   15017:     return $output;
                   15018: }
                   15019: 
                   15020: =pod
                   15021: 
1.1075.2.56  raeburn  15022: =item * &assign_category_rows()
1.663     raeburn  15023: 
                   15024: Create a datatable row for display of nested categories in a domain,
                   15025: with checkboxes to allow a course to be categorized,called recursively.
                   15026: 
                   15027: Inputs:
                   15028: 
                   15029: itemcount - track row number for alternating colors
                   15030: 
                   15031: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15032:       categories and subcategories.
                   15033: 
                   15034: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15035: 
                   15036: parent - parent of current category item
                   15037: 
                   15038: path - Array containing all categories back up through the hierarchy from the
                   15039:        current category to the top level.
                   15040: 
                   15041: currcategories - reference to array of current categories assigned to the course
                   15042: 
1.1075.2.117  raeburn  15043: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15044:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15045: 
1.663     raeburn  15046: Returns: $output (markup to be displayed).
                   15047: 
                   15048: =cut
                   15049: 
                   15050: sub assign_category_rows {
1.1075.2.117  raeburn  15051:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15052:     my ($text,$name,$item,$chgstr);
                   15053:     if (ref($cats) eq 'ARRAY') {
                   15054:         my $maxdepth = scalar(@{$cats});
                   15055:         if (ref($cats->[$depth]) eq 'HASH') {
                   15056:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15057:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15058:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  15059:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15060:                 for (my $j=0; $j<$numchildren; $j++) {
                   15061:                     $name = $cats->[$depth]{$parent}[$j];
                   15062:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15063:                     my $deeper = $depth+1;
                   15064:                     my $checked = '';
                   15065:                     if (ref($currcategories) eq 'ARRAY') {
                   15066:                         if (@{$currcategories} > 0) {
                   15067:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15068:                                 $checked = ' checked="checked"';
1.663     raeburn  15069:                             }
                   15070:                         }
                   15071:                     }
1.664     raeburn  15072:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15073:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  15074:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15075:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15076:                              '</td><td>';
1.663     raeburn  15077:                     if (ref($path) eq 'ARRAY') {
                   15078:                         push(@{$path},$name);
1.1075.2.117  raeburn  15079:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15080:                         pop(@{$path});
                   15081:                     }
                   15082:                     $text .= '</td></tr>';
                   15083:                 }
                   15084:                 $text .= '</table></td>';
                   15085:             }
                   15086:         }
                   15087:     }
                   15088:     return $text;
                   15089: }
                   15090: 
1.1075.2.69  raeburn  15091: =pod
                   15092: 
                   15093: =back
                   15094: 
                   15095: =cut
                   15096: 
1.655     raeburn  15097: ############################################################
                   15098: ############################################################
                   15099: 
                   15100: 
1.443     albertel 15101: sub commit_customrole {
1.664     raeburn  15102:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15103:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15104:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15105:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15106:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15107:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15108:                  '</b><br />';
                   15109:     return $output;
                   15110: }
                   15111: 
                   15112: sub commit_standardrole {
1.1075.2.31  raeburn  15113:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15114:     my ($output,$logmsg,$linefeed);
                   15115:     if ($context eq 'auto') {
                   15116:         $linefeed = "\n";
                   15117:     } else {
                   15118:         $linefeed = "<br />\n";
                   15119:     }  
1.443     albertel 15120:     if ($three eq 'st') {
1.541     raeburn  15121:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  15122:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15123:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15124:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15125:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15126:         } else {
1.541     raeburn  15127:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15128:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15129:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15130:             if ($context eq 'auto') {
                   15131:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15132:             } else {
                   15133:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15134:                &mt('Add to classlist').': <b>ok</b>';
                   15135:             }
                   15136:             $output .= $linefeed;
1.443     albertel 15137:         }
                   15138:     } else {
                   15139:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15140:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15141:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15142:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15143:         if ($context eq 'auto') {
                   15144:             $output .= $result.$linefeed;
                   15145:         } else {
                   15146:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15147:         }
1.443     albertel 15148:     }
                   15149:     return $output;
                   15150: }
                   15151: 
                   15152: sub commit_studentrole {
1.1075.2.31  raeburn  15153:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15154:         $credits) = @_;
1.626     raeburn  15155:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15156:     if ($context eq 'auto') {
                   15157:         $linefeed = "\n";
                   15158:     } else {
                   15159:         $linefeed = '<br />'."\n";
                   15160:     }
1.443     albertel 15161:     if (defined($one) && defined($two)) {
                   15162:         my $cid=$one.'_'.$two;
                   15163:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15164:         my $secchange = 0;
                   15165:         my $expire_role_result;
                   15166:         my $modify_section_result;
1.628     raeburn  15167:         if ($oldsec ne '-1') { 
                   15168:             if ($oldsec ne $sec) {
1.443     albertel 15169:                 $secchange = 1;
1.628     raeburn  15170:                 my $now = time;
1.443     albertel 15171:                 my $uurl='/'.$cid;
                   15172:                 $uurl=~s/\_/\//g;
                   15173:                 if ($oldsec) {
                   15174:                     $uurl.='/'.$oldsec;
                   15175:                 }
1.626     raeburn  15176:                 $oldsecurl = $uurl;
1.628     raeburn  15177:                 $expire_role_result = 
1.652     raeburn  15178:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15179:                 if ($env{'request.course.sec'} ne '') { 
                   15180:                     if ($expire_role_result eq 'refused') {
                   15181:                         my @roles = ('st');
                   15182:                         my @statuses = ('previous');
                   15183:                         my @roledoms = ($one);
                   15184:                         my $withsec = 1;
                   15185:                         my %roleshash = 
                   15186:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15187:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15188:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15189:                             my ($oldstart,$oldend) = 
                   15190:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15191:                             if ($oldend > 0 && $oldend <= $now) {
                   15192:                                 $expire_role_result = 'ok';
                   15193:                             }
                   15194:                         }
                   15195:                     }
                   15196:                 }
1.443     albertel 15197:                 $result = $expire_role_result;
                   15198:             }
                   15199:         }
                   15200:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  15201:             $modify_section_result = 
                   15202:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15203:                                                            undef,undef,undef,$sec,
                   15204:                                                            $end,$start,'','',$cid,
                   15205:                                                            '',$context,$credits);
1.443     albertel 15206:             if ($modify_section_result =~ /^ok/) {
                   15207:                 if ($secchange == 1) {
1.628     raeburn  15208:                     if ($sec eq '') {
                   15209:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15210:                     } else {
                   15211:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15212:                     }
1.443     albertel 15213:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15214:                     if ($sec eq '') {
                   15215:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15216:                     } else {
                   15217:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15218:                     }
1.443     albertel 15219:                 } else {
1.628     raeburn  15220:                     if ($sec eq '') {
                   15221:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15222:                     } else {
                   15223:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15224:                     }
1.443     albertel 15225:                 }
                   15226:             } else {
1.628     raeburn  15227:                 if ($secchange) {       
                   15228:                     $$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;
                   15229:                 } else {
                   15230:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15231:                 }
1.443     albertel 15232:             }
                   15233:             $result = $modify_section_result;
                   15234:         } elsif ($secchange == 1) {
1.628     raeburn  15235:             if ($oldsec eq '') {
1.1075.2.20  raeburn  15236:                 $$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  15237:             } else {
                   15238:                 $$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;
                   15239:             }
1.626     raeburn  15240:             if ($expire_role_result eq 'refused') {
                   15241:                 my $newsecurl = '/'.$cid;
                   15242:                 $newsecurl =~ s/\_/\//g;
                   15243:                 if ($sec ne '') {
                   15244:                     $newsecurl.='/'.$sec;
                   15245:                 }
                   15246:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15247:                     if ($sec eq '') {
                   15248:                         $$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;
                   15249:                     } else {
                   15250:                         $$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;
                   15251:                     }
                   15252:                 }
                   15253:             }
1.443     albertel 15254:         }
                   15255:     } else {
1.626     raeburn  15256:         $$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 15257:         $result = "error: incomplete course id\n";
                   15258:     }
                   15259:     return $result;
                   15260: }
                   15261: 
1.1075.2.25  raeburn  15262: sub show_role_extent {
                   15263:     my ($scope,$context,$role) = @_;
                   15264:     $scope =~ s{^/}{};
                   15265:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15266:     push(@courseroles,'co');
                   15267:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15268:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15269:         $scope =~ s{/}{_};
                   15270:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15271:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15272:         my ($audom,$auname) = split(/\//,$scope);
                   15273:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15274:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15275:     } else {
                   15276:         $scope =~ s{/$}{};
                   15277:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15278:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15279:     }
                   15280: }
                   15281: 
1.443     albertel 15282: ############################################################
                   15283: ############################################################
                   15284: 
1.566     albertel 15285: sub check_clone {
1.578     raeburn  15286:     my ($args,$linefeed) = @_;
1.566     albertel 15287:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15288:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15289:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   15290:     my $clonemsg;
                   15291:     my $can_clone = 0;
1.944     raeburn  15292:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15293:     if ($lctype ne 'community') {
                   15294:         $lctype = 'course';
                   15295:     }
1.566     albertel 15296:     if ($clonehome eq 'no_host') {
1.944     raeburn  15297:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15298:             $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'});
                   15299:         } else {
                   15300:             $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'});
                   15301:         }     
1.566     albertel 15302:     } else {
                   15303: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  15304:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15305:             if ($clonedesc{'type'} ne 'Community') {
                   15306:                  $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'});
                   15307:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15308:             }
                   15309:         }
1.1075.2.119  raeburn  15310: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15311:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15312: 	    $can_clone = 1;
                   15313: 	} else {
1.1075.2.95  raeburn  15314: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15315: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  15316:             if ($clonehash{'cloners'} eq '') {
                   15317:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15318:                 if ($domdefs{'canclone'}) {
                   15319:                     unless ($domdefs{'canclone'} eq 'none') {
                   15320:                         if ($domdefs{'canclone'} eq 'domain') {
                   15321:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15322:                                 $can_clone = 1;
                   15323:                             }
                   15324:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15325:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15326:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15327:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15328:                                 $can_clone = 1;
                   15329:                             }
                   15330:                         }
                   15331:                     }
1.908     raeburn  15332:                 }
1.1075.2.95  raeburn  15333:             } else {
                   15334: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15335:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15336:                     $can_clone = 1;
1.1075.2.95  raeburn  15337:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15338:                     $can_clone = 1;
1.1075.2.96  raeburn  15339:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15340:                     $can_clone = 1;
1.1075.2.95  raeburn  15341:                 }
                   15342:                 unless ($can_clone) {
1.1075.2.96  raeburn  15343:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15344:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  15345:                         my (%gotdomdefaults,%gotcodedefaults);
                   15346:                         foreach my $cloner (@cloners) {
                   15347:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15348:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15349:                                 my (%codedefaults,@code_order);
                   15350:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15351:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15352:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15353:                                     }
                   15354:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15355:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15356:                                     }
                   15357:                                 } else {
                   15358:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15359:                                                                             \%codedefaults,
                   15360:                                                                             \@code_order);
                   15361:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15362:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15363:                                 }
                   15364:                                 if (@code_order > 0) {
                   15365:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15366:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15367:                                                                                 $args->{'crscode'})) {
                   15368:                                         $can_clone = 1;
                   15369:                                         last;
                   15370:                                     }
                   15371:                                 }
                   15372:                             }
                   15373:                         }
                   15374:                     }
1.1075.2.96  raeburn  15375:                 }
                   15376:             }
                   15377:             unless ($can_clone) {
                   15378:                 my $ccrole = 'cc';
                   15379:                 if ($args->{'crstype'} eq 'Community') {
                   15380:                     $ccrole = 'co';
                   15381:                 }
                   15382:                 my %roleshash =
                   15383:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15384:                                                   $args->{'ccdomain'},
                   15385:                                                   'userroles',['active'],[$ccrole],
                   15386:                                                   [$args->{'clonedomain'}]);
                   15387:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15388:                     $can_clone = 1;
                   15389:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15390:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15391:                     $can_clone = 1;
1.1075.2.95  raeburn  15392:                 }
                   15393:             }
                   15394:             unless ($can_clone) {
                   15395:                 if ($args->{'crstype'} eq 'Community') {
                   15396:                     $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'});
                   15397:                 } else {
                   15398:                     $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  15399: 	        }
1.566     albertel 15400: 	    }
1.578     raeburn  15401:         }
1.566     albertel 15402:     }
                   15403:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15404: }
                   15405: 
1.444     albertel 15406: sub construct_course {
1.1075.2.119  raeburn  15407:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   15408:         $cnum,$category,$coderef) = @_;
1.444     albertel 15409:     my $outcome;
1.541     raeburn  15410:     my $linefeed =  '<br />'."\n";
                   15411:     if ($context eq 'auto') {
                   15412:         $linefeed = "\n";
                   15413:     }
1.566     albertel 15414: 
                   15415: #
                   15416: # Are we cloning?
                   15417: #
                   15418:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15419:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  15420: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 15421: 	if ($context ne 'auto') {
1.578     raeburn  15422:             if ($clonemsg ne '') {
                   15423: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   15424:             }
1.566     albertel 15425: 	}
                   15426: 	$outcome .= $clonemsg.$linefeed;
                   15427: 
                   15428:         if (!$can_clone) {
                   15429: 	    return (0,$outcome);
                   15430: 	}
                   15431:     }
                   15432: 
1.444     albertel 15433: #
                   15434: # Open course
                   15435: #
                   15436:     my $crstype = lc($args->{'crstype'});
                   15437:     my %cenv=();
                   15438:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15439:                                              $args->{'cdescr'},
                   15440:                                              $args->{'curl'},
                   15441:                                              $args->{'course_home'},
                   15442:                                              $args->{'nonstandard'},
                   15443:                                              $args->{'crscode'},
                   15444:                                              $args->{'ccuname'}.':'.
                   15445:                                              $args->{'ccdomain'},
1.882     raeburn  15446:                                              $args->{'crstype'},
1.885     raeburn  15447:                                              $cnum,$context,$category);
1.444     albertel 15448: 
                   15449:     # Note: The testing routines depend on this being output; see 
                   15450:     # Utils::Course. This needs to at least be output as a comment
                   15451:     # if anyone ever decides to not show this, and Utils::Course::new
                   15452:     # will need to be suitably modified.
1.541     raeburn  15453:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  15454:     if ($$courseid =~ /^error:/) {
                   15455:         return (0,$outcome);
                   15456:     }
                   15457: 
1.444     albertel 15458: #
                   15459: # Check if created correctly
                   15460: #
1.479     albertel 15461:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15462:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15463:     if ($crsuhome eq 'no_host') {
                   15464:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   15465:         return (0,$outcome);
                   15466:     }
1.541     raeburn  15467:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15468: 
1.444     albertel 15469: #
1.566     albertel 15470: # Do the cloning
                   15471: #   
                   15472:     if ($can_clone && $cloneid) {
                   15473: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   15474: 	if ($context ne 'auto') {
                   15475: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   15476: 	}
                   15477: 	$outcome .= $clonemsg.$linefeed;
                   15478: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15479: # Copy all files
1.637     www      15480: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 15481: # Restore URL
1.566     albertel 15482: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15483: # Restore title
1.566     albertel 15484: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15485: # Restore creation date, creator and creation context.
                   15486:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15487:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15488:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15489: # Mark as cloned
1.566     albertel 15490: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15491: # Need to clone grading mode
                   15492:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15493:         $cenv{'grading'}=$newenv{'grading'};
                   15494: # Do not clone these environment entries
                   15495:         &Apache::lonnet::del('environment',
                   15496:                   ['default_enrollment_start_date',
                   15497:                    'default_enrollment_end_date',
                   15498:                    'question.email',
                   15499:                    'policy.email',
                   15500:                    'comment.email',
                   15501:                    'pch.users.denied',
1.725     raeburn  15502:                    'plc.users.denied',
                   15503:                    'hidefromcat',
1.1075.2.36  raeburn  15504:                    'checkforpriv',
1.1075.2.158  raeburn  15505:                    'categories'],
1.638     www      15506:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  15507:         if ($args->{'textbook'}) {
                   15508:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15509:         }
1.444     albertel 15510:     }
1.566     albertel 15511: 
1.444     albertel 15512: #
                   15513: # Set environment (will override cloned, if existing)
                   15514: #
                   15515:     my @sections = ();
                   15516:     my @xlists = ();
                   15517:     if ($args->{'crstype'}) {
                   15518:         $cenv{'type'}=$args->{'crstype'};
                   15519:     }
                   15520:     if ($args->{'crsid'}) {
                   15521:         $cenv{'courseid'}=$args->{'crsid'};
                   15522:     }
                   15523:     if ($args->{'crscode'}) {
                   15524:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15525:     }
                   15526:     if ($args->{'crsquota'} ne '') {
                   15527:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15528:     } else {
                   15529:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15530:     }
                   15531:     if ($args->{'ccuname'}) {
                   15532:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15533:                                         ':'.$args->{'ccdomain'};
                   15534:     } else {
                   15535:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15536:     }
1.1075.2.31  raeburn  15537:     if ($args->{'defaultcredits'}) {
                   15538:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15539:     }
1.444     albertel 15540:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15541:     if ($args->{'crssections'}) {
                   15542:         $cenv{'internal.sectionnums'} = '';
                   15543:         if ($args->{'crssections'} =~ m/,/) {
                   15544:             @sections = split/,/,$args->{'crssections'};
                   15545:         } else {
                   15546:             $sections[0] = $args->{'crssections'};
                   15547:         }
                   15548:         if (@sections > 0) {
                   15549:             foreach my $item (@sections) {
                   15550:                 my ($sec,$gp) = split/:/,$item;
                   15551:                 my $class = $args->{'crscode'}.$sec;
                   15552:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15553:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15554:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15555:                     push(@badclasses,$class);
1.444     albertel 15556:                 }
                   15557:             }
                   15558:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15559:         }
                   15560:     }
                   15561: # do not hide course coordinator from staff listing, 
                   15562: # even if privileged
                   15563:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  15564: # add course coordinator's domain to domains to check for privileged users
                   15565: # if different to course domain
                   15566:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15567:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15568:     }
1.444     albertel 15569: # add crosslistings
                   15570:     if ($args->{'crsxlist'}) {
                   15571:         $cenv{'internal.crosslistings'}='';
                   15572:         if ($args->{'crsxlist'} =~ m/,/) {
                   15573:             @xlists = split/,/,$args->{'crsxlist'};
                   15574:         } else {
                   15575:             $xlists[0] = $args->{'crsxlist'};
                   15576:         }
                   15577:         if (@xlists > 0) {
                   15578:             foreach my $item (@xlists) {
                   15579:                 my ($xl,$gp) = split/:/,$item;
                   15580:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15581:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15582:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15583:                     push(@badclasses,$xl);
1.444     albertel 15584:                 }
                   15585:             }
                   15586:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15587:         }
                   15588:     }
                   15589:     if ($args->{'autoadds'}) {
                   15590:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15591:     }
                   15592:     if ($args->{'autodrops'}) {
                   15593:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15594:     }
                   15595: # check for notification of enrollment changes
                   15596:     my @notified = ();
                   15597:     if ($args->{'notify_owner'}) {
                   15598:         if ($args->{'ccuname'} ne '') {
                   15599:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15600:         }
                   15601:     }
                   15602:     if ($args->{'notify_dc'}) {
                   15603:         if ($uname ne '') { 
1.630     raeburn  15604:             push(@notified,$uname.':'.$udom);
1.444     albertel 15605:         }
                   15606:     }
                   15607:     if (@notified > 0) {
                   15608:         my $notifylist;
                   15609:         if (@notified > 1) {
                   15610:             $notifylist = join(',',@notified);
                   15611:         } else {
                   15612:             $notifylist = $notified[0];
                   15613:         }
                   15614:         $cenv{'internal.notifylist'} = $notifylist;
                   15615:     }
                   15616:     if (@badclasses > 0) {
                   15617:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  15618:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15619:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15620:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15621:         );
1.1075.2.119  raeburn  15622:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15623:                            &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  15624:         if ($context eq 'auto') {
                   15625:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  15626:         } else {
1.566     albertel 15627:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  15628:         }
                   15629:         foreach my $item (@badclasses) {
1.541     raeburn  15630:             if ($context eq 'auto') {
1.1075.2.119  raeburn  15631:                 $outcome .= " - $item\n";
1.541     raeburn  15632:             } else {
1.1075.2.119  raeburn  15633:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15634:             }
1.1075.2.119  raeburn  15635:         }
                   15636:         if ($context eq 'auto') {
                   15637:             $outcome .= $linefeed;
                   15638:         } else {
                   15639:             $outcome .= "</ul><br /><br /></div>\n";
                   15640:         }
1.444     albertel 15641:     }
                   15642:     if ($args->{'no_end_date'}) {
                   15643:         $args->{'endaccess'} = 0;
                   15644:     }
                   15645:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15646:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15647:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15648:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15649:     if ($args->{'showphotos'}) {
                   15650:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15651:     }
                   15652:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15653:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15654:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15655:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15656:             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'); 
                   15657:             if ($context eq 'auto') {
                   15658:                 $outcome .= $krb_msg;
                   15659:             } else {
1.566     albertel 15660:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15661:             }
                   15662:             $outcome .= $linefeed;
1.444     albertel 15663:         }
                   15664:     }
                   15665:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15666:        if ($args->{'setpolicy'}) {
                   15667:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15668:        }
                   15669:        if ($args->{'setcontent'}) {
                   15670:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15671:        }
1.1075.2.110  raeburn  15672:        if ($args->{'setcomment'}) {
                   15673:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15674:        }
1.444     albertel 15675:     }
                   15676:     if ($args->{'reshome'}) {
                   15677: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15678: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15679:     }
                   15680: #
                   15681: # course has keyed access
                   15682: #
                   15683:     if ($args->{'setkeys'}) {
                   15684:        $cenv{'keyaccess'}='yes';
                   15685:     }
                   15686: # if specified, key authority is not course, but user
                   15687: # only active if keyaccess is yes
                   15688:     if ($args->{'keyauth'}) {
1.487     albertel 15689: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15690: 	$user = &LONCAPA::clean_username($user);
                   15691: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15692: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15693: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15694: 	}
                   15695:     }
                   15696: 
1.1075.2.59  raeburn  15697: #
                   15698: #  generate and store uniquecode (available to course requester), if course should have one.
                   15699: #
                   15700:     if ($args->{'uniquecode'}) {
                   15701:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15702:         if ($code) {
                   15703:             $cenv{'internal.uniquecode'} = $code;
                   15704:             my %crsinfo =
                   15705:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15706:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15707:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15708:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15709:             }
                   15710:             if (ref($coderef)) {
                   15711:                 $$coderef = $code;
                   15712:             }
                   15713:         }
                   15714:     }
                   15715: 
1.444     albertel 15716:     if ($args->{'disresdis'}) {
                   15717:         $cenv{'pch.roles.denied'}='st';
                   15718:     }
                   15719:     if ($args->{'disablechat'}) {
                   15720:         $cenv{'plc.roles.denied'}='st';
                   15721:     }
                   15722: 
                   15723:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15724:     # course
                   15725:     $cenv{'course.helper.not.run'} = 1;
                   15726:     #
                   15727:     # Use new Randomseed
                   15728:     #
                   15729:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15730:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15731:     #
                   15732:     # The encryption code and receipt prefix for this course
                   15733:     #
                   15734:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15735:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15736:     #
                   15737:     # By default, use standard grading
                   15738:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15739: 
1.541     raeburn  15740:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15741:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15742: #
                   15743: # Open all assignments
                   15744: #
                   15745:     if ($args->{'openall'}) {
1.1075.2.146  raeburn  15746:        my $opendate = time;
                   15747:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   15748:            $opendate = $args->{'openallfrom'};
                   15749:        }
1.444     albertel 15750:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1075.2.146  raeburn  15751:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 15752:                            $storeunder.'.type' => 'date_start');
1.1075.2.146  raeburn  15753:        $outcome .= &mt('All assignments open starting [_1]',
                   15754:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   15755:                    &Apache::lonnet::cput
                   15756:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15757:    }
                   15758: #
                   15759: # Set first page
                   15760: #
                   15761:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15762: 	    || ($cloneid)) {
1.445     albertel 15763: 	use LONCAPA::map;
1.444     albertel 15764: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15765: 
                   15766: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15767:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15768: 
1.444     albertel 15769:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15770:         my $title; my $url;
                   15771:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15772: 	    $title=&mt('Syllabus');
1.444     albertel 15773:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15774:         } else {
1.963     raeburn  15775:             $title=&mt('Table of Contents');
1.444     albertel 15776:             $url='/adm/navmaps';
                   15777:         }
1.445     albertel 15778: 
                   15779:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15780: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15781: 
                   15782: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15783:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15784:     }
1.566     albertel 15785: 
                   15786:     return (1,$outcome);
1.444     albertel 15787: }
                   15788: 
1.1075.2.59  raeburn  15789: sub make_unique_code {
                   15790:     my ($cdom,$cnum) = @_;
                   15791:     # get lock on uniquecodes db
                   15792:     my $lockhash = {
                   15793:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15794:                                                   ':'.$env{'user.domain'},
                   15795:                    };
                   15796:     my $tries = 0;
                   15797:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15798:     my ($code,$error);
                   15799: 
                   15800:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15801:         $tries ++;
                   15802:         sleep 1;
                   15803:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15804:     }
                   15805:     if ($gotlock eq 'ok') {
                   15806:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15807:         my $gotcode;
                   15808:         my $attempts = 0;
                   15809:         while ((!$gotcode) && ($attempts < 100)) {
                   15810:             $code = &generate_code();
                   15811:             if (!exists($currcodes{$code})) {
                   15812:                 $gotcode = 1;
                   15813:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15814:                     $error = 'nostore';
                   15815:                 }
                   15816:             }
                   15817:             $attempts ++;
                   15818:         }
                   15819:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15820:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15821:     } else {
                   15822:         $error = 'nolock';
                   15823:     }
                   15824:     return ($code,$error);
                   15825: }
                   15826: 
                   15827: sub generate_code {
                   15828:     my $code;
                   15829:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15830:     for (my $i=0; $i<6; $i++) {
                   15831:         my $lettnum = int (rand 2);
                   15832:         my $item = '';
                   15833:         if ($lettnum) {
                   15834:             $item = $letts[int( rand(18) )];
                   15835:         } else {
                   15836:             $item = 1+int( rand(8) );
                   15837:         }
                   15838:         $code .= $item;
                   15839:     }
                   15840:     return $code;
                   15841: }
                   15842: 
1.444     albertel 15843: ############################################################
                   15844: ############################################################
                   15845: 
1.953     droeschl 15846: #SD
                   15847: # only Community and Course, or anything else?
1.378     raeburn  15848: sub course_type {
                   15849:     my ($cid) = @_;
                   15850:     if (!defined($cid)) {
                   15851:         $cid = $env{'request.course.id'};
                   15852:     }
1.404     albertel 15853:     if (defined($env{'course.'.$cid.'.type'})) {
                   15854:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15855:     } else {
                   15856:         return 'Course';
1.377     raeburn  15857:     }
                   15858: }
1.156     albertel 15859: 
1.406     raeburn  15860: sub group_term {
                   15861:     my $crstype = &course_type();
                   15862:     my %names = (
                   15863:                   'Course' => 'group',
1.865     raeburn  15864:                   'Community' => 'group',
1.406     raeburn  15865:                 );
                   15866:     return $names{$crstype};
                   15867: }
                   15868: 
1.902     raeburn  15869: sub course_types {
1.1075.2.59  raeburn  15870:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  15871:     my %typename = (
                   15872:                          official   => 'Official course',
                   15873:                          unofficial => 'Unofficial course',
                   15874:                          community  => 'Community',
1.1075.2.59  raeburn  15875:                          textbook   => 'Textbook course',
1.902     raeburn  15876:                    );
                   15877:     return (\@types,\%typename);
                   15878: }
                   15879: 
1.156     albertel 15880: sub icon {
                   15881:     my ($file)=@_;
1.505     albertel 15882:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15883:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15884:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15885:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15886: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15887: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15888: 	            $curfext.".gif") {
                   15889: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15890: 		$curfext.".gif";
                   15891: 	}
                   15892:     }
1.249     albertel 15893:     return &lonhttpdurl($iconname);
1.154     albertel 15894: } 
1.84      albertel 15895: 
1.575     albertel 15896: sub lonhttpdurl {
1.692     www      15897: #
                   15898: # Had been used for "small fry" static images on separate port 8080.
                   15899: # Modify here if lightweight http functionality desired again.
                   15900: # Currently eliminated due to increasing firewall issues.
                   15901: #
1.575     albertel 15902:     my ($url)=@_;
1.692     www      15903:     return $url;
1.215     albertel 15904: }
                   15905: 
1.213     albertel 15906: sub connection_aborted {
                   15907:     my ($r)=@_;
                   15908:     $r->print(" ");$r->rflush();
                   15909:     my $c = $r->connection;
                   15910:     return $c->aborted();
                   15911: }
                   15912: 
1.221     foxr     15913: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15914: #    strings as 'strings'.
                   15915: sub escape_single {
1.221     foxr     15916:     my ($input) = @_;
1.223     albertel 15917:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15918:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15919:     return $input;
                   15920: }
1.223     albertel 15921: 
1.222     foxr     15922: #  Same as escape_single, but escape's "'s  This 
                   15923: #  can be used for  "strings"
                   15924: sub escape_double {
                   15925:     my ($input) = @_;
                   15926:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15927:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15928:     return $input;
                   15929: }
1.223     albertel 15930:  
1.222     foxr     15931: #   Escapes the last element of a full URL.
                   15932: sub escape_url {
                   15933:     my ($url)   = @_;
1.238     raeburn  15934:     my @urlslices = split(/\//, $url,-1);
1.369     www      15935:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  15936:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15937: }
1.462     albertel 15938: 
1.820     raeburn  15939: sub compare_arrays {
                   15940:     my ($arrayref1,$arrayref2) = @_;
                   15941:     my (@difference,%count);
                   15942:     @difference = ();
                   15943:     %count = ();
                   15944:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15945:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15946:         foreach my $element (keys(%count)) {
                   15947:             if ($count{$element} == 1) {
                   15948:                 push(@difference,$element);
                   15949:             }
                   15950:         }
                   15951:     }
                   15952:     return @difference;
                   15953: }
                   15954: 
1.1075.2.152  raeburn  15955: sub lon_status_items {
                   15956:     my %defaults = (
                   15957:                      E         => 100,
                   15958:                      W         => 4,
                   15959:                      N         => 1,
                   15960:                      U         => 5,
                   15961:                      threshold => 200,
                   15962:                      sysmail   => 2500,
                   15963:                    );
                   15964:     my %names = (
                   15965:                    E => 'Errors',
                   15966:                    W => 'Warnings',
                   15967:                    N => 'Notices',
                   15968:                    U => 'Unsent',
                   15969:                 );
                   15970:     return (\%defaults,\%names);
                   15971: }
                   15972: 
1.817     bisitz   15973: # -------------------------------------------------------- Initialize user login
1.462     albertel 15974: sub init_user_environment {
1.463     albertel 15975:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15976:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15977: 
                   15978:     my $public=($username eq 'public' && $domain eq 'public');
                   15979: 
                   15980: # See if old ID present, if so, remove
                   15981: 
1.1062    raeburn  15982:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15983:     my $now=time;
                   15984: 
                   15985:     if ($public) {
                   15986: 	my $max_public=100;
                   15987: 	my $oldest;
                   15988: 	my $oldest_time=0;
                   15989: 	for(my $next=1;$next<=$max_public;$next++) {
                   15990: 	    if (-e $lonids."/publicuser_$next.id") {
                   15991: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15992: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15993: 		    $oldest_time=$mtime;
                   15994: 		    $oldest=$next;
                   15995: 		}
                   15996: 	    } else {
                   15997: 		$cookie="publicuser_$next";
                   15998: 		last;
                   15999: 	    }
                   16000: 	}
                   16001: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16002:     } else {
1.463     albertel 16003: 	# if this isn't a robot, kill any existing non-robot sessions
                   16004: 	if (!$args->{'robot'}) {
                   16005: 	    opendir(DIR,$lonids);
                   16006: 	    while ($filename=readdir(DIR)) {
                   16007: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1075.2.136  raeburn  16008:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   16009:                             &GDBM_READER(),0640)) {
                   16010:                         my $linkedfile;
                   16011:                         if (exists($oldenv{'user.linkedenv'})) {
                   16012:                             $linkedfile = $oldenv{'user.linkedenv'};
                   16013:                         }
                   16014:                         untie(%oldenv);
                   16015:                         if (unlink("$lonids/$filename")) {
                   16016:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   16017:                                 if (-l "$lonids/$linkedfile.id") {
                   16018:                                     unlink("$lonids/$linkedfile.id");
                   16019:                                 }
                   16020:                             }
                   16021:                         }
                   16022:                     } else {
                   16023:                         unlink($lonids.'/'.$filename);
                   16024:                     }
1.463     albertel 16025: 		}
1.462     albertel 16026: 	    }
1.463     albertel 16027: 	    closedir(DIR);
1.1075.2.84  raeburn  16028: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16029:             my $namespace = 'nohist_courseeditor';
                   16030:             my $lockingkey = 'paste'."\0".'locked_num';
                   16031:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16032:                                                 $domain,$username);
                   16033:             if (exists($lockhash{$lockingkey})) {
                   16034:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16035:                 unless ($delresult eq 'ok') {
                   16036:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16037:                 }
                   16038:             }
1.462     albertel 16039: 	}
                   16040: # Give them a new cookie
1.463     albertel 16041: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16042: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16043: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16044:     
                   16045: # Initialize roles
                   16046: 
1.1062    raeburn  16047: 	($userroles,$firstaccenv,$timerintenv) = 
                   16048:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16049:     }
                   16050: # ------------------------------------ Check browser type and MathML capability
                   16051: 
1.1075.2.77  raeburn  16052:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   16053:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 16054: 
                   16055: # ------------------------------------------------------------- Get environment
                   16056: 
                   16057:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   16058:     my ($tmp) = keys(%userenv);
                   16059:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   16060:     } else {
                   16061: 	undef(%userenv);
                   16062:     }
                   16063:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   16064: 	$form->{'interface'}=$userenv{'interface'};
                   16065:     }
                   16066:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   16067: 
                   16068: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   16069:     foreach my $option ('interface','localpath','localres') {
                   16070:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 16071:     }
                   16072: # --------------------------------------------------------- Write first profile
                   16073: 
                   16074:     {
1.1075.2.150  raeburn  16075:         my $ip = &Apache::lonnet::get_requestor_ip();
1.462     albertel 16076: 	my %initial_env = 
                   16077: 	    ("user.name"          => $username,
                   16078: 	     "user.domain"        => $domain,
                   16079: 	     "user.home"          => $authhost,
                   16080: 	     "browser.type"       => $clientbrowser,
                   16081: 	     "browser.version"    => $clientversion,
                   16082: 	     "browser.mathml"     => $clientmathml,
                   16083: 	     "browser.unicode"    => $clientunicode,
                   16084: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  16085:              "browser.mobile"     => $clientmobile,
                   16086:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  16087:              "browser.osversion"  => $clientosversion,
1.462     albertel 16088: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   16089: 	     "request.course.fn"  => '',
                   16090: 	     "request.course.uri" => '',
                   16091: 	     "request.course.sec" => '',
                   16092: 	     "request.role"       => 'cm',
                   16093: 	     "request.role.adv"   => $env{'user.adv'},
1.1075.2.150  raeburn  16094: 	     "request.host"       => $ip,);
1.462     albertel 16095: 
                   16096:         if ($form->{'localpath'}) {
                   16097: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   16098: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   16099:         }
                   16100: 	
                   16101: 	if ($form->{'interface'}) {
                   16102: 	    $form->{'interface'}=~s/\W//gs;
                   16103: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   16104: 	    $env{'browser.interface'}=$form->{'interface'};
                   16105: 	}
                   16106: 
1.1075.2.54  raeburn  16107:         if ($form->{'iptoken'}) {
                   16108:             my $lonhost = $r->dir_config('lonHostID');
                   16109:             $initial_env{"user.noloadbalance"} = $lonhost;
                   16110:             $env{'user.noloadbalance'} = $lonhost;
                   16111:         }
                   16112: 
1.1075.2.120  raeburn  16113:         if ($form->{'noloadbalance'}) {
                   16114:             my @hosts = &Apache::lonnet::current_machine_ids();
                   16115:             my $hosthere = $form->{'noloadbalance'};
                   16116:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   16117:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   16118:                 $env{'user.noloadbalance'} = $hosthere;
                   16119:             }
                   16120:         }
                   16121: 
1.1016    raeburn  16122:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  16123:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   16124:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  16125: 
1.1075.2.125  raeburn  16126:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   16127:                 $userenv{'availabletools.'.$tool} = 
                   16128:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16129:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   16130:             }
1.724     raeburn  16131: 
1.1075.2.125  raeburn  16132:             foreach my $crstype ('official','unofficial','community','textbook') {
                   16133:                 $userenv{'canrequest.'.$crstype} =
                   16134:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   16135:                                                       'reload','requestcourses',
                   16136:                                                       \%userenv,\%domdef,\%is_adv);
                   16137:             }
1.765     raeburn  16138: 
1.1075.2.125  raeburn  16139:             $userenv{'canrequest.author'} =
                   16140:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16141:                                                   'reload','requestauthor',
                   16142:                                                   \%userenv,\%domdef,\%is_adv);
                   16143:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16144:                                                  $domain,$username);
                   16145:             my $reqstatus = $reqauthor{'author_status'};
                   16146:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   16147:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   16148:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16149:                                                       $reqauthor{'author'}{'timestamp'};
                   16150:                 }
1.1075.2.14  raeburn  16151:             }
                   16152:         }
                   16153: 
1.462     albertel 16154: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16155: 
1.462     albertel 16156: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16157: 		 &GDBM_WRCREAT(),0640)) {
                   16158: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16159: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16160: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16161:             if (ref($firstaccenv) eq 'HASH') {
                   16162:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16163:             }
                   16164:             if (ref($timerintenv) eq 'HASH') {
                   16165:                 &_add_to_env(\%disk_env,$timerintenv);
                   16166:             }
1.463     albertel 16167: 	    if (ref($args->{'extra_env'})) {
                   16168: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16169: 	    }
1.462     albertel 16170: 	    untie(%disk_env);
                   16171: 	} else {
1.705     tempelho 16172: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16173: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16174: 	    return 'error: '.$!;
                   16175: 	}
                   16176:     }
                   16177:     $env{'request.role'}='cm';
                   16178:     $env{'request.role.adv'}=$env{'user.adv'};
                   16179:     $env{'browser.type'}=$clientbrowser;
                   16180: 
                   16181:     return $cookie;
                   16182: 
                   16183: }
                   16184: 
                   16185: sub _add_to_env {
                   16186:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16187:     if (ref($env_data) eq 'HASH') {
                   16188:         while (my ($key,$value) = each(%$env_data)) {
                   16189: 	    $idf->{$prefix.$key} = $value;
                   16190: 	    $env{$prefix.$key}   = $value;
                   16191:         }
1.462     albertel 16192:     }
                   16193: }
                   16194: 
1.685     tempelho 16195: # --- Get the symbolic name of a problem and the url
                   16196: sub get_symb {
                   16197:     my ($request,$silent) = @_;
1.726     raeburn  16198:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16199:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16200:     if ($symb eq '') {
                   16201:         if (!$silent) {
1.1071    raeburn  16202:             if (ref($request)) { 
                   16203:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16204:             }
1.685     tempelho 16205:             return ();
                   16206:         }
                   16207:     }
                   16208:     &Apache::lonenc::check_decrypt(\$symb);
                   16209:     return ($symb);
                   16210: }
                   16211: 
                   16212: # --------------------------------------------------------------Get annotation
                   16213: 
                   16214: sub get_annotation {
                   16215:     my ($symb,$enc) = @_;
                   16216: 
                   16217:     my $key = $symb;
                   16218:     if (!$enc) {
                   16219:         $key =
                   16220:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16221:     }
                   16222:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16223:     return $annotation{$key};
                   16224: }
                   16225: 
                   16226: sub clean_symb {
1.731     raeburn  16227:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16228: 
                   16229:     &Apache::lonenc::check_decrypt(\$symb);
                   16230:     my $enc = $env{'request.enc'};
1.731     raeburn  16231:     if ($delete_enc) {
1.730     raeburn  16232:         delete($env{'request.enc'});
                   16233:     }
1.685     tempelho 16234: 
                   16235:     return ($symb,$enc);
                   16236: }
1.462     albertel 16237: 
1.1075.2.69  raeburn  16238: ############################################################
                   16239: ############################################################
                   16240: 
                   16241: =pod
                   16242: 
                   16243: =head1 Routines for building display used to search for courses
                   16244: 
                   16245: 
                   16246: =over 4
                   16247: 
                   16248: =item * &build_filters()
                   16249: 
                   16250: Create markup for a table used to set filters to use when selecting
                   16251: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16252: and quotacheck.pl
                   16253: 
                   16254: 
                   16255: Inputs:
                   16256: 
                   16257: filterlist - anonymous array of fields to include as potential filters
                   16258: 
                   16259: crstype - course type
                   16260: 
                   16261: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16262:               to pop-open a course selector (will contain "extra element").
                   16263: 
                   16264: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16265: 
                   16266: filter - anonymous hash of criteria and their values
                   16267: 
                   16268: action - form action
                   16269: 
                   16270: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16271: 
                   16272: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   16273: 
                   16274: cloneruname - username of owner of new course who wants to clone
                   16275: 
                   16276: clonerudom - domain of owner of new course who wants to clone
                   16277: 
                   16278: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   16279: 
                   16280: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16281: 
                   16282: codedom - domain
                   16283: 
                   16284: formname - value of form element named "form".
                   16285: 
                   16286: fixeddom - domain, if fixed.
                   16287: 
                   16288: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   16289: 
                   16290: cnameelement - name of form element in form on opener page which will receive title of selected course
                   16291: 
                   16292: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16293: 
                   16294: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16295: 
                   16296: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16297: 
                   16298: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16299: 
                   16300: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16301: 
                   16302: 
                   16303: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16304: 
                   16305: 
                   16306: Side Effects: None
                   16307: 
                   16308: =cut
                   16309: 
                   16310: # ---------------------------------------------- search for courses based on last activity etc.
                   16311: 
                   16312: sub build_filters {
                   16313:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16314:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16315:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16316:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16317:         $clonetext,$clonewarning) = @_;
                   16318:     my ($list,$jscript);
                   16319:     my $onchange = 'javascript:updateFilters(this)';
                   16320:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16321:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16322:         $typeselectform,$instcodetitle);
                   16323:     if ($formname eq '') {
                   16324:         $formname = $caller;
                   16325:     }
                   16326:     foreach my $item (@{$filterlist}) {
                   16327:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16328:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16329:             if ($item eq 'domainfilter') {
                   16330:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16331:             } elsif ($item eq 'coursefilter') {
                   16332:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16333:             } elsif ($item eq 'ownerfilter') {
                   16334:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16335:             } elsif ($item eq 'ownerdomfilter') {
                   16336:                 $filter->{'ownerdomfilter'} =
                   16337:                     &LONCAPA::clean_domain($filter->{$item});
                   16338:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16339:                                                        'ownerdomfilter',1);
                   16340:             } elsif ($item eq 'personfilter') {
                   16341:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16342:             } elsif ($item eq 'persondomfilter') {
                   16343:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16344:                                                         'persondomfilter',1);
                   16345:             } else {
                   16346:                 $filter->{$item} =~ s/\W//g;
                   16347:             }
                   16348:             if (!$filter->{$item}) {
                   16349:                 $filter->{$item} = '';
                   16350:             }
                   16351:         }
                   16352:         if ($item eq 'domainfilter') {
                   16353:             my $allow_blank = 1;
                   16354:             if ($formname eq 'portform') {
                   16355:                 $allow_blank=0;
                   16356:             } elsif ($formname eq 'studentform') {
                   16357:                 $allow_blank=0;
                   16358:             }
                   16359:             if ($fixeddom) {
                   16360:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16361:                                     ' value="'.$codedom.'" />'.
                   16362:                                     &Apache::lonnet::domain($codedom,'description');
                   16363:             } else {
                   16364:                 $domainselectform = &select_dom_form($filter->{$item},
                   16365:                                                      'domainfilter',
                   16366:                                                       $allow_blank,'',$onchange);
                   16367:             }
                   16368:         } else {
                   16369:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16370:         }
                   16371:     }
                   16372: 
                   16373:     # last course activity filter and selection
                   16374:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16375: 
                   16376:     # course created filter and selection
                   16377:     if (exists($filter->{'createdfilter'})) {
                   16378:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16379:     }
                   16380: 
                   16381:     my %lt = &Apache::lonlocal::texthash(
                   16382:                 'cac' => "$crstype Activity",
                   16383:                 'ccr' => "$crstype Created",
                   16384:                 'cde' => "$crstype Title",
                   16385:                 'cdo' => "$crstype Domain",
                   16386:                 'ins' => 'Institutional Code',
                   16387:                 'inc' => 'Institutional Categorization',
                   16388:                 'cow' => "$crstype Owner/Co-owner",
                   16389:                 'cop' => "$crstype Personnel Includes",
                   16390:                 'cog' => 'Type',
                   16391:              );
                   16392: 
                   16393:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16394:         my $typeval = 'Course';
                   16395:         if ($crstype eq 'Community') {
                   16396:             $typeval = 'Community';
                   16397:         }
                   16398:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16399:     } else {
                   16400:         $typeselectform =  '<select name="type" size="1"';
                   16401:         if ($onchange) {
                   16402:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16403:         }
                   16404:         $typeselectform .= '>'."\n";
                   16405:         foreach my $posstype ('Course','Community') {
                   16406:             $typeselectform.='<option value="'.$posstype.'"'.
                   16407:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   16408:         }
                   16409:         $typeselectform.="</select>";
                   16410:     }
                   16411: 
                   16412:     my ($cloneableonlyform,$cloneabletitle);
                   16413:     if (exists($filter->{'cloneableonly'})) {
                   16414:         my $cloneableon = '';
                   16415:         my $cloneableoff = ' checked="checked"';
                   16416:         if ($filter->{'cloneableonly'}) {
                   16417:             $cloneableon = $cloneableoff;
                   16418:             $cloneableoff = '';
                   16419:         }
                   16420:         $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>';
                   16421:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  16422:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  16423:         } else {
                   16424:             $cloneabletitle = &mt('Cloneable by you');
                   16425:         }
                   16426:     }
                   16427:     my $officialjs;
                   16428:     if ($crstype eq 'Course') {
                   16429:         if (exists($filter->{'instcodefilter'})) {
                   16430: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16431: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16432:             if ($codedom) {
                   16433:                 $officialjs = 1;
                   16434:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16435:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16436:                                                                   $officialjs,$codetitlesref);
                   16437:                 if ($jscript) {
                   16438:                     $jscript = '<script type="text/javascript">'."\n".
                   16439:                                '// <![CDATA['."\n".
                   16440:                                $jscript."\n".
                   16441:                                '// ]]>'."\n".
                   16442:                                '</script>'."\n";
                   16443:                 }
                   16444:             }
                   16445:             if ($instcodeform eq '') {
                   16446:                 $instcodeform =
                   16447:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16448:                     $list->{'instcodefilter'}.'" />';
                   16449:                 $instcodetitle = $lt{'ins'};
                   16450:             } else {
                   16451:                 $instcodetitle = $lt{'inc'};
                   16452:             }
                   16453:             if ($fixeddom) {
                   16454:                 $instcodetitle .= '<br />('.$codedom.')';
                   16455:             }
                   16456:         }
                   16457:     }
                   16458:     my $output = qq|
                   16459: <form method="post" name="filterpicker" action="$action">
                   16460: <input type="hidden" name="form" value="$formname" />
                   16461: |;
                   16462:     if ($formname eq 'modifycourse') {
                   16463:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16464:                    '<input type="hidden" name="prevphase" value="'.
                   16465:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  16466:     } elsif ($formname eq 'quotacheck') {
                   16467:         $output .= qq|
                   16468: <input type="hidden" name="sortby" value="" />
                   16469: <input type="hidden" name="sortorder" value="" />
                   16470: |;
                   16471:     } else {
1.1075.2.69  raeburn  16472:         my $name_input;
                   16473:         if ($cnameelement ne '') {
                   16474:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16475:                           $cnameelement.'" />';
                   16476:         }
                   16477:         $output .= qq|
                   16478: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16479: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   16480: $name_input
                   16481: $roleelement
                   16482: $multelement
                   16483: $typeelement
                   16484: |;
                   16485:         if ($formname eq 'portform') {
                   16486:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16487:         }
                   16488:     }
                   16489:     if ($fixeddom) {
                   16490:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16491:     }
                   16492:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16493:     if ($sincefilterform) {
                   16494:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16495:                   .$sincefilterform
                   16496:                   .&Apache::lonhtmlcommon::row_closure();
                   16497:     }
                   16498:     if ($createdfilterform) {
                   16499:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16500:                   .$createdfilterform
                   16501:                   .&Apache::lonhtmlcommon::row_closure();
                   16502:     }
                   16503:     if ($domainselectform) {
                   16504:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16505:                   .$domainselectform
                   16506:                   .&Apache::lonhtmlcommon::row_closure();
                   16507:     }
                   16508:     if ($typeselectform) {
                   16509:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16510:             $output .= $typeselectform;
                   16511:         } else {
                   16512:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16513:                       .$typeselectform
                   16514:                       .&Apache::lonhtmlcommon::row_closure();
                   16515:         }
                   16516:     }
                   16517:     if ($instcodeform) {
                   16518:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16519:                   .$instcodeform
                   16520:                   .&Apache::lonhtmlcommon::row_closure();
                   16521:     }
                   16522:     if (exists($filter->{'ownerfilter'})) {
                   16523:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16524:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16525:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16526:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16527:                    $ownerdomselectform.'</td></tr></table>'.
                   16528:                    &Apache::lonhtmlcommon::row_closure();
                   16529:     }
                   16530:     if (exists($filter->{'personfilter'})) {
                   16531:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16532:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16533:                    '<input type="text" name="personfilter" size="20" value="'.
                   16534:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16535:                    $persondomselectform.'</td></tr></table>'.
                   16536:                    &Apache::lonhtmlcommon::row_closure();
                   16537:     }
                   16538:     if (exists($filter->{'coursefilter'})) {
                   16539:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16540:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16541:                   .$list->{'coursefilter'}.'" />'
                   16542:                   .&Apache::lonhtmlcommon::row_closure();
                   16543:     }
                   16544:     if ($cloneableonlyform) {
                   16545:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16546:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16547:     }
                   16548:     if (exists($filter->{'descriptfilter'})) {
                   16549:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16550:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16551:                   .$list->{'descriptfilter'}.'" />'
                   16552:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16553:     }
                   16554:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16555:                '<input type="hidden" name="updater" value="" />'."\n".
                   16556:                '<input type="submit" name="gosearch" value="'.
                   16557:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16558:     return $jscript.$clonewarning.$output;
                   16559: }
                   16560: 
                   16561: =pod
                   16562: 
                   16563: =item * &timebased_select_form()
                   16564: 
                   16565: Create markup for a dropdown list used to select a time-based
                   16566: filter e.g., Course Activity, Course Created, when searching for courses
                   16567: or communities
                   16568: 
                   16569: Inputs:
                   16570: 
                   16571: item - name of form element (sincefilter or createdfilter)
                   16572: 
                   16573: filter - anonymous hash of criteria and their values
                   16574: 
                   16575: Returns: HTML for a select box contained a blank, then six time selections,
                   16576:          with value set in incoming form variables currently selected.
                   16577: 
                   16578: Side Effects: None
                   16579: 
                   16580: =cut
                   16581: 
                   16582: sub timebased_select_form {
                   16583:     my ($item,$filter) = @_;
                   16584:     if (ref($filter) eq 'HASH') {
                   16585:         $filter->{$item} =~ s/[^\d-]//g;
                   16586:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16587:         return &select_form(
                   16588:                             $filter->{$item},
                   16589:                             $item,
                   16590:                             {      '-1' => '',
                   16591:                                 '86400' => &mt('today'),
                   16592:                                '604800' => &mt('last week'),
                   16593:                               '2592000' => &mt('last month'),
                   16594:                               '7776000' => &mt('last three months'),
                   16595:                              '15552000' => &mt('last six months'),
                   16596:                              '31104000' => &mt('last year'),
                   16597:                     'select_form_order' =>
                   16598:                            ['-1','86400','604800','2592000','7776000',
                   16599:                             '15552000','31104000']});
                   16600:     }
                   16601: }
                   16602: 
                   16603: =pod
                   16604: 
                   16605: =item * &js_changer()
                   16606: 
                   16607: Create script tag containing Javascript used to submit course search form
                   16608: when course type or domain is changed, and also to hide 'Searching ...' on
                   16609: page load completion for page showing search result.
                   16610: 
                   16611: Inputs: None
                   16612: 
                   16613: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   16614: 
                   16615: Side Effects: None
                   16616: 
                   16617: =cut
                   16618: 
                   16619: sub js_changer {
                   16620:     return <<ENDJS;
                   16621: <script type="text/javascript">
                   16622: // <![CDATA[
                   16623: function updateFilters(caller) {
                   16624:     if (typeof(caller) != "undefined") {
                   16625:         document.filterpicker.updater.value = caller.name;
                   16626:     }
                   16627:     document.filterpicker.submit();
                   16628: }
                   16629: 
                   16630: function hideSearching() {
                   16631:     if (document.getElementById('searching')) {
                   16632:         document.getElementById('searching').style.display = 'none';
                   16633:     }
                   16634:     return;
                   16635: }
                   16636: 
                   16637: // ]]>
                   16638: </script>
                   16639: 
                   16640: ENDJS
                   16641: }
                   16642: 
                   16643: =pod
                   16644: 
                   16645: =item * &search_courses()
                   16646: 
                   16647: Process selected filters form course search form and pass to lonnet::courseiddump
                   16648: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16649: 
                   16650: Inputs:
                   16651: 
                   16652: dom - domain being searched
                   16653: 
                   16654: type - course type ('Course' or 'Community' or '.' if any).
                   16655: 
                   16656: filter - anonymous hash of criteria and their values
                   16657: 
                   16658: numtitles - for institutional codes - number of categories
                   16659: 
                   16660: cloneruname - optional username of new course owner
                   16661: 
                   16662: clonerudom - optional domain of new course owner
                   16663: 
1.1075.2.95  raeburn  16664: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  16665:             (used when DC is using course creation form)
                   16666: 
                   16667: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16668: 
1.1075.2.95  raeburn  16669: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16670:            (and so can clone automatically)
                   16671: 
                   16672: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16673: 
                   16674: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   16675:               courses to clone
1.1075.2.69  raeburn  16676: 
                   16677: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16678: 
                   16679: 
                   16680: Side Effects: None
                   16681: 
                   16682: =cut
                   16683: 
                   16684: 
                   16685: sub search_courses {
1.1075.2.95  raeburn  16686:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16687:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  16688:     my (%courses,%showcourses,$cloner);
                   16689:     if (($filter->{'ownerfilter'} ne '') ||
                   16690:         ($filter->{'ownerdomfilter'} ne '')) {
                   16691:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16692:                                        $filter->{'ownerdomfilter'};
                   16693:     }
                   16694:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16695:         if (!$filter->{$item}) {
                   16696:             $filter->{$item}='.';
                   16697:         }
                   16698:     }
                   16699:     my $now = time;
                   16700:     my $timefilter =
                   16701:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16702:     my ($createdbefore,$createdafter);
                   16703:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16704:         $createdbefore = $now;
                   16705:         $createdafter = $now-$filter->{'createdfilter'};
                   16706:     }
                   16707:     my ($instcodefilter,$regexpok);
                   16708:     if ($numtitles) {
                   16709:         if ($env{'form.official'} eq 'on') {
                   16710:             $instcodefilter =
                   16711:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16712:             $regexpok = 1;
                   16713:         } elsif ($env{'form.official'} eq 'off') {
                   16714:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16715:             unless ($instcodefilter eq '') {
                   16716:                 $regexpok = -1;
                   16717:             }
                   16718:         }
                   16719:     } else {
                   16720:         $instcodefilter = $filter->{'instcodefilter'};
                   16721:     }
                   16722:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16723:     if ($type eq '') { $type = '.'; }
                   16724: 
                   16725:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16726:         $cloner = $cloneruname.':'.$clonerudom;
                   16727:     }
                   16728:     %courses = &Apache::lonnet::courseiddump($dom,
                   16729:                                              $filter->{'descriptfilter'},
                   16730:                                              $timefilter,
                   16731:                                              $instcodefilter,
                   16732:                                              $filter->{'combownerfilter'},
                   16733:                                              $filter->{'coursefilter'},
                   16734:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  16735:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  16736:                                              $filter->{'cloneableonly'},
                   16737:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  16738:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  16739:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16740:         my $ccrole;
                   16741:         if ($type eq 'Community') {
                   16742:             $ccrole = 'co';
                   16743:         } else {
                   16744:             $ccrole = 'cc';
                   16745:         }
                   16746:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16747:                                                      $filter->{'persondomfilter'},
                   16748:                                                      'userroles',undef,
                   16749:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16750:                                                      $dom);
                   16751:         foreach my $role (keys(%rolehash)) {
                   16752:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16753:             my $cid = $cdom.'_'.$cnum;
                   16754:             if (exists($courses{$cid})) {
                   16755:                 if (ref($courses{$cid}) eq 'HASH') {
                   16756:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16757:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  16758:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  16759:                         }
                   16760:                     } else {
                   16761:                         $courses{$cid}{roles} = [$courserole];
                   16762:                     }
                   16763:                     $showcourses{$cid} = $courses{$cid};
                   16764:                 }
                   16765:             }
                   16766:         }
                   16767:         %courses = %showcourses;
                   16768:     }
                   16769:     return %courses;
                   16770: }
                   16771: 
                   16772: =pod
                   16773: 
                   16774: =back
                   16775: 
1.1075.2.88  raeburn  16776: =head1 Routines for version requirements for current course.
                   16777: 
                   16778: =over 4
                   16779: 
                   16780: =item * &check_release_required()
                   16781: 
                   16782: Compares required LON-CAPA version with version on server, and
                   16783: if required version is newer looks for a server with the required version.
                   16784: 
                   16785: Looks first at servers in user's owen domain; if none suitable, looks at
                   16786: servers in course's domain are permitted to host sessions for user's domain.
                   16787: 
                   16788: Inputs:
                   16789: 
                   16790: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16791: 
                   16792: $courseid - Course ID of current course
                   16793: 
                   16794: $rolecode - User's current role in course (for switchserver query string).
                   16795: 
                   16796: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16797: 
                   16798: 
                   16799: Returns:
                   16800: 
                   16801: $switchserver - query string tp append to /adm/switchserver call (if
                   16802:                 current server's LON-CAPA version is too old.
                   16803: 
                   16804: $warning - Message is displayed if no suitable server could be found.
                   16805: 
                   16806: =cut
                   16807: 
                   16808: sub check_release_required {
                   16809:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16810:     my ($switchserver,$warning);
                   16811:     if ($required ne '') {
                   16812:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16813:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16814:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16815:             my $otherserver;
                   16816:             if (($major eq '' && $minor eq '') ||
                   16817:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16818:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16819:                 my $switchlcrev =
                   16820:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16821:                                                            $userdomserver);
                   16822:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16823:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16824:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16825:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16826:                     if ($cdom ne $env{'user.domain'}) {
                   16827:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16828:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16829:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16830:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16831:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16832:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16833:                         my $canhost =
                   16834:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16835:                                                               $coursedomserver,
                   16836:                                                               $remoterev,
                   16837:                                                               $udomdefaults{'remotesessions'},
                   16838:                                                               $defdomdefaults{'hostedsessions'});
                   16839: 
                   16840:                         if ($canhost) {
                   16841:                             $otherserver = $coursedomserver;
                   16842:                         } else {
                   16843:                             $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.");
                   16844:                         }
                   16845:                     } else {
                   16846:                         $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).");
                   16847:                     }
                   16848:                 } else {
                   16849:                     $otherserver = $userdomserver;
                   16850:                 }
                   16851:             }
                   16852:             if ($otherserver ne '') {
                   16853:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16854:             }
                   16855:         }
                   16856:     }
                   16857:     return ($switchserver,$warning);
                   16858: }
                   16859: 
                   16860: =pod
                   16861: 
                   16862: =item * &check_release_result()
                   16863: 
                   16864: Inputs:
                   16865: 
                   16866: $switchwarning - Warning message if no suitable server found to host session.
                   16867: 
                   16868: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16869:                 and current role.
                   16870: 
                   16871: Returns: HTML to display with information about requirement to switch server.
                   16872:          Either displaying warning with link to Roles/Courses screen or
                   16873:          display link to switchserver.
                   16874: 
1.1075.2.69  raeburn  16875: =cut
                   16876: 
1.1075.2.88  raeburn  16877: sub check_release_result {
                   16878:     my ($switchwarning,$switchserver) = @_;
                   16879:     my $output = &start_page('Selected course unavailable on this server').
                   16880:                  '<p class="LC_warning">';
                   16881:     if ($switchwarning) {
                   16882:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16883:         if (&show_course()) {
                   16884:             $output .= &mt('Display courses');
                   16885:         } else {
                   16886:             $output .= &mt('Display roles');
                   16887:         }
                   16888:         $output .= '</a>';
                   16889:     } elsif ($switchserver) {
                   16890:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16891:                    '<br />'.
                   16892:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16893:                    &mt('Switch Server').
                   16894:                    '</a>';
                   16895:     }
                   16896:     $output .= '</p>'.&end_page();
                   16897:     return $output;
                   16898: }
                   16899: 
                   16900: =pod
                   16901: 
                   16902: =item * &needs_coursereinit()
                   16903: 
                   16904: Determine if course contents stored for user's session needs to be
                   16905: refreshed, because content has changed since "Big Hash" last tied.
                   16906: 
                   16907: Check for change is made if time last checked is more than 10 minutes ago
                   16908: (by default).
                   16909: 
                   16910: Inputs:
                   16911: 
                   16912: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16913: 
                   16914: $interval (optional) - Time which may elapse (in s) between last check for content
                   16915:                        change in current course. (default: 600 s).
                   16916: 
                   16917: Returns: an array; first element is:
                   16918: 
                   16919: =over 4
                   16920: 
                   16921: 'switch' - if content updates mean user's session
                   16922:            needs to be switched to a server running a newer LON-CAPA version
                   16923: 
                   16924: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16925:            on current server hosting user's session
                   16926: 
                   16927: ''       - if no action required.
                   16928: 
                   16929: =back
                   16930: 
                   16931: If first item element is 'switch':
                   16932: 
                   16933: second item is $switchwarning - Warning message if no suitable server found to host session.
                   16934: 
                   16935: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16936:                               and current role.
                   16937: 
                   16938: otherwise: no other elements returned.
                   16939: 
                   16940: =back
                   16941: 
                   16942: =cut
                   16943: 
                   16944: sub needs_coursereinit {
                   16945:     my ($loncaparev,$interval) = @_;
                   16946:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16947:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16948:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16949:     my $now = time;
                   16950:     if ($interval eq '') {
                   16951:         $interval = 600;
                   16952:     }
                   16953:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16954:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16955:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16956:         if ($lastchange > $env{'request.course.tied'}) {
                   16957:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16958:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16959:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16960:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16961:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16962:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16963:                     my ($switchserver,$switchwarning) =
                   16964:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16965:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16966:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16967:                         return ('switch',$switchwarning,$switchserver);
                   16968:                     }
                   16969:                 }
                   16970:             }
                   16971:             return ('update');
                   16972:         }
                   16973:     }
                   16974:     return ();
                   16975: }
1.1075.2.69  raeburn  16976: 
1.1075.2.11  raeburn  16977: sub update_content_constraints {
                   16978:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16979:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16980:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16981:     my %checkresponsetypes;
                   16982:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   16983:         my ($item,$name,$value) = split(/:/,$key);
                   16984:         if ($item eq 'resourcetag') {
                   16985:             if ($name eq 'responsetype') {
                   16986:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16987:             }
                   16988:         }
                   16989:     }
                   16990:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16991:     if (defined($navmap)) {
                   16992:         my %allresponses;
                   16993:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16994:             my %responses = $res->responseTypes();
                   16995:             foreach my $key (keys(%responses)) {
                   16996:                 next unless(exists($checkresponsetypes{$key}));
                   16997:                 $allresponses{$key} += $responses{$key};
                   16998:             }
                   16999:         }
                   17000:         foreach my $key (keys(%allresponses)) {
                   17001:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   17002:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17003:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17004:             }
                   17005:         }
                   17006:         undef($navmap);
                   17007:     }
                   17008:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   17009:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   17010:     }
                   17011:     return;
                   17012: }
                   17013: 
1.1075.2.27  raeburn  17014: sub allmaps_incourse {
                   17015:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17016:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   17017:         $cid = $env{'request.course.id'};
                   17018:         $cdom = $env{'course.'.$cid.'.domain'};
                   17019:         $cnum = $env{'course.'.$cid.'.num'};
                   17020:         $chome = $env{'course.'.$cid.'.home'};
                   17021:     }
                   17022:     my %allmaps = ();
                   17023:     my $lastchange =
                   17024:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17025:     if ($lastchange > $env{'request.course.tied'}) {
                   17026:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   17027:         unless ($ferr) {
                   17028:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   17029:         }
                   17030:     }
                   17031:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17032:     if (defined($navmap)) {
                   17033:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   17034:             $allmaps{$res->src()} = 1;
                   17035:         }
                   17036:     }
                   17037:     return \%allmaps;
                   17038: }
                   17039: 
1.1075.2.11  raeburn  17040: sub parse_supplemental_title {
                   17041:     my ($title) = @_;
                   17042: 
                   17043:     my ($foldertitle,$renametitle);
                   17044:     if ($title =~ /&amp;&amp;&amp;/) {
                   17045:         $title = &HTML::Entites::decode($title);
                   17046:     }
                   17047:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   17048:         $renametitle=$4;
                   17049:         my ($time,$uname,$udom) = ($1,$2,$3);
                   17050:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   17051:         my $name =  &plainname($uname,$udom);
                   17052:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   17053:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   17054:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   17055:             $name.': <br />'.$foldertitle;
                   17056:     }
                   17057:     if (wantarray) {
                   17058:         return ($title,$foldertitle,$renametitle);
                   17059:     }
                   17060:     return $title;
                   17061: }
                   17062: 
1.1075.2.43  raeburn  17063: sub recurse_supplemental {
                   17064:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   17065:     if ($suppmap) {
                   17066:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   17067:         if ($fatal) {
                   17068:             $errors ++;
                   17069:         } else {
                   17070:             if ($#LONCAPA::map::resources > 0) {
                   17071:                 foreach my $res (@LONCAPA::map::resources) {
                   17072:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   17073:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  17074:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   17075:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  17076:                         } else {
                   17077:                             $numfiles ++;
                   17078:                         }
                   17079:                     }
                   17080:                 }
                   17081:             }
                   17082:         }
                   17083:     }
                   17084:     return ($numfiles,$errors);
                   17085: }
                   17086: 
1.1075.2.18  raeburn  17087: sub symb_to_docspath {
1.1075.2.119  raeburn  17088:     my ($symb,$navmapref) = @_;
                   17089:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  17090:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   17091:     if ($resurl=~/\.(sequence|page)$/) {
                   17092:         $mapurl=$resurl;
                   17093:     } elsif ($resurl eq 'adm/navmaps') {
                   17094:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   17095:     }
                   17096:     my $mapresobj;
1.1075.2.119  raeburn  17097:     unless (ref($$navmapref)) {
                   17098:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   17099:     }
                   17100:     if (ref($$navmapref)) {
                   17101:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  17102:     }
                   17103:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   17104:     my $type=$2;
                   17105:     my $path;
                   17106:     if (ref($mapresobj)) {
                   17107:         my $pcslist = $mapresobj->map_hierarchy();
                   17108:         if ($pcslist ne '') {
                   17109:             foreach my $pc (split(/,/,$pcslist)) {
                   17110:                 next if ($pc <= 1);
1.1075.2.119  raeburn  17111:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  17112:                 if (ref($res)) {
                   17113:                     my $thisurl = $res->src();
                   17114:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   17115:                     my $thistitle = $res->title();
                   17116:                     $path .= '&'.
                   17117:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  17118:                              &escape($thistitle).
1.1075.2.18  raeburn  17119:                              ':'.$res->randompick().
                   17120:                              ':'.$res->randomout().
                   17121:                              ':'.$res->encrypted().
                   17122:                              ':'.$res->randomorder().
                   17123:                              ':'.$res->is_page();
                   17124:                 }
                   17125:             }
                   17126:         }
                   17127:         $path =~ s/^\&//;
                   17128:         my $maptitle = $mapresobj->title();
                   17129:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  17130:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  17131:         }
                   17132:         $path .= (($path ne '')? '&' : '').
                   17133:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  17134:                  &escape($maptitle).
1.1075.2.18  raeburn  17135:                  ':'.$mapresobj->randompick().
                   17136:                  ':'.$mapresobj->randomout().
                   17137:                  ':'.$mapresobj->encrypted().
                   17138:                  ':'.$mapresobj->randomorder().
                   17139:                  ':'.$mapresobj->is_page();
                   17140:     } else {
                   17141:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17142:         my $ispage = (($type eq 'page')? 1 : '');
                   17143:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  17144:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  17145:         }
                   17146:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  17147:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  17148:     }
                   17149:     unless ($mapurl eq 'default') {
                   17150:         $path = 'default&'.
1.1075.2.46  raeburn  17151:                 &escape('Main Content').
1.1075.2.18  raeburn  17152:                 ':::::&'.$path;
                   17153:     }
                   17154:     return $path;
                   17155: }
                   17156: 
1.1075.2.14  raeburn  17157: sub captcha_display {
1.1075.2.137  raeburn  17158:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  17159:     my ($output,$error);
1.1075.2.107  raeburn  17160:     my ($captcha,$pubkey,$privkey,$version) =
1.1075.2.137  raeburn  17161:         &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  17162:     if ($captcha eq 'original') {
                   17163:         $output = &create_captcha();
                   17164:         unless ($output) {
                   17165:             $error = 'captcha';
                   17166:         }
                   17167:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  17168:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  17169:         unless ($output) {
                   17170:             $error = 'recaptcha';
                   17171:         }
                   17172:     }
1.1075.2.107  raeburn  17173:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  17174: }
                   17175: 
                   17176: sub captcha_response {
1.1075.2.137  raeburn  17177:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  17178:     my ($captcha_chk,$captcha_error);
1.1075.2.137  raeburn  17179:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  17180:     if ($captcha eq 'original') {
                   17181:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17182:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  17183:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  17184:     } else {
                   17185:         $captcha_chk = 1;
                   17186:     }
                   17187:     return ($captcha_chk,$captcha_error);
                   17188: }
                   17189: 
                   17190: sub get_captcha_config {
1.1075.2.137  raeburn  17191:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1075.2.107  raeburn  17192:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  17193:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17194:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17195:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17196:     if ($context eq 'usercreation') {
                   17197:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17198:         if (ref($domconfig{$context}) eq 'HASH') {
                   17199:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17200:             if (ref($hashtocheck) eq 'HASH') {
                   17201:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17202:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17203:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17204:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17205:                     }
                   17206:                     if ($privkey && $pubkey) {
                   17207:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  17208:                         $version = $hashtocheck->{'recaptchaversion'};
                   17209:                         if ($version ne '2') {
                   17210:                             $version = 1;
                   17211:                         }
1.1075.2.14  raeburn  17212:                     } else {
                   17213:                         $captcha = 'original';
                   17214:                     }
                   17215:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17216:                     $captcha = 'original';
                   17217:                 }
                   17218:             }
                   17219:         } else {
                   17220:             $captcha = 'captcha';
                   17221:         }
                   17222:     } elsif ($context eq 'login') {
                   17223:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17224:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17225:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17226:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   17227:             if ($privkey && $pubkey) {
                   17228:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  17229:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17230:                 if ($version ne '2') {
                   17231:                     $version = 1;
                   17232:                 }
1.1075.2.14  raeburn  17233:             } else {
                   17234:                 $captcha = 'original';
                   17235:             }
                   17236:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17237:             $captcha = 'original';
                   17238:         }
1.1075.2.137  raeburn  17239:     } elsif ($context eq 'passwords') {
                   17240:         if ($dom_in_effect) {
                   17241:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   17242:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   17243:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   17244:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   17245:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   17246:                 }
                   17247:                 if ($privkey && $pubkey) {
                   17248:                     $captcha = 'recaptcha';
                   17249:                     $version = $passwdconf{'recaptchaversion'};
                   17250:                     if ($version ne '2') {
                   17251:                         $version = 1;
                   17252:                     }
                   17253:                 } else {
                   17254:                     $captcha = 'original';
                   17255:                 }
                   17256:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   17257:                 $captcha = 'original';
                   17258:             }
                   17259:         }
1.1075.2.14  raeburn  17260:     }
1.1075.2.107  raeburn  17261:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  17262: }
                   17263: 
                   17264: sub create_captcha {
                   17265:     my %captcha_params = &captcha_settings();
                   17266:     my ($output,$maxtries,$tries) = ('',10,0);
                   17267:     while ($tries < $maxtries) {
                   17268:         $tries ++;
                   17269:         my $captcha = Authen::Captcha->new (
                   17270:                                            output_folder => $captcha_params{'output_dir'},
                   17271:                                            data_folder   => $captcha_params{'db_dir'},
                   17272:                                           );
                   17273:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17274: 
                   17275:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17276:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1075.2.158  raeburn  17277:                       '<span class="LC_nobreak">'.
1.1075.2.14  raeburn  17278:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  17279:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
1.1075.2.158  raeburn  17280:                       '</span><br />'.
1.1075.2.66  raeburn  17281:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  17282:             last;
                   17283:         }
                   17284:     }
1.1075.2.158  raeburn  17285:     if ($output eq '') {
                   17286:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   17287:     }
1.1075.2.14  raeburn  17288:     return $output;
                   17289: }
                   17290: 
                   17291: sub captcha_settings {
                   17292:     my %captcha_params = (
                   17293:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17294:                            www_output_dir => "/captchaspool",
                   17295:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17296:                            numchars       => '5',
                   17297:                          );
                   17298:     return %captcha_params;
                   17299: }
                   17300: 
                   17301: sub check_captcha {
                   17302:     my ($captcha_chk,$captcha_error);
                   17303:     my $code = $env{'form.code'};
                   17304:     my $md5sum = $env{'form.crypt'};
                   17305:     my %captcha_params = &captcha_settings();
                   17306:     my $captcha = Authen::Captcha->new(
                   17307:                       output_folder => $captcha_params{'output_dir'},
                   17308:                       data_folder   => $captcha_params{'db_dir'},
                   17309:                   );
1.1075.2.26  raeburn  17310:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  17311:     my %captcha_hash = (
                   17312:                         0       => 'Code not checked (file error)',
                   17313:                        -1      => 'Failed: code expired',
                   17314:                        -2      => 'Failed: invalid code (not in database)',
                   17315:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17316:     );
                   17317:     if ($captcha_chk != 1) {
                   17318:         $captcha_error = $captcha_hash{$captcha_chk}
                   17319:     }
                   17320:     return ($captcha_chk,$captcha_error);
                   17321: }
                   17322: 
                   17323: sub create_recaptcha {
1.1075.2.107  raeburn  17324:     my ($pubkey,$version) = @_;
                   17325:     if ($version >= 2) {
1.1075.2.158  raeburn  17326:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   17327:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1075.2.107  raeburn  17328:     } else {
                   17329:         my $use_ssl;
                   17330:         if ($ENV{'SERVER_PORT'} == 443) {
                   17331:             $use_ssl = 1;
                   17332:         }
                   17333:         my $captcha = Captcha::reCAPTCHA->new;
                   17334:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17335:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17336:                &mt('If the text is hard to read, [_1] will replace them.',
                   17337:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17338:                '<br /><br />';
                   17339:      }
1.1075.2.14  raeburn  17340: }
                   17341: 
                   17342: sub check_recaptcha {
1.1075.2.107  raeburn  17343:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  17344:     my $captcha_chk;
1.1075.2.150  raeburn  17345:     my $ip = &Apache::lonnet::get_requestor_ip(); 
1.1075.2.107  raeburn  17346:     if ($version >= 2) {
                   17347:         my $ua = LWP::UserAgent->new;
                   17348:         $ua->timeout(10);
                   17349:         my %info = (
                   17350:                      secret   => $privkey,
                   17351:                      response => $env{'form.g-recaptcha-response'},
1.1075.2.150  raeburn  17352:                      remoteip => $ip,
1.1075.2.107  raeburn  17353:                    );
                   17354:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   17355:         if ($response->is_success)  {
                   17356:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17357:             if (ref($data) eq 'HASH') {
                   17358:                 if ($data->{'success'}) {
                   17359:                     $captcha_chk = 1;
                   17360:                 }
                   17361:             }
                   17362:         }
                   17363:     } else {
                   17364:         my $captcha = Captcha::reCAPTCHA->new;
                   17365:         my $captcha_result =
                   17366:             $captcha->check_answer(
                   17367:                                     $privkey,
1.1075.2.150  raeburn  17368:                                     $ip,
1.1075.2.107  raeburn  17369:                                     $env{'form.recaptcha_challenge_field'},
                   17370:                                     $env{'form.recaptcha_response_field'},
                   17371:                                   );
                   17372:         if ($captcha_result->{is_valid}) {
                   17373:             $captcha_chk = 1;
                   17374:         }
1.1075.2.14  raeburn  17375:     }
                   17376:     return $captcha_chk;
                   17377: }
                   17378: 
1.1075.2.64  raeburn  17379: sub emailusername_info {
1.1075.2.103  raeburn  17380:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  17381:     my %titles = &Apache::lonlocal::texthash (
                   17382:                      lastname      => 'Last Name',
                   17383:                      firstname     => 'First Name',
                   17384:                      institution   => 'School/college/university',
                   17385:                      location      => "School's city, state/province, country",
                   17386:                      web           => "School's web address",
                   17387:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  17388:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  17389:                  );
                   17390:     return (\@fields,\%titles);
                   17391: }
                   17392: 
1.1075.2.56  raeburn  17393: sub cleanup_html {
                   17394:     my ($incoming) = @_;
                   17395:     my $outgoing;
                   17396:     if ($incoming ne '') {
                   17397:         $outgoing = $incoming;
                   17398:         $outgoing =~ s/;/&#059;/g;
                   17399:         $outgoing =~ s/\#/&#035;/g;
                   17400:         $outgoing =~ s/\&/&#038;/g;
                   17401:         $outgoing =~ s/</&#060;/g;
                   17402:         $outgoing =~ s/>/&#062;/g;
                   17403:         $outgoing =~ s/\(/&#040/g;
                   17404:         $outgoing =~ s/\)/&#041;/g;
                   17405:         $outgoing =~ s/"/&#034;/g;
                   17406:         $outgoing =~ s/'/&#039;/g;
                   17407:         $outgoing =~ s/\$/&#036;/g;
                   17408:         $outgoing =~ s{/}{&#047;}g;
                   17409:         $outgoing =~ s/=/&#061;/g;
                   17410:         $outgoing =~ s/\\/&#092;/g
                   17411:     }
                   17412:     return $outgoing;
                   17413: }
                   17414: 
1.1075.2.74  raeburn  17415: # Checks for critical messages and returns a redirect url if one exists.
                   17416: # $interval indicates how often to check for messages.
                   17417: sub critical_redirect {
                   17418:     my ($interval) = @_;
1.1075.2.158  raeburn  17419:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   17420:         return ();
                   17421:     }
1.1075.2.74  raeburn  17422:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   17423:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   17424:                                         $env{'user.name'});
                   17425:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   17426:         my $redirecturl;
                   17427:         if ($what[0]) {
1.1075.2.158  raeburn  17428:             if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1075.2.74  raeburn  17429:                 $redirecturl='/adm/email?critical=display';
                   17430:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17431:                 return (1, $url);
                   17432:             }
                   17433:         }
                   17434:     }
                   17435:     return ();
                   17436: }
                   17437: 
1.1075.2.64  raeburn  17438: # Use:
                   17439: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17440: #
                   17441: ##################################################
                   17442: #          password associated functions         #
                   17443: ##################################################
                   17444: sub des_keys {
                   17445:     # Make a new key for DES encryption.
                   17446:     # Each key has two parts which are returned separately.
                   17447:     # Please note:  Each key must be passed through the &hex function
                   17448:     # before it is output to the web browser.  The hex versions cannot
                   17449:     # be used to decrypt.
                   17450:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17451:                 '8','9','a','b','c','d','e','f');
                   17452:     my $lkey='';
                   17453:     for (0..7) {
                   17454:         $lkey.=$hexstr[rand(15)];
                   17455:     }
                   17456:     my $ukey='';
                   17457:     for (0..7) {
                   17458:         $ukey.=$hexstr[rand(15)];
                   17459:     }
                   17460:     return ($lkey,$ukey);
                   17461: }
                   17462: 
                   17463: sub des_decrypt {
                   17464:     my ($key,$cyphertext) = @_;
                   17465:     my $keybin=pack("H16",$key);
                   17466:     my $cypher;
                   17467:     if ($Crypt::DES::VERSION>=2.03) {
                   17468:         $cypher=new Crypt::DES $keybin;
                   17469:     } else {
                   17470:         $cypher=new DES $keybin;
                   17471:     }
1.1075.2.106  raeburn  17472:     my $plaintext='';
                   17473:     my $cypherlength = length($cyphertext);
                   17474:     my $numchunks = int($cypherlength/32);
                   17475:     for (my $j=0; $j<$numchunks; $j++) {
                   17476:         my $start = $j*32;
                   17477:         my $cypherblock = substr($cyphertext,$start,32);
                   17478:         my $chunk =
                   17479:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17480:         $chunk .=
                   17481:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17482:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17483:         $plaintext .= $chunk;
                   17484:     }
1.1075.2.64  raeburn  17485:     return $plaintext;
                   17486: }
                   17487: 
1.1075.2.135  raeburn  17488: sub is_nonframeable {
                   17489:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   17490:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
                   17491:     return if (($remprotocol eq '') || ($remhost eq ''));
                   17492: 
                   17493:     $remprotocol = lc($remprotocol);
                   17494:     $remhost = lc($remhost);
                   17495:     my $remport = 80;
                   17496:     if ($remprotocol eq 'https') {
                   17497:         $remport = 443;
                   17498:     }
                   17499:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
                   17500:     if ($cached) {
                   17501:         unless ($nocache) {
                   17502:             if ($result) {
                   17503:                 return 1;
                   17504:             } else {
                   17505:                 return 0;
                   17506:             }
                   17507:         }
                   17508:     }
                   17509:     my $uselink;
                   17510:     my $request = new HTTP::Request('HEAD',$url);
1.1075.2.142  raeburn  17511:     my $ua = LWP::UserAgent->new;
                   17512:     $ua->timeout(5);
                   17513:     my $response=$ua->request($request);
1.1075.2.135  raeburn  17514:     if ($response->is_success()) {
                   17515:         my $secpolicy = lc($response->header('content-security-policy'));
                   17516:         my $xframeop = lc($response->header('x-frame-options'));
                   17517:         $secpolicy =~ s/^\s+|\s+$//g;
                   17518:         $xframeop =~ s/^\s+|\s+$//g;
                   17519:         if (($secpolicy ne '') || ($xframeop ne '')) {
                   17520:             my $remotehost = $remprotocol.'://'.$remhost;
                   17521:             my ($origin,$protocol,$port);
                   17522:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   17523:                 $port = $ENV{'SERVER_PORT'};
                   17524:             } else {
                   17525:                 $port = 80;
                   17526:             }
                   17527:             if ($absolute eq '') {
                   17528:                 $protocol = 'http:';
                   17529:                 if ($port == 443) {
                   17530:                     $protocol = 'https:';
                   17531:                 }
                   17532:                 $origin = $protocol.'//'.lc($hostname);
                   17533:             } else {
                   17534:                 $origin = lc($absolute);
                   17535:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   17536:             }
                   17537:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   17538:                 my $framepolicy = $1;
                   17539:                 $framepolicy =~ s/^\s+|\s+$//g;
                   17540:                 my @policies = split(/\s+/,$framepolicy);
                   17541:                 if (@policies) {
                   17542:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   17543:                         $uselink = 1;
                   17544:                     } else {
                   17545:                         $uselink = 1;
                   17546:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   17547:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   17548:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   17549:                             undef($uselink);
                   17550:                         }
                   17551:                         if ($uselink) {
                   17552:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   17553:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   17554:                                     undef($uselink);
                   17555:                                 }
                   17556:                             }
                   17557:                         }
                   17558:                         if ($uselink) {
                   17559:                             my @possok;
                   17560:                             if ($ip ne '') {
                   17561:                                 push(@possok,$ip);
                   17562:                             }
                   17563:                             my $hoststr = '';
                   17564:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   17565:                                 if ($hoststr eq '') {
                   17566:                                     $hoststr = $part;
                   17567:                                 } else {
                   17568:                                     $hoststr = "$part.$hoststr";
                   17569:                                 }
                   17570:                                 if ($hoststr eq $hostname) {
                   17571:                                     push(@possok,$hostname);
                   17572:                                 } else {
                   17573:                                     push(@possok,"*.$hoststr");
                   17574:                                 }
                   17575:                             }
                   17576:                             if (@possok) {
                   17577:                                 foreach my $poss (@possok) {
                   17578:                                     last if (!$uselink);
                   17579:                                     foreach my $policy (@policies) {
                   17580:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   17581:                                             undef($uselink);
                   17582:                                             last;
                   17583:                                         }
                   17584:                                     }
                   17585:                                 }
                   17586:                             }
                   17587:                         }
                   17588:                     }
                   17589:                 }
                   17590:             } elsif ($xframeop ne '') {
                   17591:                 $uselink = 1;
                   17592:                 my @policies = split(/\s*,\s*/,$xframeop);
                   17593:                 if (@policies) {
                   17594:                     unless (grep(/^deny$/,@policies)) {
                   17595:                         if ($origin ne '') {
                   17596:                             if (grep(/^sameorigin$/,@policies)) {
                   17597:                                 if ($remotehost eq $origin) {
                   17598:                                     undef($uselink);
                   17599:                                 }
                   17600:                             }
                   17601:                             if ($uselink) {
                   17602:                                 foreach my $policy (@policies) {
                   17603:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   17604:                                         my $allowfrom = $1;
                   17605:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   17606:                                             undef($uselink);
                   17607:                                             last;
                   17608:                                         }
                   17609:                                     }
                   17610:                                 }
                   17611:                             }
                   17612:                         }
                   17613:                     }
                   17614:                 }
                   17615:             }
                   17616:         }
                   17617:     }
                   17618:     if ($nocache) {
                   17619:         if ($cached) {
                   17620:             my $devalidate;
                   17621:             if ($uselink && !$result) {
                   17622:                 $devalidate = 1;
                   17623:             } elsif (!$uselink && $result) {
                   17624:                 $devalidate = 1;
                   17625:             }
                   17626:             if ($devalidate) {
                   17627:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   17628:             }
                   17629:         }
                   17630:     } else {
                   17631:         if ($uselink) {
                   17632:             $result = 1;
                   17633:         } else {
                   17634:             $result = 0;
                   17635:         }
                   17636:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   17637:     }
                   17638:     return $uselink;
                   17639: }
                   17640: 
1.112     bowersj2 17641: 1;
                   17642: __END__;
1.41      ng       17643: 

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