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

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.141.  .3(raebu    4:20): # $Id: loncommon.pm,v 1.1075.2.141.2.2 2020/02/04 22:28:29 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.1075.2.141.  .1(raebu   86:20): use String::CRC32();
                     87:20): use Short::URL();
1.117     www        88: 
1.517     raeburn    89: # ---------------------------------------------- Designs
                     90: use vars qw(%defaultdesign);
                     91: 
1.22      www        92: my $readit;
                     93: 
1.517     raeburn    94: 
1.157     matthew    95: ##
                     96: ## Global Variables
                     97: ##
1.46      matthew    98: 
1.643     foxr       99: 
                    100: # ----------------------------------------------- SSI with retries:
                    101: #
                    102: 
                    103: =pod
                    104: 
1.648     raeburn   105: =head1 Server Side include with retries:
1.643     foxr      106: 
                    107: =over 4
                    108: 
1.648     raeburn   109: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      110: 
                    111: Performs an ssi with some number of retries.  Retries continue either
                    112: until the result is ok or until the retry count supplied by the
                    113: caller is exhausted.  
                    114: 
                    115: Inputs:
1.648     raeburn   116: 
                    117: =over 4
                    118: 
1.643     foxr      119: resource   - Identifies the resource to insert.
1.648     raeburn   120: 
1.643     foxr      121: retries    - Count of the number of retries allowed.
1.648     raeburn   122: 
1.643     foxr      123: form       - Hash that identifies the rendering options.
                    124: 
1.648     raeburn   125: =back
                    126: 
                    127: Returns:
                    128: 
                    129: =over 4
                    130: 
1.643     foxr      131: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   132: 
1.643     foxr      133: response   - The response from the last attempt (which may or may not have been successful.
                    134: 
1.648     raeburn   135: =back
                    136: 
                    137: =back
                    138: 
1.643     foxr      139: =cut
                    140: 
                    141: sub ssi_with_retries {
                    142:     my ($resource, $retries, %form) = @_;
                    143: 
                    144: 
                    145:     my $ok = 0;			# True if we got a good response.
                    146:     my $content;
                    147:     my $response;
                    148: 
                    149:     # Try to get the ssi done. within the retries count:
                    150: 
                    151:     do {
                    152: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    153: 	$ok      = $response->is_success;
1.650     www       154:         if (!$ok) {
                    155:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    156:         }
1.643     foxr      157: 	$retries--;
                    158:     } while (!$ok && ($retries > 0));
                    159: 
                    160:     if (!$ok) {
                    161: 	$content = '';		# On error return an empty content.
                    162:     }
                    163:     return ($content, $response);
                    164: 
                    165: }
                    166: 
                    167: 
                    168: 
1.20      www       169: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  170: my %language;
1.124     www       171: my %supported_language;
1.1048    foxr      172: my %latex_language;		# For choosing hyphenation in <transl..>
                    173: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  174: my %cprtag;
1.192     taceyjo1  175: my %scprtag;
1.351     www       176: my %fe; my %fd; my %fm;
1.41      ng        177: my %category_extensions;
1.12      harris41  178: 
1.46      matthew   179: # ---------------------------------------------- Thesaurus variables
1.144     matthew   180: #
                    181: # %Keywords:
                    182: #      A hash used by &keyword to determine if a word is considered a keyword.
                    183: # $thesaurus_db_file 
                    184: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   185: 
                    186: my %Keywords;
                    187: my $thesaurus_db_file;
                    188: 
1.144     matthew   189: #
                    190: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    191: # thesaurus.tab, and filecategories.tab.
                    192: #
1.18      www       193: BEGIN {
1.46      matthew   194:     # Variable initialization
                    195:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    196:     #
1.22      www       197:     unless ($readit) {
1.12      harris41  198: # ------------------------------------------------------------------- languages
                    199:     {
1.158     raeburn   200:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    201:                                    '/language.tab';
1.1075.2.128  raeburn   202:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  203:             while (my $line = <$fh>) {
                    204:                 next if ($line=~/^\#/);
                    205:                 chomp($line);
1.1048    foxr      206:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   207:                 $language{$key}=$val.' - '.$enc;
                    208:                 if ($sup) {
                    209:                     $supported_language{$key}=$sup;
                    210:                 }
1.1048    foxr      211: 		if ($latex) {
                    212: 		    $latex_language_bykey{$key} = $latex;
                    213: 		    $latex_language{$two} = $latex;
                    214: 		}
1.158     raeburn   215:             }
                    216:             close($fh);
                    217:         }
1.12      harris41  218:     }
                    219: # ------------------------------------------------------------------ copyrights
                    220:     {
1.158     raeburn   221:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    222:                                   '/copyright.tab';
1.1075.2.128  raeburn   223:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  224:             while (my $line = <$fh>) {
                    225:                 next if ($line=~/^\#/);
                    226:                 chomp($line);
                    227:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   228:                 $cprtag{$key}=$val;
                    229:             }
                    230:             close($fh);
                    231:         }
1.12      harris41  232:     }
1.351     www       233: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  234:     {
                    235:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    236:                                   '/source_copyright.tab';
1.1075.2.128  raeburn   237:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  238:             while (my $line = <$fh>) {
                    239:                 next if ($line =~ /^\#/);
                    240:                 chomp($line);
                    241:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  242:                 $scprtag{$key}=$val;
                    243:             }
                    244:             close($fh);
                    245:         }
                    246:     }
1.63      www       247: 
1.517     raeburn   248: # -------------------------------------------------------------- default domain designs
1.63      www       249:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   250:     my $designfile = $designdir.'/default.tab';
1.1075.2.128  raeburn   251:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   252:         while (my $line = <$fh>) {
                    253:             next if ($line =~ /^\#/);
                    254:             chomp($line);
                    255:             my ($key,$val)=(split(/\=/,$line));
                    256:             if ($val) { $defaultdesign{$key}=$val; }
                    257:         }
                    258:         close($fh);
1.63      www       259:     }
                    260: 
1.15      harris41  261: # ------------------------------------------------------------- file categories
                    262:     {
1.158     raeburn   263:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    264:                                   '/filecategories.tab';
1.1075.2.128  raeburn   265:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  266: 	    while (my $line = <$fh>) {
                    267: 		next if ($line =~ /^\#/);
                    268: 		chomp($line);
                    269:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1075.2.119  raeburn   270:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   271:             }
                    272:             close($fh);
                    273:         }
                    274: 
1.15      harris41  275:     }
1.12      harris41  276: # ------------------------------------------------------------------ file types
                    277:     {
1.158     raeburn   278:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    279:                '/filetypes.tab';
1.1075.2.128  raeburn   280:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  281:             while (my $line = <$fh>) {
                    282: 		next if ($line =~ /^\#/);
                    283: 		chomp($line);
                    284:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   285:                 if ($descr ne '') {
                    286:                     $fe{$ending}=lc($emb);
                    287:                     $fd{$ending}=$descr;
1.351     www       288:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   289:                 }
                    290:             }
                    291:             close($fh);
                    292:         }
1.12      harris41  293:     }
1.22      www       294:     &Apache::lonnet::logthis(
1.705     tempelho  295:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       296:     $readit=1;
1.46      matthew   297:     }  # end of unless($readit) 
1.32      matthew   298:     
                    299: }
1.112     bowersj2  300: 
1.42      matthew   301: ###############################################################
                    302: ##           HTML and Javascript Helper Functions            ##
                    303: ###############################################################
                    304: 
                    305: =pod 
                    306: 
1.112     bowersj2  307: =head1 HTML and Javascript Functions
1.42      matthew   308: 
1.112     bowersj2  309: =over 4
                    310: 
1.648     raeburn   311: =item * &browser_and_searcher_javascript()
1.112     bowersj2  312: 
                    313: X<browsing, javascript>X<searching, javascript>Returns a string
                    314: containing javascript with two functions, C<openbrowser> and
                    315: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    316: tags.
1.42      matthew   317: 
1.648     raeburn   318: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   319: 
                    320: inputs: formname, elementname, only, omit
                    321: 
                    322: formname and elementname indicate the name of the html form and name of
                    323: the element that the results of the browsing selection are to be placed in. 
                    324: 
                    325: Specifying 'only' will restrict the browser to displaying only files
1.185     www       326: with the given extension.  Can be a comma separated list.
1.42      matthew   327: 
                    328: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       329: with the given extension.  Can be a comma separated list.
1.42      matthew   330: 
1.648     raeburn   331: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   332: 
                    333: Inputs: formname, elementname
                    334: 
                    335: formname and elementname specify the name of the html form and the name
                    336: of the element the selection from the search results will be placed in.
1.542     raeburn   337: 
1.42      matthew   338: =cut
                    339: 
                    340: sub browser_and_searcher_javascript {
1.199     albertel  341:     my ($mode)=@_;
                    342:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  343:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   344:     return <<END;
1.219     albertel  345: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   346:     var editbrowser = null;
1.135     albertel  347:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       348:         var url = '$resurl/?';
1.42      matthew   349:         if (editbrowser == null) {
                    350:             url += 'launch=1&';
                    351:         }
                    352:         url += 'catalogmode=interactive&';
1.199     albertel  353:         url += 'mode=$mode&';
1.611     albertel  354:         url += 'inhibitmenu=yes&';
1.42      matthew   355:         url += 'form=' + formname + '&';
                    356:         if (only != null) {
                    357:             url += 'only=' + only + '&';
1.217     albertel  358:         } else {
                    359:             url += 'only=&';
                    360: 	}
1.42      matthew   361:         if (omit != null) {
                    362:             url += 'omit=' + omit + '&';
1.217     albertel  363:         } else {
                    364:             url += 'omit=&';
                    365: 	}
1.135     albertel  366:         if (titleelement != null) {
                    367:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  368:         } else {
                    369: 	    url += 'titleelement=&';
                    370: 	}
1.42      matthew   371:         url += 'element=' + elementname + '';
                    372:         var title = 'Browser';
1.435     albertel  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   374:         options += ',width=700,height=600';
                    375:         editbrowser = open(url,title,options,'1');
                    376:         editbrowser.focus();
                    377:     }
                    378:     var editsearcher;
1.135     albertel  379:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   380:         var url = '/adm/searchcat?';
                    381:         if (editsearcher == null) {
                    382:             url += 'launch=1&';
                    383:         }
                    384:         url += 'catalogmode=interactive&';
1.199     albertel  385:         url += 'mode=$mode&';
1.42      matthew   386:         url += 'form=' + formname + '&';
1.135     albertel  387:         if (titleelement != null) {
                    388:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  389:         } else {
                    390: 	    url += 'titleelement=&';
                    391: 	}
1.42      matthew   392:         url += 'element=' + elementname + '';
                    393:         var title = 'Search';
1.435     albertel  394:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   395:         options += ',width=700,height=600';
                    396:         editsearcher = open(url,title,options,'1');
                    397:         editsearcher.focus();
                    398:     }
1.219     albertel  399: // END LON-CAPA Internal -->
1.42      matthew   400: END
1.170     www       401: }
                    402: 
                    403: sub lastresurl {
1.258     albertel  404:     if ($env{'environment.lastresurl'}) {
                    405: 	return $env{'environment.lastresurl'}
1.170     www       406:     } else {
                    407: 	return '/res';
                    408:     }
                    409: }
                    410: 
                    411: sub storeresurl {
                    412:     my $resurl=&Apache::lonnet::clutter(shift);
                    413:     unless ($resurl=~/^\/res/) { return 0; }
                    414:     $resurl=~s/\/$//;
                    415:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   416:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       417:     return 1;
1.42      matthew   418: }
                    419: 
1.74      www       420: sub studentbrowser_javascript {
1.111     www       421:    unless (
1.258     albertel  422:             (($env{'request.course.id'}) && 
1.302     albertel  423:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    424: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    425: 					  '/'.$env{'request.course.sec'})
                    426: 	      ))
1.258     albertel  427:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       428:           ) { return ''; }  
1.74      www       429:    return (<<'ENDSTDBRW');
1.776     bisitz    430: <script type="text/javascript" language="Javascript">
1.824     bisitz    431: // <![CDATA[
1.74      www       432:     var stdeditbrowser;
1.1075.2.141.  .3(raebu  433:20):     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
1.74      www       434:         var url = '/adm/pickstudent?';
                    435:         var filter;
1.558     albertel  436: 	if (!ignorefilter) {
                    437: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    438: 	}
1.74      www       439:         if (filter != null) {
                    440:            if (filter != '') {
                    441:                url += 'filter='+filter+'&';
                    442: 	   }
                    443:         }
                    444:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       445:                                     '&udomelement='+udom+
                    446:                                     '&clicker='+clicker;
1.111     www       447: 	if (roleflag) { url+="&roles=1"; }
1.1075.2.141.  .3(raebu  448:20):         if (courseadv == 'condition') {
                    449:20):             if (document.getElementById('courseadv')) {
                    450:20):                 courseadv = document.getElementById('courseadv').value;
                    451:20):             }
                    452:20):         }
                    453:20):         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       454:         var title = 'Student_Browser';
1.74      www       455:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    456:         options += ',width=700,height=600';
                    457:         stdeditbrowser = open(url,title,options,'1');
                    458:         stdeditbrowser.focus();
                    459:     }
1.824     bisitz    460: // ]]>
1.74      www       461: </script>
                    462: ENDSTDBRW
                    463: }
1.42      matthew   464: 
1.1003    www       465: sub resourcebrowser_javascript {
                    466:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       467:    return (<<'ENDRESBRW');
1.1003    www       468: <script type="text/javascript" language="Javascript">
                    469: // <![CDATA[
                    470:     var reseditbrowser;
1.1004    www       471:     function openresbrowser(formname,reslink) {
1.1005    www       472:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       473:         var title = 'Resource_Browser';
                    474:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       475:         options += ',width=700,height=500';
1.1004    www       476:         reseditbrowser = open(url,title,options,'1');
                    477:         reseditbrowser.focus();
1.1003    www       478:     }
                    479: // ]]>
                    480: </script>
1.1004    www       481: ENDRESBRW
1.1003    www       482: }
                    483: 
1.74      www       484: sub selectstudent_link {
1.1075.2.141.  .3(raebu  485:20):    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       486:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    487:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    488:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  489:    if ($env{'request.course.id'}) {  
1.302     albertel  490:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    491: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    492: 					'/'.$env{'request.course.sec'})) {
1.111     www       493: 	   return '';
                    494:        }
1.999     www       495:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1075.2.141.  .3(raebu  496:20):        if ($courseadv eq 'only') {
                    497:20):            $callargs .= ",'',1,'$courseadv'";
                    498:20):        } elsif ($courseadv eq 'none') {
                    499:20):            $callargs .= ",'','','$courseadv'";
                    500:20):        } elsif ($courseadv eq 'condition') {
                    501:20):            $callargs .= ",'','','$courseadv'";
1.793     raeburn   502:        }
                    503:        return '<span class="LC_nobreak">'.
                    504:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    505:               &mt('Select User').'</a></span>';
1.74      www       506:    }
1.258     albertel  507:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       508:        $callargs .= ",'',1"; 
1.793     raeburn   509:        return '<span class="LC_nobreak">'.
                    510:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    511:               &mt('Select User').'</a></span>';
1.111     www       512:    }
                    513:    return '';
1.91      www       514: }
                    515: 
1.1004    www       516: sub selectresource_link {
                    517:    my ($form,$reslink,$arg)=@_;
                    518:    
                    519:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    520:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    521:    unless ($env{'request.course.id'}) { return $arg; }
                    522:    return '<span class="LC_nobreak">'.
                    523:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    524:               $arg.'</a></span>';
                    525: }
                    526: 
                    527: 
                    528: 
1.653     raeburn   529: sub authorbrowser_javascript {
                    530:     return <<"ENDAUTHORBRW";
1.776     bisitz    531: <script type="text/javascript" language="JavaScript">
1.824     bisitz    532: // <![CDATA[
1.653     raeburn   533: var stdeditbrowser;
                    534: 
                    535: function openauthorbrowser(formname,udom) {
                    536:     var url = '/adm/pickauthor?';
                    537:     url += 'form='+formname+'&roledom='+udom;
                    538:     var title = 'Author_Browser';
                    539:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    540:     options += ',width=700,height=600';
                    541:     stdeditbrowser = open(url,title,options,'1');
                    542:     stdeditbrowser.focus();
                    543: }
                    544: 
1.824     bisitz    545: // ]]>
1.653     raeburn   546: </script>
                    547: ENDAUTHORBRW
                    548: }
                    549: 
1.91      www       550: sub coursebrowser_javascript {
1.1075.2.31  raeburn   551:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   552:         $credits_element,$instcode) = @_;
1.932     raeburn   553:     my $wintitle = 'Course_Browser';
1.931     raeburn   554:     if ($crstype eq 'Community') {
1.932     raeburn   555:         $wintitle = 'Community_Browser';
1.909     raeburn   556:     }
1.876     raeburn   557:     my $id_functions = &javascript_index_functions();
                    558:     my $output = '
1.776     bisitz    559: <script type="text/javascript" language="JavaScript">
1.824     bisitz    560: // <![CDATA[
1.468     raeburn   561:     var stdeditbrowser;'."\n";
1.876     raeburn   562: 
                    563:     $output .= <<"ENDSTDBRW";
1.909     raeburn   564:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       565:         var url = '/adm/pickcourse?';
1.895     raeburn   566:         var formid = getFormIdByName(formname);
1.876     raeburn   567:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  568:         if (domainfilter != null) {
                    569:            if (domainfilter != '') {
                    570:                url += 'domainfilter='+domainfilter+'&';
                    571: 	   }
                    572:         }
1.91      www       573:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  574: 	                            '&cdomelement='+udom+
                    575:                                     '&cnameelement='+desc;
1.468     raeburn   576:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   577:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   578:                 url += '&roleelement='+extra_element;
                    579:                 if (domainfilter == null || domainfilter == '') {
                    580:                     url += '&domainfilter='+extra_element;
                    581:                 }
1.234     raeburn   582:             }
1.468     raeburn   583:             else {
                    584:                 if (formname == 'portform') {
                    585:                     url += '&setroles='+extra_element;
1.800     raeburn   586:                 } else {
                    587:                     if (formname == 'rules') {
                    588:                         url += '&fixeddom='+extra_element; 
                    589:                     }
1.468     raeburn   590:                 }
                    591:             }     
1.230     raeburn   592:         }
1.909     raeburn   593:         if (type != null && type != '') {
                    594:             url += '&type='+type;
                    595:         }
                    596:         if (type_elem != null && type_elem != '') {
                    597:             url += '&typeelement='+type_elem;
                    598:         }
1.872     raeburn   599:         if (formname == 'ccrs') {
                    600:             var ownername = document.forms[formid].ccuname.value;
                    601:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   602:             url += '&cloner='+ownername+':'+ownerdom;
                    603:             if (type == 'Course') {
                    604:                 url += '&crscode='+document.forms[formid].crscode.value;
                    605:             }
1.1075.2.95  raeburn   606:         }
                    607:         if (formname == 'requestcrs') {
                    608:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   609:         }
1.293     raeburn   610:         if (multflag !=null && multflag != '') {
                    611:             url += '&multiple='+multflag;
                    612:         }
1.909     raeburn   613:         var title = '$wintitle';
1.91      www       614:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    615:         options += ',width=700,height=600';
                    616:         stdeditbrowser = open(url,title,options,'1');
                    617:         stdeditbrowser.focus();
                    618:     }
1.876     raeburn   619: $id_functions
                    620: ENDSTDBRW
1.1075.2.31  raeburn   621:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    622:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    623:                                       $credits_element);
1.876     raeburn   624:     }
                    625:     $output .= '
                    626: // ]]>
                    627: </script>';
                    628:     return $output;
                    629: }
                    630: 
                    631: sub javascript_index_functions {
                    632:     return <<"ENDJS";
                    633: 
                    634: function getFormIdByName(formname) {
                    635:     for (var i=0;i<document.forms.length;i++) {
                    636:         if (document.forms[i].name == formname) {
                    637:             return i;
                    638:         }
                    639:     }
                    640:     return -1;
                    641: }
                    642: 
                    643: function getIndexByName(formid,item) {
                    644:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    645:         if (document.forms[formid].elements[i].name == item) {
                    646:             return i;
                    647:         }
                    648:     }
                    649:     return -1;
                    650: }
1.468     raeburn   651: 
1.876     raeburn   652: function getDomainFromSelectbox(formname,udom) {
                    653:     var userdom;
                    654:     var formid = getFormIdByName(formname);
                    655:     if (formid > -1) {
                    656:         var domid = getIndexByName(formid,udom);
                    657:         if (domid > -1) {
                    658:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    659:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    660:             }
                    661:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    662:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   663:             }
                    664:         }
                    665:     }
1.876     raeburn   666:     return userdom;
                    667: }
                    668: 
                    669: ENDJS
1.468     raeburn   670: 
1.876     raeburn   671: }
                    672: 
1.1017    raeburn   673: sub javascript_array_indexof {
1.1018    raeburn   674:     return <<ENDJS;
1.1017    raeburn   675: <script type="text/javascript" language="JavaScript">
                    676: // <![CDATA[
                    677: 
                    678: if (!Array.prototype.indexOf) {
                    679:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    680:         "use strict";
                    681:         if (this === void 0 || this === null) {
                    682:             throw new TypeError();
                    683:         }
                    684:         var t = Object(this);
                    685:         var len = t.length >>> 0;
                    686:         if (len === 0) {
                    687:             return -1;
                    688:         }
                    689:         var n = 0;
                    690:         if (arguments.length > 0) {
                    691:             n = Number(arguments[1]);
                    692:             if (n !== n) { // shortcut for verifying if it's NaN
                    693:                 n = 0;
                    694:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    695:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    696:             }
                    697:         }
                    698:         if (n >= len) {
                    699:             return -1;
                    700:         }
                    701:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    702:         for (; k < len; k++) {
                    703:             if (k in t && t[k] === searchElement) {
                    704:                 return k;
                    705:             }
                    706:         }
                    707:         return -1;
                    708:     }
                    709: }
                    710: 
                    711: // ]]>
                    712: </script>
                    713: 
                    714: ENDJS
                    715: 
                    716: }
                    717: 
1.876     raeburn   718: sub userbrowser_javascript {
                    719:     my $id_functions = &javascript_index_functions();
                    720:     return <<"ENDUSERBRW";
                    721: 
1.888     raeburn   722: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   723:     var url = '/adm/pickuser?';
                    724:     var userdom = getDomainFromSelectbox(formname,udom);
                    725:     if (userdom != null) {
                    726:        if (userdom != '') {
                    727:            url += 'srchdom='+userdom+'&';
                    728:        }
                    729:     }
                    730:     url += 'form=' + formname + '&unameelement='+uname+
                    731:                                 '&udomelement='+udom+
                    732:                                 '&ulastelement='+ulast+
                    733:                                 '&ufirstelement='+ufirst+
                    734:                                 '&uemailelement='+uemail+
1.881     raeburn   735:                                 '&hideudomelement='+hideudom+
                    736:                                 '&coursedom='+crsdom;
1.888     raeburn   737:     if ((caller != null) && (caller != undefined)) {
                    738:         url += '&caller='+caller;
                    739:     }
1.876     raeburn   740:     var title = 'User_Browser';
                    741:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    742:     options += ',width=700,height=600';
                    743:     var stdeditbrowser = open(url,title,options,'1');
                    744:     stdeditbrowser.focus();
                    745: }
                    746: 
1.888     raeburn   747: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   748:     var formid = getFormIdByName(formname);
                    749:     if (formid > -1) {
1.888     raeburn   750:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   751:         var domid = getIndexByName(formid,udom);
                    752:         var hidedomid = getIndexByName(formid,origdom);
                    753:         if (hidedomid > -1) {
                    754:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   755:             var unameval = document.forms[formid].elements[unameid].value;
                    756:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    757:                 if (domid > -1) {
                    758:                     var slct = document.forms[formid].elements[domid];
                    759:                     if (slct.type == 'select-one') {
                    760:                         var i;
                    761:                         for (i=0;i<slct.length;i++) {
                    762:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    763:                         }
                    764:                     }
                    765:                     if (slct.type == 'hidden') {
                    766:                         slct.value = fixeddom;
1.876     raeburn   767:                     }
                    768:                 }
1.468     raeburn   769:             }
                    770:         }
                    771:     }
1.876     raeburn   772:     return;
                    773: }
                    774: 
                    775: $id_functions
                    776: ENDUSERBRW
1.468     raeburn   777: }
                    778: 
                    779: sub setsec_javascript {
1.1075.2.31  raeburn   780:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   781:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    782:         $communityrolestr);
                    783:     if ($role_element ne '') {
                    784:         my @allroles = ('st','ta','ep','in','ad');
                    785:         foreach my $crstype ('Course','Community') {
                    786:             if ($crstype eq 'Community') {
                    787:                 foreach my $role (@allroles) {
                    788:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    789:                 }
                    790:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    791:             } else {
                    792:                 foreach my $role (@allroles) {
                    793:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    794:                 }
                    795:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    796:             }
                    797:         }
                    798:         $rolestr = '"'.join('","',@allroles).'"';
                    799:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    800:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    801:     }
1.468     raeburn   802:     my $setsections = qq|
                    803: function setSect(sectionlist) {
1.629     raeburn   804:     var sectionsArray = new Array();
                    805:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    806:         sectionsArray = sectionlist.split(",");
                    807:     }
1.468     raeburn   808:     var numSections = sectionsArray.length;
                    809:     document.$formname.$sec_element.length = 0;
                    810:     if (numSections == 0) {
                    811:         document.$formname.$sec_element.multiple=false;
                    812:         document.$formname.$sec_element.size=1;
                    813:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    814:     } else {
                    815:         if (numSections == 1) {
                    816:             document.$formname.$sec_element.multiple=false;
                    817:             document.$formname.$sec_element.size=1;
                    818:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    819:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    820:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    821:         } else {
                    822:             for (var i=0; i<numSections; i++) {
                    823:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    824:             }
                    825:             document.$formname.$sec_element.multiple=true
                    826:             if (numSections < 3) {
                    827:                 document.$formname.$sec_element.size=numSections;
                    828:             } else {
                    829:                 document.$formname.$sec_element.size=3;
                    830:             }
                    831:             document.$formname.$sec_element.options[0].selected = false
                    832:         }
                    833:     }
1.91      www       834: }
1.905     raeburn   835: 
                    836: function setRole(crstype) {
1.468     raeburn   837: |;
1.905     raeburn   838:     if ($role_element eq '') {
                    839:         $setsections .= '    return;
                    840: }
                    841: ';
                    842:     } else {
                    843:         $setsections .= qq|
                    844:     var elementLength = document.$formname.$role_element.length;
                    845:     var allroles = Array($rolestr);
                    846:     var courserolenames = Array($courserolestr);
                    847:     var communityrolenames = Array($communityrolestr);
                    848:     if (elementLength != undefined) {
                    849:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    850:             if (crstype == 'Course') {
                    851:                 return;
                    852:             } else {
                    853:                 allroles[5] = 'co';
                    854:                 for (var i=0; i<6; i++) {
                    855:                     document.$formname.$role_element.options[i].value = allroles[i];
                    856:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    857:                 }
                    858:             }
                    859:         } else {
                    860:             if (crstype == 'Community') {
                    861:                 return;
                    862:             } else {
                    863:                 allroles[5] = 'cc';
                    864:                 for (var i=0; i<6; i++) {
                    865:                     document.$formname.$role_element.options[i].value = allroles[i];
                    866:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    867:                 }
                    868:             }
                    869:         }
                    870:     }
                    871:     return;
                    872: }
                    873: |;
                    874:     }
1.1075.2.31  raeburn   875:     if ($credits_element) {
                    876:         $setsections .= qq|
                    877: function setCredits(defaultcredits) {
                    878:     document.$formname.$credits_element.value = defaultcredits;
                    879:     return;
                    880: }
                    881: |;
                    882:     }
1.468     raeburn   883:     return $setsections;
                    884: }
                    885: 
1.91      www       886: sub selectcourse_link {
1.909     raeburn   887:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    888:        $typeelement) = @_;
                    889:    my $type = $selecttype;
1.871     raeburn   890:    my $linktext = &mt('Select Course');
                    891:    if ($selecttype eq 'Community') {
1.909     raeburn   892:        $linktext = &mt('Select Community');
1.906     raeburn   893:    } elsif ($selecttype eq 'Course/Community') {
                    894:        $linktext = &mt('Select Course/Community');
1.909     raeburn   895:        $type = '';
1.1019    raeburn   896:    } elsif ($selecttype eq 'Select') {
                    897:        $linktext = &mt('Select');
                    898:        $type = '';
1.871     raeburn   899:    }
1.787     bisitz    900:    return '<span class="LC_nobreak">'
                    901:          ."<a href='"
                    902:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    903:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   904:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   905:          ."'>".$linktext.'</a>'
1.787     bisitz    906:          .'</span>';
1.74      www       907: }
1.42      matthew   908: 
1.653     raeburn   909: sub selectauthor_link {
                    910:    my ($form,$udom)=@_;
                    911:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    912:           &mt('Select Author').'</a>';
                    913: }
                    914: 
1.876     raeburn   915: sub selectuser_link {
1.881     raeburn   916:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   917:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   918:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   919:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   920:            ');">'.$linktext.'</a>';
1.876     raeburn   921: }
                    922: 
1.273     raeburn   923: sub check_uncheck_jscript {
                    924:     my $jscript = <<"ENDSCRT";
                    925: function checkAll(field) {
                    926:     if (field.length > 0) {
                    927:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   928:             if (!field[i].disabled) {
                    929:                 field[i].checked = true;
                    930:             }
1.273     raeburn   931:         }
                    932:     } else {
1.1075.2.14  raeburn   933:         if (!field.disabled) {
                    934:             field.checked = true;
                    935:         }
1.273     raeburn   936:     }
                    937: }
                    938:  
                    939: function uncheckAll(field) {
                    940:     if (field.length > 0) {
                    941:         for (i = 0; i < field.length; i++) {
                    942:             field[i].checked = false ;
1.543     albertel  943:         }
                    944:     } else {
1.273     raeburn   945:         field.checked = false ;
                    946:     }
                    947: }
                    948: ENDSCRT
                    949:     return $jscript;
                    950: }
                    951: 
1.656     www       952: sub select_timezone {
1.1075.2.115  raeburn   953:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    954:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   955:    if ($includeempty) {
                    956:        $output .= '<option value=""';
                    957:        if (($selected eq '') || ($selected eq 'local')) {
                    958:            $output .= ' selected="selected" ';
                    959:        }
                    960:        $output .= '> </option>';
                    961:    }
1.657     raeburn   962:    my @timezones = DateTime::TimeZone->all_names;
                    963:    foreach my $tzone (@timezones) {
                    964:        $output.= '<option value="'.$tzone.'"';
                    965:        if ($tzone eq $selected) {
                    966:            $output.=' selected="selected"';
                    967:        }
                    968:        $output.=">$tzone</option>\n";
1.656     www       969:    }
                    970:    $output.="</select>";
                    971:    return $output;
                    972: }
1.273     raeburn   973: 
1.687     raeburn   974: sub select_datelocale {
1.1075.2.115  raeburn   975:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    976:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   977:     if ($includeempty) {
                    978:         $output .= '<option value=""';
                    979:         if ($selected eq '') {
                    980:             $output .= ' selected="selected" ';
                    981:         }
                    982:         $output .= '> </option>';
                    983:     }
1.1075.2.102  raeburn   984:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   985:     my (@possibles,%locale_names);
1.1075.2.102  raeburn   986:     my @locales = DateTime::Locale->ids();
                    987:     foreach my $id (@locales) {
                    988:         if ($id ne '') {
                    989:             my ($en_terr,$native_terr);
                    990:             my $loc = DateTime::Locale->load($id);
                    991:             if (ref($loc)) {
                    992:                 $en_terr = $loc->name();
                    993:                 $native_terr = $loc->native_name();
1.687     raeburn   994:                 if (grep(/^en$/,@languages) || !@languages) {
                    995:                     if ($en_terr ne '') {
                    996:                         $locale_names{$id} = '('.$en_terr.')';
                    997:                     } elsif ($native_terr ne '') {
                    998:                         $locale_names{$id} = $native_terr;
                    999:                     }
                   1000:                 } else {
                   1001:                     if ($native_terr ne '') {
                   1002:                         $locale_names{$id} = $native_terr.' ';
                   1003:                     } elsif ($en_terr ne '') {
                   1004:                         $locale_names{$id} = '('.$en_terr.')';
                   1005:                     }
                   1006:                 }
1.1075.2.94  raeburn  1007:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1075.2.102  raeburn  1008:                 push(@possibles,$id);
1.687     raeburn  1009:             }
                   1010:         }
                   1011:     }
                   1012:     foreach my $item (sort(@possibles)) {
                   1013:         $output.= '<option value="'.$item.'"';
                   1014:         if ($item eq $selected) {
                   1015:             $output.=' selected="selected"';
                   1016:         }
                   1017:         $output.=">$item";
                   1018:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn  1019:             $output.='  '.$locale_names{$item};
1.687     raeburn  1020:         }
                   1021:         $output.="</option>\n";
                   1022:     }
                   1023:     $output.="</select>";
                   1024:     return $output;
                   1025: }
                   1026: 
1.792     raeburn  1027: sub select_language {
1.1075.2.115  raeburn  1028:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1029:     my %langchoices;
                   1030:     if ($includeempty) {
1.1075.2.32  raeburn  1031:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1032:     }
                   1033:     foreach my $id (&languageids()) {
                   1034:         my $code = &supportedlanguagecode($id);
                   1035:         if ($code) {
                   1036:             $langchoices{$code} = &plainlanguagedescription($id);
                   1037:         }
                   1038:     }
1.1075.2.32  raeburn  1039:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1075.2.115  raeburn  1040:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1041: }
                   1042: 
1.42      matthew  1043: =pod
1.36      matthew  1044: 
1.648     raeburn  1045: =item * &linked_select_forms(...)
1.36      matthew  1046: 
                   1047: linked_select_forms returns a string containing a <script></script> block
                   1048: and html for two <select> menus.  The select menus will be linked in that
                   1049: changing the value of the first menu will result in new values being placed
                   1050: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1051: order unless a defined order is provided.
1.36      matthew  1052: 
                   1053: linked_select_forms takes the following ordered inputs:
                   1054: 
                   1055: =over 4
                   1056: 
1.112     bowersj2 1057: =item * $formname, the name of the <form> tag
1.36      matthew  1058: 
1.112     bowersj2 1059: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1060: 
1.112     bowersj2 1061: =item * $firstdefault, the default value for the first menu
1.36      matthew  1062: 
1.112     bowersj2 1063: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1064: 
1.112     bowersj2 1065: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1066: 
1.112     bowersj2 1067: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1068: 
1.609     raeburn  1069: =item * $menuorder, the order of values in the first menu
                   1070: 
1.1075.2.31  raeburn  1071: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1072:         event for the first <select> tag
                   1073: 
                   1074: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1075:         event for the second <select> tag
                   1076: 
1.41      ng       1077: =back 
                   1078: 
1.36      matthew  1079: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1080: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1081: values for the first select menu.  The text that coincides with the 
1.41      ng       1082: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1083: and text for the second menu are given in the hash pointed to by 
                   1084: $menu{$choice1}->{'select2'}.  
                   1085: 
1.112     bowersj2 1086:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1087:                        default => "B3",
                   1088:                        select2 => { 
                   1089:                            B1 => "Choice B1",
                   1090:                            B2 => "Choice B2",
                   1091:                            B3 => "Choice B3",
                   1092:                            B4 => "Choice B4"
1.609     raeburn  1093:                            },
                   1094:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1095:                    },
                   1096:                A2 => { text =>"Choice A2" ,
                   1097:                        default => "C2",
                   1098:                        select2 => { 
                   1099:                            C1 => "Choice C1",
                   1100:                            C2 => "Choice C2",
                   1101:                            C3 => "Choice C3"
1.609     raeburn  1102:                            },
                   1103:                        order => ['C2','C1','C3'],
1.112     bowersj2 1104:                    },
                   1105:                A3 => { text =>"Choice A3" ,
                   1106:                        default => "D6",
                   1107:                        select2 => { 
                   1108:                            D1 => "Choice D1",
                   1109:                            D2 => "Choice D2",
                   1110:                            D3 => "Choice D3",
                   1111:                            D4 => "Choice D4",
                   1112:                            D5 => "Choice D5",
                   1113:                            D6 => "Choice D6",
                   1114:                            D7 => "Choice D7"
1.609     raeburn  1115:                            },
                   1116:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1117:                    }
                   1118:                );
1.36      matthew  1119: 
                   1120: =cut
                   1121: 
                   1122: sub linked_select_forms {
                   1123:     my ($formname,
                   1124:         $middletext,
                   1125:         $firstdefault,
                   1126:         $firstselectname,
                   1127:         $secondselectname, 
1.609     raeburn  1128:         $hashref,
                   1129:         $menuorder,
1.1075.2.31  raeburn  1130:         $onchangefirst,
                   1131:         $onchangesecond
1.36      matthew  1132:         ) = @_;
                   1133:     my $second = "document.$formname.$secondselectname";
                   1134:     my $first = "document.$formname.$firstselectname";
                   1135:     # output the javascript to do the changing
                   1136:     my $result = '';
1.776     bisitz   1137:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1138:     $result.="// <![CDATA[\n";
1.36      matthew  1139:     $result.="var select2data = new Object();\n";
                   1140:     $" = '","';
                   1141:     my $debug = '';
                   1142:     foreach my $s1 (sort(keys(%$hashref))) {
                   1143:         $result.="select2data.d_$s1 = new Object();\n";        
                   1144:         $result.="select2data.d_$s1.def = new String('".
                   1145:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1146:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1147:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1148:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1149:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1150:         }
1.36      matthew  1151:         $result.="\"@s2values\");\n";
                   1152:         $result.="select2data.d_$s1.texts = new Array(";        
                   1153:         my @s2texts;
                   1154:         foreach my $value (@s2values) {
1.1075.2.119  raeburn  1155:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1156:         }
                   1157:         $result.="\"@s2texts\");\n";
                   1158:     }
                   1159:     $"=' ';
                   1160:     $result.= <<"END";
                   1161: 
                   1162: function select1_changed() {
                   1163:     // Determine new choice
                   1164:     var newvalue = "d_" + $first.value;
                   1165:     // update select2
                   1166:     var values     = select2data[newvalue].values;
                   1167:     var texts      = select2data[newvalue].texts;
                   1168:     var select2def = select2data[newvalue].def;
                   1169:     var i;
                   1170:     // out with the old
                   1171:     for (i = 0; i < $second.options.length; i++) {
                   1172:         $second.options[i] = null;
                   1173:     }
                   1174:     // in with the nuclear
                   1175:     for (i=0;i<values.length; i++) {
                   1176:         $second.options[i] = new Option(values[i]);
1.143     matthew  1177:         $second.options[i].value = values[i];
1.36      matthew  1178:         $second.options[i].text = texts[i];
                   1179:         if (values[i] == select2def) {
                   1180:             $second.options[i].selected = true;
                   1181:         }
                   1182:     }
                   1183: }
1.824     bisitz   1184: // ]]>
1.36      matthew  1185: </script>
                   1186: END
                   1187:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1188:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1189:     my @order = sort(keys(%{$hashref}));
                   1190:     if (ref($menuorder) eq 'ARRAY') {
                   1191:         @order = @{$menuorder};
                   1192:     }
                   1193:     foreach my $value (@order) {
1.36      matthew  1194:         $result.="    <option value=\"$value\" ";
1.253     albertel 1195:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1196:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1197:     }
                   1198:     $result .= "</select>\n";
                   1199:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1200:     $result .= $middletext;
1.1075.2.31  raeburn  1201:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1202:     if ($onchangesecond) {
                   1203:         $result .= ' onchange="'.$onchangesecond.'"';
                   1204:     }
                   1205:     $result .= ">\n";
1.36      matthew  1206:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1207:     
                   1208:     my @secondorder = sort(keys(%select2));
                   1209:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1210:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1211:     }
                   1212:     foreach my $value (@secondorder) {
1.36      matthew  1213:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1214:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1215:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1216:     }
                   1217:     $result .= "</select>\n";
                   1218:     #    return $debug;
                   1219:     return $result;
                   1220: }   #  end of sub linked_select_forms {
                   1221: 
1.45      matthew  1222: =pod
1.44      bowersj2 1223: 
1.973     raeburn  1224: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1225: 
1.112     bowersj2 1226: Returns a string corresponding to an HTML link to the given help
                   1227: $topic, where $topic corresponds to the name of a .tex file in
                   1228: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1229: spaces. 
                   1230: 
                   1231: $text will optionally be linked to the same topic, allowing you to
                   1232: link text in addition to the graphic. If you do not want to link
                   1233: text, but wish to specify one of the later parameters, pass an
                   1234: empty string. 
                   1235: 
                   1236: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1237: the link will not open a new window. If false, the link will open
                   1238: a new window using Javascript. (Default is false.) 
                   1239: 
                   1240: $width and $height are optional numerical parameters that will
                   1241: override the width and height of the popped up window, which may
1.973     raeburn  1242: be useful for certain help topics with big pictures included.
                   1243: 
                   1244: $imgid is the id of the img tag used for the help icon. This may be
                   1245: used in a javascript call to switch the image src.  See 
                   1246: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1247: 
                   1248: =cut
                   1249: 
                   1250: sub help_open_topic {
1.973     raeburn  1251:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1252:     $text = "" if (not defined $text);
1.44      bowersj2 1253:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1254:     $width = 500 if (not defined $width);
1.44      bowersj2 1255:     $height = 400 if (not defined $height);
                   1256:     my $filename = $topic;
                   1257:     $filename =~ s/ /_/g;
                   1258: 
1.48      bowersj2 1259:     my $template = "";
                   1260:     my $link;
1.572     banghart 1261:     
1.159     www      1262:     $topic=~s/\W/\_/g;
1.44      bowersj2 1263: 
1.572     banghart 1264:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1265:         if ($env{'browser.mobile'}) {
                   1266: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1267:         } else {
                   1268:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1269:         }
1.1037    www      1270:     } elsif ($stayOnPage eq 'popup') {
                   1271:         $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 1272:     } else {
1.48      bowersj2 1273: 	$link = "/adm/help/${filename}.hlp";
                   1274:     }
                   1275: 
                   1276:     # Add the text
1.755     neumanie 1277:     if ($text ne "") {	
1.763     bisitz   1278: 	$template.='<span class="LC_help_open_topic">'
                   1279:                   .'<a target="_top" href="'.$link.'">'
                   1280:                   .$text.'</a>';
1.48      bowersj2 1281:     }
                   1282: 
1.763     bisitz   1283:     # (Always) Add the graphic
1.179     matthew  1284:     my $title = &mt('Online Help');
1.667     raeburn  1285:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1286:     if ($imgid ne '') {
                   1287:         $imgid = ' id="'.$imgid.'"';
                   1288:     }
1.763     bisitz   1289:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1290:               .'<img src="'.$helpicon.'" border="0"'
                   1291:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1292:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1293:               .' /></a>';
                   1294:     if ($text ne "") {	
                   1295:         $template.='</span>';
                   1296:     }
1.44      bowersj2 1297:     return $template;
                   1298: 
1.106     bowersj2 1299: }
                   1300: 
                   1301: # This is a quicky function for Latex cheatsheet editing, since it 
                   1302: # appears in at least four places
                   1303: sub helpLatexCheatsheet {
1.1037    www      1304:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1305:     my $out;
1.106     bowersj2 1306:     my $addOther = '';
1.732     raeburn  1307:     if ($topic) {
1.1037    www      1308: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1309:     }
                   1310:     $out = '<span>' # Start cheatsheet
                   1311: 	  .$addOther
                   1312:           .'<span>'
1.1037    www      1313: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1314: 	  .'</span> <span>'
1.1037    www      1315: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1316: 	  .'</span>';
1.732     raeburn  1317:     unless ($not_author) {
1.763     bisitz   1318:         $out .= ' <span>'
1.1037    www      1319: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1320: 	       .'</span> <span>'
1.1075.2.78  raeburn  1321:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1322:                .'</span>';
1.732     raeburn  1323:     }
1.763     bisitz   1324:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1325:     return $out;
1.172     www      1326: }
                   1327: 
1.430     albertel 1328: sub general_help {
                   1329:     my $helptopic='Student_Intro';
                   1330:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1331: 	$helptopic='Authoring_Intro';
1.907     raeburn  1332:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1333: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1334:     } elsif ($env{'request.role'}=~/^dc/) {
                   1335:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1336:     }
                   1337:     return $helptopic;
                   1338: }
                   1339: 
                   1340: sub update_help_link {
                   1341:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1342:     my $origurl = $ENV{'REQUEST_URI'};
                   1343:     $origurl=~s|^/~|/priv/|;
                   1344:     my $timestamp = time;
                   1345:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1346:         $$datum = &escape($$datum);
                   1347:     }
                   1348: 
                   1349:     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";
                   1350:     my $output .= <<"ENDOUTPUT";
                   1351: <script type="text/javascript">
1.824     bisitz   1352: // <![CDATA[
1.430     albertel 1353: banner_link = '$banner_link';
1.824     bisitz   1354: // ]]>
1.430     albertel 1355: </script>
                   1356: ENDOUTPUT
                   1357:     return $output;
                   1358: }
                   1359: 
                   1360: # now just updates the help link and generates a blue icon
1.193     raeburn  1361: sub help_open_menu {
1.430     albertel 1362:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1363: 	= @_;    
1.949     droeschl 1364:     $stayOnPage = 1;
1.430     albertel 1365:     my $output;
                   1366:     if ($component_help) {
                   1367: 	if (!$text) {
                   1368: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1369: 				       $width,$height);
                   1370: 	} else {
                   1371: 	    my $help_text;
                   1372: 	    $help_text=&unescape($topic);
                   1373: 	    $output='<table><tr><td>'.
                   1374: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1375: 				 $width,$height).'</td></tr></table>';
                   1376: 	}
                   1377:     }
                   1378:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1379:     return $output.$banner_link;
                   1380: }
                   1381: 
                   1382: sub top_nav_help {
                   1383:     my ($text) = @_;
1.436     albertel 1384:     $text = &mt($text);
1.1075.2.60  raeburn  1385:     my $stay_on_page;
                   1386:     unless ($env{'environment.remote'} eq 'on') {
                   1387:         $stay_on_page = 1;
                   1388:     }
1.1075.2.61  raeburn  1389:     my ($link,$banner_link);
                   1390:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1391:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1392: 	                         : "javascript:helpMenu('open')";
                   1393:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1394:     }
1.201     raeburn  1395:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1396:     if ($link) {
                   1397:         return <<"END";
1.436     albertel 1398: $banner_link
1.1075.2.56  raeburn  1399: <a href="$link" title="$title">$text</a>
1.436     albertel 1400: END
1.1075.2.61  raeburn  1401:     } else {
                   1402:         return '&nbsp;'.$text.'&nbsp;';
                   1403:     }
1.436     albertel 1404: }
                   1405: 
                   1406: sub help_menu_js {
1.1075.2.52  raeburn  1407:     my ($httphost) = @_;
1.949     droeschl 1408:     my $stayOnPage = 1;
1.436     albertel 1409:     my $width = 620;
                   1410:     my $height = 600;
1.430     albertel 1411:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1412:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1413:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1414:     my $start_page =
                   1415:         &Apache::loncommon::start_page('Help Menu', undef,
                   1416: 				       {'frameset'    => 1,
                   1417: 					'js_ready'    => 1,
1.1075.2.136  raeburn  1418:                                         'use_absolute' => $httphost,
1.331     albertel 1419: 					'add_entries' => {
                   1420: 					    'border' => '0',
1.579     raeburn  1421: 					    'rows'   => "110,*",},});
1.331     albertel 1422:     my $end_page =
                   1423:         &Apache::loncommon::end_page({'frameset' => 1,
                   1424: 				      'js_ready' => 1,});
                   1425: 
1.436     albertel 1426:     my $template .= <<"ENDTEMPLATE";
                   1427: <script type="text/javascript">
1.877     bisitz   1428: // <![CDATA[
1.253     albertel 1429: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1430: var banner_link = '';
1.243     raeburn  1431: function helpMenu(target) {
                   1432:     var caller = this;
                   1433:     if (target == 'open') {
                   1434:         var newWindow = null;
                   1435:         try {
1.262     albertel 1436:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1437:         }
                   1438:         catch(error) {
                   1439:             writeHelp(caller);
                   1440:             return;
                   1441:         }
                   1442:         if (newWindow) {
                   1443:             caller = newWindow;
                   1444:         }
1.193     raeburn  1445:     }
1.243     raeburn  1446:     writeHelp(caller);
                   1447:     return;
                   1448: }
                   1449: function writeHelp(caller) {
1.1075.2.61  raeburn  1450:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1451:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1452:     caller.document.close();
                   1453:     caller.focus();
1.193     raeburn  1454: }
1.877     bisitz   1455: // END LON-CAPA Internal -->
1.253     albertel 1456: // ]]>
1.436     albertel 1457: </script>
1.193     raeburn  1458: ENDTEMPLATE
                   1459:     return $template;
                   1460: }
                   1461: 
1.172     www      1462: sub help_open_bug {
                   1463:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1464:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1465:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1466:     $text = "" if (not defined $text);
                   1467: 	$stayOnPage=1;
1.184     albertel 1468:     $width = 600 if (not defined $width);
                   1469:     $height = 600 if (not defined $height);
1.172     www      1470: 
                   1471:     $topic=~s/\W+/\+/g;
                   1472:     my $link='';
                   1473:     my $template='';
1.379     albertel 1474:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1475: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1476:     if (!$stayOnPage)
                   1477:     {
                   1478: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1479:     }
                   1480:     else
                   1481:     {
                   1482: 	$link = $url;
                   1483:     }
                   1484:     # Add the text
                   1485:     if ($text ne "")
                   1486:     {
                   1487: 	$template .= 
                   1488:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1489:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1490:     }
                   1491: 
                   1492:     # Add the graphic
1.179     matthew  1493:     my $title = &mt('Report a Bug');
1.215     albertel 1494:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1495:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1496:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1497: ENDTEMPLATE
                   1498:     if ($text ne '') { $template.='</td></tr></table>' };
                   1499:     return $template;
                   1500: 
                   1501: }
                   1502: 
                   1503: sub help_open_faq {
                   1504:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1505:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1506:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1507:     $text = "" if (not defined $text);
                   1508: 	$stayOnPage=1;
                   1509:     $width = 350 if (not defined $width);
                   1510:     $height = 400 if (not defined $height);
                   1511: 
                   1512:     $topic=~s/\W+/\+/g;
                   1513:     my $link='';
                   1514:     my $template='';
                   1515:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1516:     if (!$stayOnPage)
                   1517:     {
                   1518: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1519:     }
                   1520:     else
                   1521:     {
                   1522: 	$link = $url;
                   1523:     }
                   1524: 
                   1525:     # Add the text
                   1526:     if ($text ne "")
                   1527:     {
                   1528: 	$template .= 
1.173     www      1529:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1530:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1531:     }
                   1532: 
                   1533:     # Add the graphic
1.179     matthew  1534:     my $title = &mt('View the FAQ');
1.215     albertel 1535:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1536:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1537:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1538: ENDTEMPLATE
                   1539:     if ($text ne '') { $template.='</td></tr></table>' };
                   1540:     return $template;
                   1541: 
1.44      bowersj2 1542: }
1.37      matthew  1543: 
1.180     matthew  1544: ###############################################################
                   1545: ###############################################################
                   1546: 
1.45      matthew  1547: =pod
                   1548: 
1.648     raeburn  1549: =item * &change_content_javascript():
1.256     matthew  1550: 
                   1551: This and the next function allow you to create small sections of an
                   1552: otherwise static HTML page that you can update on the fly with
                   1553: Javascript, even in Netscape 4.
                   1554: 
                   1555: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1556: must be written to the HTML page once. It will prove the Javascript
                   1557: function "change(name, content)". Calling the change function with the
                   1558: name of the section 
                   1559: you want to update, matching the name passed to C<changable_area>, and
                   1560: the new content you want to put in there, will put the content into
                   1561: that area.
                   1562: 
                   1563: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1564: to contain room for the original contents. You need to "make space"
                   1565: for whatever changes you wish to make, and be B<sure> to check your
                   1566: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1567: it's adequate for updating a one-line status display, but little more.
                   1568: This script will set the space to 100% width, so you only need to
                   1569: worry about height in Netscape 4.
                   1570: 
                   1571: Modern browsers are much less limiting, and if you can commit to the
                   1572: user not using Netscape 4, this feature may be used freely with
                   1573: pretty much any HTML.
                   1574: 
                   1575: =cut
                   1576: 
                   1577: sub change_content_javascript {
                   1578:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1579:     if ($env{'browser.type'} eq 'netscape' &&
                   1580: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1581: 	return (<<NETSCAPE4);
                   1582: 	function change(name, content) {
                   1583: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1584: 	    doc.open();
                   1585: 	    doc.write(content);
                   1586: 	    doc.close();
                   1587: 	}
                   1588: NETSCAPE4
                   1589:     } else {
                   1590: 	# Otherwise, we need to use semi-standards-compliant code
                   1591: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1592: 	# is really scary, and every useful browser supports it
                   1593: 	return (<<DOMBASED);
                   1594: 	function change(name, content) {
                   1595: 	    element = document.getElementById(name);
                   1596: 	    element.innerHTML = content;
                   1597: 	}
                   1598: DOMBASED
                   1599:     }
                   1600: }
                   1601: 
                   1602: =pod
                   1603: 
1.648     raeburn  1604: =item * &changable_area($name,$origContent):
1.256     matthew  1605: 
                   1606: This provides a "changable area" that can be modified on the fly via
                   1607: the Javascript code provided in C<change_content_javascript>. $name is
                   1608: the name you will use to reference the area later; do not repeat the
                   1609: same name on a given HTML page more then once. $origContent is what
                   1610: the area will originally contain, which can be left blank.
                   1611: 
                   1612: =cut
                   1613: 
                   1614: sub changable_area {
                   1615:     my ($name, $origContent) = @_;
                   1616: 
1.258     albertel 1617:     if ($env{'browser.type'} eq 'netscape' &&
                   1618: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1619: 	# If this is netscape 4, we need to use the Layer tag
                   1620: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1621:     } else {
                   1622: 	return "<span id='$name'>$origContent</span>";
                   1623:     }
                   1624: }
                   1625: 
                   1626: =pod
                   1627: 
1.648     raeburn  1628: =item * &viewport_geometry_js 
1.590     raeburn  1629: 
                   1630: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1631: 
                   1632: =cut
                   1633: 
                   1634: 
                   1635: sub viewport_geometry_js { 
                   1636:     return <<"GEOMETRY";
                   1637: var Geometry = {};
                   1638: function init_geometry() {
                   1639:     if (Geometry.init) { return };
                   1640:     Geometry.init=1;
                   1641:     if (window.innerHeight) {
                   1642:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1643:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1644:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1645:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1646:     }
                   1647:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1648:         Geometry.getViewportHeight =
                   1649:             function() { return document.documentElement.clientHeight; };
                   1650:         Geometry.getViewportWidth =
                   1651:             function() { return document.documentElement.clientWidth; };
                   1652: 
                   1653:         Geometry.getHorizontalScroll =
                   1654:             function() { return document.documentElement.scrollLeft; };
                   1655:         Geometry.getVerticalScroll =
                   1656:             function() { return document.documentElement.scrollTop; };
                   1657:     }
                   1658:     else if (document.body.clientHeight) {
                   1659:         Geometry.getViewportHeight =
                   1660:             function() { return document.body.clientHeight; };
                   1661:         Geometry.getViewportWidth =
                   1662:             function() { return document.body.clientWidth; };
                   1663:         Geometry.getHorizontalScroll =
                   1664:             function() { return document.body.scrollLeft; };
                   1665:         Geometry.getVerticalScroll =
                   1666:             function() { return document.body.scrollTop; };
                   1667:     }
                   1668: }
                   1669: 
                   1670: GEOMETRY
                   1671: }
                   1672: 
                   1673: =pod
                   1674: 
1.648     raeburn  1675: =item * &viewport_size_js()
1.590     raeburn  1676: 
                   1677: 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. 
                   1678: 
                   1679: =cut
                   1680: 
                   1681: sub viewport_size_js {
                   1682:     my $geometry = &viewport_geometry_js();
                   1683:     return <<"DIMS";
                   1684: 
                   1685: $geometry
                   1686: 
                   1687: function getViewportDims(width,height) {
                   1688:     init_geometry();
                   1689:     width.value = Geometry.getViewportWidth();
                   1690:     height.value = Geometry.getViewportHeight();
                   1691:     return;
                   1692: }
                   1693: 
                   1694: DIMS
                   1695: }
                   1696: 
                   1697: =pod
                   1698: 
1.648     raeburn  1699: =item * &resize_textarea_js()
1.565     albertel 1700: 
                   1701: emits the needed javascript to resize a textarea to be as big as possible
                   1702: 
                   1703: creates a function resize_textrea that takes two IDs first should be
                   1704: the id of the element to resize, second should be the id of a div that
                   1705: surrounds everything that comes after the textarea, this routine needs
                   1706: to be attached to the <body> for the onload and onresize events.
                   1707: 
1.648     raeburn  1708: =back
1.565     albertel 1709: 
                   1710: =cut
                   1711: 
                   1712: sub resize_textarea_js {
1.590     raeburn  1713:     my $geometry = &viewport_geometry_js();
1.565     albertel 1714:     return <<"RESIZE";
                   1715:     <script type="text/javascript">
1.824     bisitz   1716: // <![CDATA[
1.590     raeburn  1717: $geometry
1.565     albertel 1718: 
1.588     albertel 1719: function getX(element) {
                   1720:     var x = 0;
                   1721:     while (element) {
                   1722: 	x += element.offsetLeft;
                   1723: 	element = element.offsetParent;
                   1724:     }
                   1725:     return x;
                   1726: }
                   1727: function getY(element) {
                   1728:     var y = 0;
                   1729:     while (element) {
                   1730: 	y += element.offsetTop;
                   1731: 	element = element.offsetParent;
                   1732:     }
                   1733:     return y;
                   1734: }
                   1735: 
                   1736: 
1.565     albertel 1737: function resize_textarea(textarea_id,bottom_id) {
                   1738:     init_geometry();
                   1739:     var textarea        = document.getElementById(textarea_id);
                   1740:     //alert(textarea);
                   1741: 
1.588     albertel 1742:     var textarea_top    = getY(textarea);
1.565     albertel 1743:     var textarea_height = textarea.offsetHeight;
                   1744:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1745:     var bottom_top      = getY(bottom);
1.565     albertel 1746:     var bottom_height   = bottom.offsetHeight;
                   1747:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1748:     var fudge           = 23;
1.565     albertel 1749:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1750:     if (new_height < 300) {
                   1751: 	new_height = 300;
                   1752:     }
                   1753:     textarea.style.height=new_height+'px';
                   1754: }
1.824     bisitz   1755: // ]]>
1.565     albertel 1756: </script>
                   1757: RESIZE
                   1758: 
                   1759: }
                   1760: 
1.1075.2.112  raeburn  1761: sub colorfuleditor_js {
                   1762:     return <<"COLORFULEDIT"
                   1763: <script type="text/javascript">
                   1764: // <![CDATA[>
                   1765:     function fold_box(curDepth, lastresource){
                   1766: 
                   1767:     // we need a list because there can be several blocks you need to fold in one tag
                   1768:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1769:     // but there is only one folding button per tag
                   1770:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1771: 
                   1772:         if(block.item(0).style.display == 'none'){
                   1773: 
                   1774:             foldbutton.value = '@{[&mt("Hide")]}';
                   1775:             for (i = 0; i < block.length; i++){
                   1776:                 block.item(i).style.display = '';
                   1777:             }
                   1778:         }else{
                   1779: 
                   1780:             foldbutton.value = '@{[&mt("Show")]}';
                   1781:             for (i = 0; i < block.length; i++){
                   1782:                 // block.item(i).style.visibility = 'collapse';
                   1783:                 block.item(i).style.display = 'none';
                   1784:             }
                   1785:         };
                   1786:         saveState(lastresource);
                   1787:     }
                   1788: 
                   1789:     function saveState (lastresource) {
                   1790: 
                   1791:         var tag_list = getTagList();
                   1792:         if(tag_list != null){
                   1793:             var timestamp = new Date().getTime();
                   1794:             var key = lastresource;
                   1795: 
                   1796:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1797:             // starting with timestamp
                   1798:             var value = timestamp+';';
                   1799: 
                   1800:             // building the list of key-value pairs
                   1801:             for(var i = 0; i < tag_list.length; i++){
                   1802:                 value += tag_list[i]+',';
                   1803:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1804:             }
                   1805: 
                   1806:             // only iterate whole storage if nothing to override
                   1807:             if(localStorage.getItem(key) == null){
                   1808: 
                   1809:                 // prevent storage from growing large
                   1810:                 if(localStorage.length > 50){
                   1811:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1812:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1813:                     var oldest_key;
                   1814: 
                   1815:                     for(var i = 1; i < localStorage.length; i++){
                   1816:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1817:                             oldest_key = localStorage.key(i);
                   1818:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1819:                         }
                   1820:                     }
                   1821:                     localStorage.removeItem(oldest_key);
                   1822:                 }
                   1823:             }
                   1824:             localStorage.setItem(key,value);
                   1825:         }
                   1826:     }
                   1827: 
                   1828:     // restore folding status of blocks (on page load)
                   1829:     function restoreState (lastresource) {
                   1830:         if(localStorage.getItem(lastresource) != null){
                   1831:             var key = lastresource;
                   1832:             var value = localStorage.getItem(key);
                   1833:             var regex_delTimestamp = /^\d+;/;
                   1834: 
                   1835:             value.replace(regex_delTimestamp, '');
                   1836: 
                   1837:             var valueArr = value.split(';');
                   1838:             var pairs;
                   1839:             var elements;
                   1840:             for (var i = 0; i < valueArr.length; i++){
                   1841:                 pairs = valueArr[i].split(',');
                   1842:                 elements = document.getElementsByName(pairs[0]);
                   1843: 
                   1844:                 for (var j = 0; j < elements.length; j++){
                   1845:                     elements[j].style.display = pairs[1];
                   1846:                     if (pairs[1] == "none"){
                   1847:                         var regex_id = /([_\\d]+)\$/;
                   1848:                         regex_id.exec(pairs[0]);
                   1849:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1850:                     }
                   1851:                 }
                   1852:             }
                   1853:         }
                   1854:     }
                   1855: 
                   1856:     function getTagList () {
                   1857: 
                   1858:         var stringToSearch = document.lonhomework.innerHTML;
                   1859: 
                   1860:         var ret = new Array();
                   1861:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1862:         var tag_list = stringToSearch.match(regex_findBlock);
                   1863: 
                   1864:         if(tag_list != null){
                   1865:             for(var i = 0; i < tag_list.length; i++){
                   1866:                 ret.push(tag_list[i].replace(/"/, ''));
                   1867:             }
                   1868:         }
                   1869:         return ret;
                   1870:     }
                   1871: 
                   1872:     function saveScrollPosition (resource) {
                   1873:         var tag_list = getTagList();
                   1874: 
                   1875:         // we dont always want to jump to the first block
                   1876:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1877:         if(\$(window).scrollTop() > 170){
                   1878:             if(tag_list != null){
                   1879:                 var result;
                   1880:                 for(var i = 0; i < tag_list.length; i++){
                   1881:                     if(isElementInViewport(tag_list[i])){
                   1882:                         result += tag_list[i]+';';
                   1883:                     }
                   1884:                 }
                   1885:                 sessionStorage.setItem('anchor_'+resource, result);
                   1886:             }
                   1887:         } else {
                   1888:             // we dont need to save zero, just delete the item to leave everything tidy
                   1889:             sessionStorage.removeItem('anchor_'+resource);
                   1890:         }
                   1891:     }
                   1892: 
                   1893:     function restoreScrollPosition(resource){
                   1894: 
                   1895:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1896:         if(elem != null){
                   1897:             var tag_list = elem.split(';');
                   1898:             var elem_list;
                   1899: 
                   1900:             for(var i = 0; i < tag_list.length; i++){
                   1901:                 elem_list = document.getElementsByName(tag_list[i]);
                   1902: 
                   1903:                 if(elem_list.length > 0){
                   1904:                     elem = elem_list[0];
                   1905:                     break;
                   1906:                 }
                   1907:             }
                   1908:             elem.scrollIntoView();
                   1909:         }
                   1910:     }
                   1911: 
                   1912:     function isElementInViewport(el) {
                   1913: 
                   1914:         // change to last element instead of first
                   1915:         var elem = document.getElementsByName(el);
                   1916:         var rect = elem[0].getBoundingClientRect();
                   1917: 
                   1918:         return (
                   1919:             rect.top >= 0 &&
                   1920:             rect.left >= 0 &&
                   1921:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1922:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1923:         );
                   1924:     }
                   1925: 
                   1926:     function autosize(depth){
                   1927:         var cmInst = window['cm'+depth];
                   1928:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1929: 
                   1930:         // is fixed size, switching to dynamic
                   1931:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1932:             cmInst.setSize("","auto");
                   1933:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1934:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1935: 
                   1936:         // is dynamic size, switching to fixed
                   1937:         } else {
                   1938:             cmInst.setSize("","300px");
                   1939:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1940:             sessionStorage.removeItem("autosized_"+depth);
                   1941:         }
                   1942:     }
                   1943: 
                   1944: 
                   1945: 
                   1946: // ]]>
                   1947: </script>
                   1948: COLORFULEDIT
                   1949: }
                   1950: 
                   1951: sub xmleditor_js {
                   1952:     return <<XMLEDIT
                   1953: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1954: <script type="text/javascript">
                   1955: // <![CDATA[>
                   1956: 
                   1957:     function saveScrollPosition (resource) {
                   1958: 
                   1959:         var scrollPos = \$(window).scrollTop();
                   1960:         sessionStorage.setItem(resource,scrollPos);
                   1961:     }
                   1962: 
                   1963:     function restoreScrollPosition(resource){
                   1964: 
                   1965:         var scrollPos = sessionStorage.getItem(resource);
                   1966:         \$(window).scrollTop(scrollPos);
                   1967:     }
                   1968: 
                   1969:     // unless internet explorer
                   1970:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1971: 
                   1972:         \$(document).ready(function() {
                   1973:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1974:         });
                   1975:     }
                   1976: 
                   1977:     // inserts text at cursor position into codemirror (xml editor only)
                   1978:     function insertText(text){
                   1979:         cm.focus();
                   1980:         var curPos = cm.getCursor();
                   1981:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1982:     }
                   1983: // ]]>
                   1984: </script>
                   1985: XMLEDIT
                   1986: }
                   1987: 
                   1988: sub insert_folding_button {
                   1989:     my $curDepth = $Apache::lonxml::curdepth;
                   1990:     my $lastresource = $env{'request.ambiguous'};
                   1991: 
                   1992:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   1993:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   1994: }
                   1995: 
                   1996: 
1.565     albertel 1997: =pod
                   1998: 
1.256     matthew  1999: =head1 Excel and CSV file utility routines
                   2000: 
                   2001: =cut
                   2002: 
                   2003: ###############################################################
                   2004: ###############################################################
                   2005: 
                   2006: =pod
                   2007: 
1.1075.2.56  raeburn  2008: =over 4
                   2009: 
1.648     raeburn  2010: =item * &csv_translate($text) 
1.37      matthew  2011: 
1.185     www      2012: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2013: format.
                   2014: 
                   2015: =cut
                   2016: 
1.180     matthew  2017: ###############################################################
                   2018: ###############################################################
1.37      matthew  2019: sub csv_translate {
                   2020:     my $text = shift;
                   2021:     $text =~ s/\"/\"\"/g;
1.209     albertel 2022:     $text =~ s/\n/ /g;
1.37      matthew  2023:     return $text;
                   2024: }
1.180     matthew  2025: 
                   2026: ###############################################################
                   2027: ###############################################################
                   2028: 
                   2029: =pod
                   2030: 
1.648     raeburn  2031: =item * &define_excel_formats()
1.180     matthew  2032: 
                   2033: Define some commonly used Excel cell formats.
                   2034: 
                   2035: Currently supported formats:
                   2036: 
                   2037: =over 4
                   2038: 
                   2039: =item header
                   2040: 
                   2041: =item bold
                   2042: 
                   2043: =item h1
                   2044: 
                   2045: =item h2
                   2046: 
                   2047: =item h3
                   2048: 
1.256     matthew  2049: =item h4
                   2050: 
                   2051: =item i
                   2052: 
1.180     matthew  2053: =item date
                   2054: 
                   2055: =back
                   2056: 
                   2057: Inputs: $workbook
                   2058: 
                   2059: Returns: $format, a hash reference.
                   2060: 
1.1057    foxr     2061: 
1.180     matthew  2062: =cut
                   2063: 
                   2064: ###############################################################
                   2065: ###############################################################
                   2066: sub define_excel_formats {
                   2067:     my ($workbook) = @_;
                   2068:     my $format;
                   2069:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2070:                                                 bottom    => 1,
                   2071:                                                 align     => 'center');
                   2072:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2073:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2074:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2075:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2076:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2077:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2078:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2079:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2080:     return $format;
                   2081: }
                   2082: 
                   2083: ###############################################################
                   2084: ###############################################################
1.113     bowersj2 2085: 
                   2086: =pod
                   2087: 
1.648     raeburn  2088: =item * &create_workbook()
1.255     matthew  2089: 
                   2090: Create an Excel worksheet.  If it fails, output message on the
                   2091: request object and return undefs.
                   2092: 
                   2093: Inputs: Apache request object
                   2094: 
                   2095: Returns (undef) on failure, 
                   2096:     Excel worksheet object, scalar with filename, and formats 
                   2097:     from &Apache::loncommon::define_excel_formats on success
                   2098: 
                   2099: =cut
                   2100: 
                   2101: ###############################################################
                   2102: ###############################################################
                   2103: sub create_workbook {
                   2104:     my ($r) = @_;
                   2105:         #
                   2106:     # Create the excel spreadsheet
                   2107:     my $filename = '/prtspool/'.
1.258     albertel 2108:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2109:         time.'_'.rand(1000000000).'.xls';
                   2110:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2111:     if (! defined($workbook)) {
                   2112:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2113:         $r->print(
                   2114:             '<p class="LC_error">'
                   2115:            .&mt('Problems occurred in creating the new Excel file.')
                   2116:            .' '.&mt('This error has been logged.')
                   2117:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2118:            .'</p>'
                   2119:         );
1.255     matthew  2120:         return (undef);
                   2121:     }
                   2122:     #
1.1014    foxr     2123:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2124:     #
                   2125:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2126:     return ($workbook,$filename,$format);
                   2127: }
                   2128: 
                   2129: ###############################################################
                   2130: ###############################################################
                   2131: 
                   2132: =pod
                   2133: 
1.648     raeburn  2134: =item * &create_text_file()
1.113     bowersj2 2135: 
1.542     raeburn  2136: Create a file to write to and eventually make available to the user.
1.256     matthew  2137: If file creation fails, outputs an error message on the request object and 
                   2138: return undefs.
1.113     bowersj2 2139: 
1.256     matthew  2140: Inputs: Apache request object, and file suffix
1.113     bowersj2 2141: 
1.256     matthew  2142: Returns (undef) on failure, 
                   2143:     Filehandle and filename on success.
1.113     bowersj2 2144: 
                   2145: =cut
                   2146: 
1.256     matthew  2147: ###############################################################
                   2148: ###############################################################
                   2149: sub create_text_file {
                   2150:     my ($r,$suffix) = @_;
                   2151:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2152:     my $fh;
                   2153:     my $filename = '/prtspool/'.
1.258     albertel 2154:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2155:         time.'_'.rand(1000000000).'.'.$suffix;
                   2156:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2157:     if (! defined($fh)) {
                   2158:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2159:         $r->print(
                   2160:             '<p class="LC_error">'
                   2161:            .&mt('Problems occurred in creating the output file.')
                   2162:            .' '.&mt('This error has been logged.')
                   2163:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2164:            .'</p>'
                   2165:         );
1.113     bowersj2 2166:     }
1.256     matthew  2167:     return ($fh,$filename)
1.113     bowersj2 2168: }
                   2169: 
                   2170: 
1.256     matthew  2171: =pod 
1.113     bowersj2 2172: 
                   2173: =back
                   2174: 
                   2175: =cut
1.37      matthew  2176: 
                   2177: ###############################################################
1.33      matthew  2178: ##        Home server <option> list generating code          ##
                   2179: ###############################################################
1.35      matthew  2180: 
1.169     www      2181: # ------------------------------------------
                   2182: 
                   2183: sub domain_select {
                   2184:     my ($name,$value,$multiple)=@_;
                   2185:     my %domains=map { 
1.514     albertel 2186: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2187:     } &Apache::lonnet::all_domains();
1.169     www      2188:     if ($multiple) {
                   2189: 	$domains{''}=&mt('Any domain');
1.550     albertel 2190: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2191: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2192:     } else {
1.550     albertel 2193: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2194: 	return &select_form($name,$value,\%domains);
1.169     www      2195:     }
                   2196: }
                   2197: 
1.282     albertel 2198: #-------------------------------------------
                   2199: 
                   2200: =pod
                   2201: 
1.519     raeburn  2202: =head1 Routines for form select boxes
                   2203: 
                   2204: =over 4
                   2205: 
1.648     raeburn  2206: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2207: 
                   2208: Returns a string containing a <select> element int multiple mode
                   2209: 
                   2210: 
                   2211: Args:
                   2212:   $name - name of the <select> element
1.506     raeburn  2213:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2214:   $size - number of rows long the select element is
1.283     albertel 2215:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2216:           (shown text should already have been &mt())
1.506     raeburn  2217:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2218: 
1.282     albertel 2219: =cut
                   2220: 
                   2221: #-------------------------------------------
1.169     www      2222: sub multiple_select_form {
1.284     albertel 2223:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2224:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2225:     my $output='';
1.191     matthew  2226:     if (! defined($size)) {
                   2227:         $size = 4;
1.283     albertel 2228:         if (scalar(keys(%$hash))<4) {
                   2229:             $size = scalar(keys(%$hash));
1.191     matthew  2230:         }
                   2231:     }
1.734     bisitz   2232:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2233:     my @order;
1.506     raeburn  2234:     if (ref($order) eq 'ARRAY')  {
                   2235:         @order = @{$order};
                   2236:     } else {
                   2237:         @order = sort(keys(%$hash));
1.501     banghart 2238:     }
                   2239:     if (exists($$hash{'select_form_order'})) {
                   2240:         @order = @{$$hash{'select_form_order'}};
                   2241:     }
                   2242:         
1.284     albertel 2243:     foreach my $key (@order) {
1.356     albertel 2244:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2245:         $output.='selected="selected" ' if ($selected{$key});
                   2246:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2247:     }
                   2248:     $output.="</select>\n";
                   2249:     return $output;
                   2250: }
                   2251: 
1.88      www      2252: #-------------------------------------------
                   2253: 
                   2254: =pod
                   2255: 
1.1075.2.115  raeburn  2256: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2257: 
                   2258: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2259: allow a user to select options from a ref to a hash containing:
                   2260: option_name => displayed text. An optional $onchange can include
1.1075.2.115  raeburn  2261: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2262: An optional arg -- $readonly -- if true will cause the select form
                   2263: to be disabled, e.g., for the case where an instructor has a section-
                   2264: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2265: 
1.88      www      2266: See lonrights.pm for an example invocation and use.
                   2267: 
                   2268: =cut
                   2269: 
                   2270: #-------------------------------------------
                   2271: sub select_form {
1.1075.2.115  raeburn  2272:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2273:     return unless (ref($hashref) eq 'HASH');
                   2274:     if ($onchange) {
                   2275:         $onchange = ' onchange="'.$onchange.'"';
                   2276:     }
1.1075.2.129  raeburn  2277:     my $disabled;
                   2278:     if ($readonly) {
                   2279:         $disabled = ' disabled="disabled"';
                   2280:     }
                   2281:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2282:     my @keys;
1.970     raeburn  2283:     if (exists($hashref->{'select_form_order'})) {
                   2284: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2285:     } else {
1.970     raeburn  2286: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2287:     }
1.356     albertel 2288:     foreach my $key (@keys) {
                   2289:         $selectform.=
                   2290: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2291:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2292:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2293:     }
                   2294:     $selectform.="</select>";
                   2295:     return $selectform;
                   2296: }
                   2297: 
1.475     www      2298: # For display filters
                   2299: 
                   2300: sub display_filter {
1.1074    raeburn  2301:     my ($context) = @_;
1.475     www      2302:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2303:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2304:     my $phraseinput = 'hidden';
                   2305:     my $includeinput = 'hidden';
                   2306:     my ($checked,$includetypestext);
                   2307:     if ($env{'form.displayfilter'} eq 'containing') {
                   2308:         $phraseinput = 'text'; 
                   2309:         if ($context eq 'parmslog') {
                   2310:             $includeinput = 'checkbox';
                   2311:             if ($env{'form.includetypes'}) {
                   2312:                 $checked = ' checked="checked"';
                   2313:             }
                   2314:             $includetypestext = &mt('Include parameter types');
                   2315:         }
                   2316:     } else {
                   2317:         $includetypestext = '&nbsp;';
                   2318:     }
                   2319:     my ($additional,$secondid,$thirdid);
                   2320:     if ($context eq 'parmslog') {
                   2321:         $additional = 
                   2322:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2323:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2324:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2325:             '</label>';
                   2326:         $secondid = 'includetypes';
                   2327:         $thirdid = 'includetypestext';
                   2328:     }
                   2329:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2330:                                                     '$secondid','$thirdid')";
                   2331:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2332: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2333: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2334: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2335:            &mt('Filter: [_1]',
1.477     www      2336: 	   &select_form($env{'form.displayfilter'},
                   2337: 			'displayfilter',
1.970     raeburn  2338: 			{'currentfolder' => 'Current folder/page',
1.477     www      2339: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2340: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2341: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2342:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2343:                          '" />'.$additional;
                   2344: }
                   2345: 
                   2346: sub display_filter_js {
                   2347:     my $includetext = &mt('Include parameter types');
                   2348:     return <<"ENDJS";
                   2349:   
                   2350: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2351:     var firstType = 'hidden';
                   2352:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2353:         firstType = 'text';
                   2354:     }
                   2355:     firstObject = document.getElementById(firstid);
                   2356:     if (typeof(firstObject) == 'object') {
                   2357:         if (firstObject.type != firstType) {
                   2358:             changeInputType(firstObject,firstType);
                   2359:         }
                   2360:     }
                   2361:     if (context == 'parmslog') {
                   2362:         var secondType = 'hidden';
                   2363:         if (firstType == 'text') {
                   2364:             secondType = 'checkbox';
                   2365:         }
                   2366:         secondObject = document.getElementById(secondid);  
                   2367:         if (typeof(secondObject) == 'object') {
                   2368:             if (secondObject.type != secondType) {
                   2369:                 changeInputType(secondObject,secondType);
                   2370:             }
                   2371:         }
                   2372:         var textItem = document.getElementById(thirdid);
                   2373:         var currtext = textItem.innerHTML;
                   2374:         var newtext;
                   2375:         if (firstType == 'text') {
                   2376:             newtext = '$includetext';
                   2377:         } else {
                   2378:             newtext = '&nbsp;';
                   2379:         }
                   2380:         if (currtext != newtext) {
                   2381:             textItem.innerHTML = newtext;
                   2382:         }
                   2383:     }
                   2384:     return;
                   2385: }
                   2386: 
                   2387: function changeInputType(oldObject,newType) {
                   2388:     var newObject = document.createElement('input');
                   2389:     newObject.type = newType;
                   2390:     if (oldObject.size) {
                   2391:         newObject.size = oldObject.size;
                   2392:     }
                   2393:     if (oldObject.value) {
                   2394:         newObject.value = oldObject.value;
                   2395:     }
                   2396:     if (oldObject.name) {
                   2397:         newObject.name = oldObject.name;
                   2398:     }
                   2399:     if (oldObject.id) {
                   2400:         newObject.id = oldObject.id;
                   2401:     }
                   2402:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2403:     return;
                   2404: }
                   2405: 
                   2406: ENDJS
1.475     www      2407: }
                   2408: 
1.167     www      2409: sub gradeleveldescription {
                   2410:     my $gradelevel=shift;
                   2411:     my %gradelevels=(0 => 'Not specified',
                   2412: 		     1 => 'Grade 1',
                   2413: 		     2 => 'Grade 2',
                   2414: 		     3 => 'Grade 3',
                   2415: 		     4 => 'Grade 4',
                   2416: 		     5 => 'Grade 5',
                   2417: 		     6 => 'Grade 6',
                   2418: 		     7 => 'Grade 7',
                   2419: 		     8 => 'Grade 8',
                   2420: 		     9 => 'Grade 9',
                   2421: 		     10 => 'Grade 10',
                   2422: 		     11 => 'Grade 11',
                   2423: 		     12 => 'Grade 12',
                   2424: 		     13 => 'Grade 13',
                   2425: 		     14 => '100 Level',
                   2426: 		     15 => '200 Level',
                   2427: 		     16 => '300 Level',
                   2428: 		     17 => '400 Level',
                   2429: 		     18 => 'Graduate Level');
                   2430:     return &mt($gradelevels{$gradelevel});
                   2431: }
                   2432: 
1.163     www      2433: sub select_level_form {
                   2434:     my ($deflevel,$name)=@_;
                   2435:     unless ($deflevel) { $deflevel=0; }
1.167     www      2436:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2437:     for (my $i=0; $i<=18; $i++) {
                   2438:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2439:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2440:                 ">".&gradeleveldescription($i)."</option>\n";
                   2441:     }
                   2442:     $selectform.="</select>";
                   2443:     return $selectform;
1.163     www      2444: }
1.167     www      2445: 
1.35      matthew  2446: #-------------------------------------------
                   2447: 
1.45      matthew  2448: =pod
                   2449: 
1.1075.2.115  raeburn  2450: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2451: 
                   2452: Returns a string containing a <select name='$name' size='1'> form to 
                   2453: allow a user to select the domain to preform an operation in.  
                   2454: See loncreateuser.pm for an example invocation and use.
                   2455: 
1.90      www      2456: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2457: selected");
                   2458: 
1.743     raeburn  2459: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2460: 
1.910     raeburn  2461: 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.
                   2462: 
1.1075.2.36  raeburn  2463: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2464: 
1.1075.2.115  raeburn  2465: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2466: 
                   2467: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2468: 
1.35      matthew  2469: =cut
                   2470: 
                   2471: #-------------------------------------------
1.34      matthew  2472: sub select_dom_form {
1.1075.2.115  raeburn  2473:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2474:     if ($onchange) {
1.874     raeburn  2475:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2476:     }
1.1075.2.115  raeburn  2477:     if ($disabled) {
                   2478:         $disabled = ' disabled="disabled"';
                   2479:     }
1.1075.2.36  raeburn  2480:     my (@domains,%exclude);
1.910     raeburn  2481:     if (ref($incdoms) eq 'ARRAY') {
                   2482:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2483:     } else {
                   2484:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2485:     }
1.90      www      2486:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2487:     if (ref($excdoms) eq 'ARRAY') {
                   2488:         map { $exclude{$_} = 1; } @{$excdoms};
                   2489:     }
1.1075.2.115  raeburn  2490:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2491:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2492:         next if ($exclude{$dom});
1.356     albertel 2493:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2494:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2495:         if ($showdomdesc) {
                   2496:             if ($dom ne '') {
                   2497:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2498:                 if ($domdesc ne '') {
                   2499:                     $selectdomain .= ' ('.$domdesc.')';
                   2500:                 }
                   2501:             } 
                   2502:         }
                   2503:         $selectdomain .= "</option>\n";
1.34      matthew  2504:     }
                   2505:     $selectdomain.="</select>";
                   2506:     return $selectdomain;
                   2507: }
                   2508: 
1.35      matthew  2509: #-------------------------------------------
                   2510: 
1.45      matthew  2511: =pod
                   2512: 
1.648     raeburn  2513: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2514: 
1.586     raeburn  2515: input: 4 arguments (two required, two optional) - 
                   2516:     $domain - domain of new user
                   2517:     $name - name of form element
                   2518:     $default - Value of 'default' causes a default item to be first 
                   2519:                             option, and selected by default. 
                   2520:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2521:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2522: output: returns 2 items: 
1.586     raeburn  2523: (a) form element which contains either:
                   2524:    (i) <select name="$name">
                   2525:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2526:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2527:        </select>
                   2528:        form item if there are multiple library servers in $domain, or
                   2529:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2530:        if there is only one library server in $domain.
                   2531: 
                   2532: (b) number of library servers found.
                   2533: 
                   2534: See loncreateuser.pm for example of use.
1.35      matthew  2535: 
                   2536: =cut
                   2537: 
                   2538: #-------------------------------------------
1.586     raeburn  2539: sub home_server_form_item {
                   2540:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2541:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2542:     my $result;
                   2543:     my $numlib = keys(%servers);
                   2544:     if ($numlib > 1) {
                   2545:         $result .= '<select name="'.$name.'" />'."\n";
                   2546:         if ($default) {
1.804     bisitz   2547:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2548:                        '</option>'."\n";
                   2549:         }
                   2550:         foreach my $hostid (sort(keys(%servers))) {
                   2551:             $result.= '<option value="'.$hostid.'">'.
                   2552: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2553:         }
                   2554:         $result .= '</select>'."\n";
                   2555:     } elsif ($numlib == 1) {
                   2556:         my $hostid;
                   2557:         foreach my $item (keys(%servers)) {
                   2558:             $hostid = $item;
                   2559:         }
                   2560:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2561:                    $hostid.'" />';
                   2562:                    if (!$hide) {
                   2563:                        $result .= $hostid.' '.$servers{$hostid};
                   2564:                    }
                   2565:                    $result .= "\n";
                   2566:     } elsif ($default) {
                   2567:         $result .= '<input type="hidden" name="'.$name.
                   2568:                    '" value="default" />';
                   2569:                    if (!$hide) {
                   2570:                        $result .= &mt('default');
                   2571:                    }
                   2572:                    $result .= "\n";
1.33      matthew  2573:     }
1.586     raeburn  2574:     return ($result,$numlib);
1.33      matthew  2575: }
1.112     bowersj2 2576: 
                   2577: =pod
                   2578: 
1.534     albertel 2579: =back 
                   2580: 
1.112     bowersj2 2581: =cut
1.87      matthew  2582: 
                   2583: ###############################################################
1.112     bowersj2 2584: ##                  Decoding User Agent                      ##
1.87      matthew  2585: ###############################################################
                   2586: 
                   2587: =pod
                   2588: 
1.112     bowersj2 2589: =head1 Decoding the User Agent
                   2590: 
                   2591: =over 4
                   2592: 
                   2593: =item * &decode_user_agent()
1.87      matthew  2594: 
                   2595: Inputs: $r
                   2596: 
                   2597: Outputs:
                   2598: 
                   2599: =over 4
                   2600: 
1.112     bowersj2 2601: =item * $httpbrowser
1.87      matthew  2602: 
1.112     bowersj2 2603: =item * $clientbrowser
1.87      matthew  2604: 
1.112     bowersj2 2605: =item * $clientversion
1.87      matthew  2606: 
1.112     bowersj2 2607: =item * $clientmathml
1.87      matthew  2608: 
1.112     bowersj2 2609: =item * $clientunicode
1.87      matthew  2610: 
1.112     bowersj2 2611: =item * $clientos
1.87      matthew  2612: 
1.1075.2.42  raeburn  2613: =item * $clientmobile
                   2614: 
                   2615: =item * $clientinfo
                   2616: 
1.1075.2.77  raeburn  2617: =item * $clientosversion
                   2618: 
1.87      matthew  2619: =back
                   2620: 
1.157     matthew  2621: =back 
                   2622: 
1.87      matthew  2623: =cut
                   2624: 
                   2625: ###############################################################
                   2626: ###############################################################
                   2627: sub decode_user_agent {
1.247     albertel 2628:     my ($r)=@_;
1.87      matthew  2629:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2630:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2631:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2632:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2633:     my $clientbrowser='unknown';
                   2634:     my $clientversion='0';
                   2635:     my $clientmathml='';
                   2636:     my $clientunicode='0';
1.1075.2.42  raeburn  2637:     my $clientmobile=0;
1.1075.2.77  raeburn  2638:     my $clientosversion='';
1.87      matthew  2639:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2640:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2641: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2642: 	    $clientbrowser=$bname;
                   2643:             $httpbrowser=~/$vreg/i;
                   2644: 	    $clientversion=$1;
                   2645:             $clientmathml=($clientversion>=$minv);
                   2646:             $clientunicode=($clientversion>=$univ);
                   2647: 	}
                   2648:     }
                   2649:     my $clientos='unknown';
1.1075.2.42  raeburn  2650:     my $clientinfo;
1.87      matthew  2651:     if (($httpbrowser=~/linux/i) ||
                   2652:         ($httpbrowser=~/unix/i) ||
                   2653:         ($httpbrowser=~/ux/i) ||
                   2654:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2655:     if (($httpbrowser=~/vax/i) ||
                   2656:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2657:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2658:     if (($httpbrowser=~/mac/i) ||
                   2659:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2660:     if ($httpbrowser=~/win/i) {
                   2661:         $clientos='win';
                   2662:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2663:             $clientosversion = $1;
                   2664:         }
                   2665:     }
1.87      matthew  2666:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2667:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2668:         $clientmobile=lc($1);
                   2669:     }
                   2670:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2671:         $clientinfo = 'firefox-'.$1;
                   2672:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2673:         $clientinfo = 'chromeframe-'.$1;
                   2674:     }
1.87      matthew  2675:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2676:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2677:             $clientosversion);
1.87      matthew  2678: }
                   2679: 
1.32      matthew  2680: ###############################################################
                   2681: ##    Authentication changing form generation subroutines    ##
                   2682: ###############################################################
                   2683: ##
                   2684: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2685: ## hash, and have reasonable default values.
                   2686: ##
                   2687: ##    formname = the name given in the <form> tag.
1.35      matthew  2688: #-------------------------------------------
                   2689: 
1.45      matthew  2690: =pod
                   2691: 
1.112     bowersj2 2692: =head1 Authentication Routines
                   2693: 
                   2694: =over 4
                   2695: 
1.648     raeburn  2696: =item * &authform_xxxxxx()
1.35      matthew  2697: 
                   2698: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2699: handle some of the conveniences required for authentication forms.  
                   2700: This is not an optimal method, but it works.  
                   2701: 
                   2702: =over 4
                   2703: 
1.112     bowersj2 2704: =item * authform_header
1.35      matthew  2705: 
1.112     bowersj2 2706: =item * authform_authorwarning
1.35      matthew  2707: 
1.112     bowersj2 2708: =item * authform_nochange
1.35      matthew  2709: 
1.112     bowersj2 2710: =item * authform_kerberos
1.35      matthew  2711: 
1.112     bowersj2 2712: =item * authform_internal
1.35      matthew  2713: 
1.112     bowersj2 2714: =item * authform_filesystem
1.35      matthew  2715: 
                   2716: =back
                   2717: 
1.648     raeburn  2718: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2719: 
1.35      matthew  2720: =cut
                   2721: 
                   2722: #-------------------------------------------
1.32      matthew  2723: sub authform_header{  
                   2724:     my %in = (
                   2725:         formname => 'cu',
1.80      albertel 2726:         kerb_def_dom => '',
1.32      matthew  2727:         @_,
                   2728:     );
                   2729:     $in{'formname'} = 'document.' . $in{'formname'};
                   2730:     my $result='';
1.80      albertel 2731: 
                   2732: #---------------------------------------------- Code for upper case translation
                   2733:     my $Javascript_toUpperCase;
                   2734:     unless ($in{kerb_def_dom}) {
                   2735:         $Javascript_toUpperCase =<<"END";
                   2736:         switch (choice) {
                   2737:            case 'krb': currentform.elements[choicearg].value =
                   2738:                currentform.elements[choicearg].value.toUpperCase();
                   2739:                break;
                   2740:            default:
                   2741:         }
                   2742: END
                   2743:     } else {
                   2744:         $Javascript_toUpperCase = "";
                   2745:     }
                   2746: 
1.165     raeburn  2747:     my $radioval = "'nochange'";
1.591     raeburn  2748:     if (defined($in{'curr_authtype'})) {
                   2749:         if ($in{'curr_authtype'} ne '') {
                   2750:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2751:         }
1.174     matthew  2752:     }
1.165     raeburn  2753:     my $argfield = 'null';
1.591     raeburn  2754:     if (defined($in{'mode'})) {
1.165     raeburn  2755:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2756:             if (defined($in{'curr_autharg'})) {
                   2757:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2758:                     $argfield = "'$in{'curr_autharg'}'";
                   2759:                 }
                   2760:             }
                   2761:         }
                   2762:     }
                   2763: 
1.32      matthew  2764:     $result.=<<"END";
                   2765: var current = new Object();
1.165     raeburn  2766: current.radiovalue = $radioval;
                   2767: current.argfield = $argfield;
1.32      matthew  2768: 
                   2769: function changed_radio(choice,currentform) {
                   2770:     var choicearg = choice + 'arg';
                   2771:     // If a radio button in changed, we need to change the argfield
                   2772:     if (current.radiovalue != choice) {
                   2773:         current.radiovalue = choice;
                   2774:         if (current.argfield != null) {
                   2775:             currentform.elements[current.argfield].value = '';
                   2776:         }
                   2777:         if (choice == 'nochange') {
                   2778:             current.argfield = null;
                   2779:         } else {
                   2780:             current.argfield = choicearg;
                   2781:             switch(choice) {
                   2782:                 case 'krb': 
                   2783:                     currentform.elements[current.argfield].value = 
                   2784:                         "$in{'kerb_def_dom'}";
                   2785:                 break;
                   2786:               default:
                   2787:                 break;
                   2788:             }
                   2789:         }
                   2790:     }
                   2791:     return;
                   2792: }
1.22      www      2793: 
1.32      matthew  2794: function changed_text(choice,currentform) {
                   2795:     var choicearg = choice + 'arg';
                   2796:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2797:         $Javascript_toUpperCase
1.32      matthew  2798:         // clear old field
                   2799:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2800:             currentform.elements[current.argfield].value = '';
                   2801:         }
                   2802:         current.argfield = choicearg;
                   2803:     }
                   2804:     set_auth_radio_buttons(choice,currentform);
                   2805:     return;
1.20      www      2806: }
1.32      matthew  2807: 
                   2808: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2809:     var numauthchoices = currentform.login.length;
                   2810:     if (typeof numauthchoices  == "undefined") {
                   2811:         return;
                   2812:     } 
1.32      matthew  2813:     var i=0;
1.986     raeburn  2814:     while (i < numauthchoices) {
1.32      matthew  2815:         if (currentform.login[i].value == newvalue) { break; }
                   2816:         i++;
                   2817:     }
1.986     raeburn  2818:     if (i == numauthchoices) {
1.32      matthew  2819:         return;
                   2820:     }
                   2821:     current.radiovalue = newvalue;
                   2822:     currentform.login[i].checked = true;
                   2823:     return;
                   2824: }
                   2825: END
                   2826:     return $result;
                   2827: }
                   2828: 
1.1075.2.20  raeburn  2829: sub authform_authorwarning {
1.32      matthew  2830:     my $result='';
1.144     matthew  2831:     $result='<i>'.
                   2832:         &mt('As a general rule, only authors or co-authors should be '.
                   2833:             'filesystem authenticated '.
                   2834:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2835:     return $result;
                   2836: }
                   2837: 
1.1075.2.20  raeburn  2838: sub authform_nochange {
1.32      matthew  2839:     my %in = (
                   2840:               formname => 'document.cu',
                   2841:               kerb_def_dom => 'MSU.EDU',
                   2842:               @_,
                   2843:           );
1.1075.2.20  raeburn  2844:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2845:     my $result;
1.1075.2.20  raeburn  2846:     if (!$authnum) {
                   2847:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2848:     } else {
                   2849:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2850:                   '<input type="radio" name="login" value="nochange" '.
                   2851:                   'checked="checked" onclick="'.
1.281     albertel 2852:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2853: 	    '</label>';
1.586     raeburn  2854:     }
1.32      matthew  2855:     return $result;
                   2856: }
                   2857: 
1.591     raeburn  2858: sub authform_kerberos {
1.32      matthew  2859:     my %in = (
                   2860:               formname => 'document.cu',
                   2861:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2862:               kerb_def_auth => 'krb4',
1.32      matthew  2863:               @_,
                   2864:               );
1.586     raeburn  2865:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2866:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2867:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2868:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2869:        $check5 = ' checked="checked"';
1.80      albertel 2870:     } else {
1.772     bisitz   2871:        $check4 = ' checked="checked"';
1.80      albertel 2872:     }
1.1075.2.117  raeburn  2873:     if ($in{'readonly'}) {
                   2874:         $disabled = ' disabled="disabled"';
                   2875:     }
1.165     raeburn  2876:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2877:     if (defined($in{'curr_authtype'})) {
                   2878:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2879:             $krbcheck = ' checked="checked"';
1.623     raeburn  2880:             if (defined($in{'mode'})) {
                   2881:                 if ($in{'mode'} eq 'modifyuser') {
                   2882:                     $krbcheck = '';
                   2883:                 }
                   2884:             }
1.591     raeburn  2885:             if (defined($in{'curr_kerb_ver'})) {
                   2886:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2887:                     $check5 = ' checked="checked"';
1.591     raeburn  2888:                     $check4 = '';
                   2889:                 } else {
1.772     bisitz   2890:                     $check4 = ' checked="checked"';
1.591     raeburn  2891:                     $check5 = '';
                   2892:                 }
1.586     raeburn  2893:             }
1.591     raeburn  2894:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2895:                 $krbarg = $in{'curr_autharg'};
                   2896:             }
1.586     raeburn  2897:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2898:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2899:                     $result = 
                   2900:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2901:         $in{'curr_autharg'},$krbver);
                   2902:                 } else {
                   2903:                     $result =
                   2904:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2905:                 }
                   2906:                 return $result; 
                   2907:             }
                   2908:         }
                   2909:     } else {
                   2910:         if ($authnum == 1) {
1.784     bisitz   2911:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2912:         }
                   2913:     }
1.586     raeburn  2914:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2915:         return;
1.587     raeburn  2916:     } elsif ($authtype eq '') {
1.591     raeburn  2917:         if (defined($in{'mode'})) {
1.587     raeburn  2918:             if ($in{'mode'} eq 'modifycourse') {
                   2919:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2920:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  2921:                 }
                   2922:             }
                   2923:         }
1.586     raeburn  2924:     }
                   2925:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2926:     if ($authtype eq '') {
                   2927:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2928:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  2929:                     $krbcheck.$disabled.' />';
1.586     raeburn  2930:     }
                   2931:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2932:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2933:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2934:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2935:          $in{'curr_authtype'} eq 'krb4')) {
                   2936:         $result .= &mt
1.144     matthew  2937:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2938:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2939:          '<label>'.$authtype,
1.281     albertel 2940:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2941:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2942:              'onchange="'.$jscall.'"'.$disabled.' />',
                   2943:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   2944:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 2945: 	 '</label>');
1.586     raeburn  2946:     } elsif ($can_assign{'krb4'}) {
                   2947:         $result .= &mt
                   2948:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2949:          '[_3] Version 4 [_4]',
                   2950:          '<label>'.$authtype,
                   2951:          '</label><input type="text" size="10" name="krbarg" '.
                   2952:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2953:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2954:          '<label><input type="hidden" name="krbver" value="4" />',
                   2955:          '</label>');
                   2956:     } elsif ($can_assign{'krb5'}) {
                   2957:         $result .= &mt
                   2958:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2959:          '[_3] Version 5 [_4]',
                   2960:          '<label>'.$authtype,
                   2961:          '</label><input type="text" size="10" name="krbarg" '.
                   2962:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2963:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2964:          '<label><input type="hidden" name="krbver" value="5" />',
                   2965:          '</label>');
                   2966:     }
1.32      matthew  2967:     return $result;
                   2968: }
                   2969: 
1.1075.2.20  raeburn  2970: sub authform_internal {
1.586     raeburn  2971:     my %in = (
1.32      matthew  2972:                 formname => 'document.cu',
                   2973:                 kerb_def_dom => 'MSU.EDU',
                   2974:                 @_,
                   2975:                 );
1.1075.2.117  raeburn  2976:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2977:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  2978:     if ($in{'readonly'}) {
                   2979:         $disabled = ' disabled="disabled"';
                   2980:     }
1.591     raeburn  2981:     if (defined($in{'curr_authtype'})) {
                   2982:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2983:             if ($can_assign{'int'}) {
1.772     bisitz   2984:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2985:                 if (defined($in{'mode'})) {
                   2986:                     if ($in{'mode'} eq 'modifyuser') {
                   2987:                         $intcheck = '';
                   2988:                     }
                   2989:                 }
1.591     raeburn  2990:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2991:                     $intarg = $in{'curr_autharg'};
                   2992:                 }
                   2993:             } else {
                   2994:                 $result = &mt('Currently internally authenticated.');
                   2995:                 return $result;
1.165     raeburn  2996:             }
                   2997:         }
1.586     raeburn  2998:     } else {
                   2999:         if ($authnum == 1) {
1.784     bisitz   3000:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3001:         }
                   3002:     }
                   3003:     if (!$can_assign{'int'}) {
                   3004:         return;
1.587     raeburn  3005:     } elsif ($authtype eq '') {
1.591     raeburn  3006:         if (defined($in{'mode'})) {
1.587     raeburn  3007:             if ($in{'mode'} eq 'modifycourse') {
                   3008:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3009:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3010:                 }
                   3011:             }
                   3012:         }
1.165     raeburn  3013:     }
1.586     raeburn  3014:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3015:     if ($authtype eq '') {
                   3016:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  3017:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3018:     }
1.605     bisitz   3019:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3020:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3021:     $result = &mt
1.144     matthew  3022:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3023:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3024:     $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  3025:     return $result;
                   3026: }
                   3027: 
1.1075.2.20  raeburn  3028: sub authform_local {
1.32      matthew  3029:     my %in = (
                   3030:               formname => 'document.cu',
                   3031:               kerb_def_dom => 'MSU.EDU',
                   3032:               @_,
                   3033:               );
1.1075.2.117  raeburn  3034:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3035:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3036:     if ($in{'readonly'}) {
                   3037:         $disabled = ' disabled="disabled"';
                   3038:     }
1.591     raeburn  3039:     if (defined($in{'curr_authtype'})) {
                   3040:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3041:             if ($can_assign{'loc'}) {
1.772     bisitz   3042:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3043:                 if (defined($in{'mode'})) {
                   3044:                     if ($in{'mode'} eq 'modifyuser') {
                   3045:                         $loccheck = '';
                   3046:                     }
                   3047:                 }
1.591     raeburn  3048:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3049:                     $locarg = $in{'curr_autharg'};
                   3050:                 }
                   3051:             } else {
                   3052:                 $result = &mt('Currently using local (institutional) authentication.');
                   3053:                 return $result;
1.165     raeburn  3054:             }
                   3055:         }
1.586     raeburn  3056:     } else {
                   3057:         if ($authnum == 1) {
1.784     bisitz   3058:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3059:         }
                   3060:     }
                   3061:     if (!$can_assign{'loc'}) {
                   3062:         return;
1.587     raeburn  3063:     } elsif ($authtype eq '') {
1.591     raeburn  3064:         if (defined($in{'mode'})) {
1.587     raeburn  3065:             if ($in{'mode'} eq 'modifycourse') {
                   3066:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3067:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3068:                 }
                   3069:             }
                   3070:         }
1.165     raeburn  3071:     }
1.586     raeburn  3072:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3073:     if ($authtype eq '') {
                   3074:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3075:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3076:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3077:     }
                   3078:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3079:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3080:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3081:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3082:     return $result;
                   3083: }
                   3084: 
1.1075.2.20  raeburn  3085: sub authform_filesystem {
1.32      matthew  3086:     my %in = (
                   3087:               formname => 'document.cu',
                   3088:               kerb_def_dom => 'MSU.EDU',
                   3089:               @_,
                   3090:               );
1.1075.2.117  raeburn  3091:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3092:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3093:     if ($in{'readonly'}) {
                   3094:         $disabled = ' disabled="disabled"';
                   3095:     }
1.591     raeburn  3096:     if (defined($in{'curr_authtype'})) {
                   3097:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3098:             if ($can_assign{'fsys'}) {
1.772     bisitz   3099:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3100:                 if (defined($in{'mode'})) {
                   3101:                     if ($in{'mode'} eq 'modifyuser') {
                   3102:                         $fsyscheck = '';
                   3103:                     }
                   3104:                 }
1.586     raeburn  3105:             } else {
                   3106:                 $result = &mt('Currently Filesystem Authenticated.');
                   3107:                 return $result;
                   3108:             }           
                   3109:         }
                   3110:     } else {
                   3111:         if ($authnum == 1) {
1.784     bisitz   3112:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3113:         }
                   3114:     }
                   3115:     if (!$can_assign{'fsys'}) {
                   3116:         return;
1.587     raeburn  3117:     } elsif ($authtype eq '') {
1.591     raeburn  3118:         if (defined($in{'mode'})) {
1.587     raeburn  3119:             if ($in{'mode'} eq 'modifycourse') {
                   3120:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3121:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3122:                 }
                   3123:             }
                   3124:         }
1.586     raeburn  3125:     }
                   3126:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3127:     if ($authtype eq '') {
                   3128:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3129:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3130:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3131:     }
                   3132:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3133:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3134:     $result = &mt
1.144     matthew  3135:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3136:          '<label><input type="radio" name="login" value="fsys" '.
1.1075.2.117  raeburn  3137:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
1.605     bisitz   3138:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.1075.2.117  raeburn  3139:                   'onchange="'.$jscall.'"'.$disabled.' />');
1.32      matthew  3140:     return $result;
                   3141: }
                   3142: 
1.586     raeburn  3143: sub get_assignable_auth {
                   3144:     my ($dom) = @_;
                   3145:     if ($dom eq '') {
                   3146:         $dom = $env{'request.role.domain'};
                   3147:     }
                   3148:     my %can_assign = (
                   3149:                           krb4 => 1,
                   3150:                           krb5 => 1,
                   3151:                           int  => 1,
                   3152:                           loc  => 1,
                   3153:                      );
                   3154:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3155:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3156:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3157:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3158:             my $context;
                   3159:             if ($env{'request.role'} =~ /^au/) {
                   3160:                 $context = 'author';
1.1075.2.117  raeburn  3161:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3162:                 $context = 'domain';
                   3163:             } elsif ($env{'request.course.id'}) {
                   3164:                 $context = 'course';
                   3165:             }
                   3166:             if ($context) {
                   3167:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3168:                    %can_assign = %{$authhash->{$context}}; 
                   3169:                 }
                   3170:             }
                   3171:         }
                   3172:     }
                   3173:     my $authnum = 0;
                   3174:     foreach my $key (keys(%can_assign)) {
                   3175:         if ($can_assign{$key}) {
                   3176:             $authnum ++;
                   3177:         }
                   3178:     }
                   3179:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3180:         $authnum --;
                   3181:     }
                   3182:     return ($authnum,%can_assign);
                   3183: }
                   3184: 
1.1075.2.137  raeburn  3185: sub check_passwd_rules {
                   3186:     my ($domain,$plainpass) = @_;
                   3187:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3188:     my ($min,$max,@chars,@brokerule,$warning);
1.1075.2.138  raeburn  3189:     $min = $Apache::lonnet::passwdmin;
1.1075.2.137  raeburn  3190:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3191:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1075.2.138  raeburn  3192:             if ($passwdconf{'min'} > $min) {
                   3193:                 $min = $passwdconf{'min'};
                   3194:             }
1.1075.2.137  raeburn  3195:         }
                   3196:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3197:             $max = $passwdconf{'max'};
                   3198:         }
                   3199:         @chars = @{$passwdconf{'chars'}};
                   3200:     }
                   3201:     if (($min) && (length($plainpass) < $min)) {
                   3202:         push(@brokerule,'min');
                   3203:     }
                   3204:     if (($max) && (length($plainpass) > $max)) {
                   3205:         push(@brokerule,'max');
                   3206:     }
                   3207:     if (@chars) {
                   3208:         my %rules;
                   3209:         map { $rules{$_} = 1; } @chars;
                   3210:         if ($rules{'uc'}) {
                   3211:             unless ($plainpass =~ /[A-Z]/) {
                   3212:                 push(@brokerule,'uc');
                   3213:             }
                   3214:         }
                   3215:         if ($rules{'lc'}) {
                   3216:             unless ($plainpass =~ /[a-z]/) {
                   3217:                 push(@brokerule,'lc');
                   3218:             }
                   3219:         }
                   3220:         if ($rules{'num'}) {
                   3221:             unless ($plainpass =~ /\d/) {
                   3222:                 push(@brokerule,'num');
                   3223:             }
                   3224:         }
                   3225:         if ($rules{'spec'}) {
                   3226:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3227:                 push(@brokerule,'spec');
                   3228:             }
                   3229:         }
                   3230:     }
                   3231:     if (@brokerule) {
                   3232:         my %rulenames = &Apache::lonlocal::texthash(
                   3233:             uc   => 'At least one upper case letter',
                   3234:             lc   => 'At least one lower case letter',
                   3235:             num  => 'At least one number',
                   3236:             spec => 'At least one non-alphanumeric',
                   3237:         );
                   3238:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3239:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3240:         $rulenames{'num'} .= ': 0123456789';
                   3241:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3242:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3243:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3244:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1075.2.141.  .3(raebu 3245:20):         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1075.2.137  raeburn  3246:             if (grep(/^$rule$/,@brokerule)) {
                   3247:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3248:             }
                   3249:         }
                   3250:         $warning .= '</ul>';
                   3251:     }
                   3252:     if (wantarray) {
                   3253:         return @brokerule;
                   3254:     }
                   3255:     return $warning;
                   3256: }
                   3257: 
1.80      albertel 3258: ###############################################################
                   3259: ##    Get Kerberos Defaults for Domain                 ##
                   3260: ###############################################################
                   3261: ##
                   3262: ## Returns default kerberos version and an associated argument
                   3263: ## as listed in file domain.tab. If not listed, provides
                   3264: ## appropriate default domain and kerberos version.
                   3265: ##
                   3266: #-------------------------------------------
                   3267: 
                   3268: =pod
                   3269: 
1.648     raeburn  3270: =item * &get_kerberos_defaults()
1.80      albertel 3271: 
                   3272: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3273: version and domain. If not found, it defaults to version 4 and the 
                   3274: domain of the server.
1.80      albertel 3275: 
1.648     raeburn  3276: =over 4
                   3277: 
1.80      albertel 3278: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3279: 
1.648     raeburn  3280: =back
                   3281: 
                   3282: =back
                   3283: 
1.80      albertel 3284: =cut
                   3285: 
                   3286: #-------------------------------------------
                   3287: sub get_kerberos_defaults {
                   3288:     my $domain=shift;
1.641     raeburn  3289:     my ($krbdef,$krbdefdom);
                   3290:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3291:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3292:         $krbdef = $domdefaults{'auth_def'};
                   3293:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3294:     } else {
1.80      albertel 3295:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3296:         my $krbdefdom=$1;
                   3297:         $krbdefdom=~tr/a-z/A-Z/;
                   3298:         $krbdef = "krb4";
                   3299:     }
                   3300:     return ($krbdef,$krbdefdom);
                   3301: }
1.112     bowersj2 3302: 
1.32      matthew  3303: 
1.46      matthew  3304: ###############################################################
                   3305: ##                Thesaurus Functions                        ##
                   3306: ###############################################################
1.20      www      3307: 
1.46      matthew  3308: =pod
1.20      www      3309: 
1.112     bowersj2 3310: =head1 Thesaurus Functions
                   3311: 
                   3312: =over 4
                   3313: 
1.648     raeburn  3314: =item * &initialize_keywords()
1.46      matthew  3315: 
                   3316: Initializes the package variable %Keywords if it is empty.  Uses the
                   3317: package variable $thesaurus_db_file.
                   3318: 
                   3319: =cut
                   3320: 
                   3321: ###################################################
                   3322: 
                   3323: sub initialize_keywords {
                   3324:     return 1 if (scalar keys(%Keywords));
                   3325:     # If we are here, %Keywords is empty, so fill it up
                   3326:     #   Make sure the file we need exists...
                   3327:     if (! -e $thesaurus_db_file) {
                   3328:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3329:                                  " failed because it does not exist");
                   3330:         return 0;
                   3331:     }
                   3332:     #   Set up the hash as a database
                   3333:     my %thesaurus_db;
                   3334:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3335:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3336:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3337:                                  $thesaurus_db_file);
                   3338:         return 0;
                   3339:     } 
                   3340:     #  Get the average number of appearances of a word.
                   3341:     my $avecount = $thesaurus_db{'average.count'};
                   3342:     #  Put keywords (those that appear > average) into %Keywords
                   3343:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3344:         my ($count,undef) = split /:/,$data;
                   3345:         $Keywords{$word}++ if ($count > $avecount);
                   3346:     }
                   3347:     untie %thesaurus_db;
                   3348:     # Remove special values from %Keywords.
1.356     albertel 3349:     foreach my $value ('total.count','average.count') {
                   3350:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3351:   }
1.46      matthew  3352:     return 1;
                   3353: }
                   3354: 
                   3355: ###################################################
                   3356: 
                   3357: =pod
                   3358: 
1.648     raeburn  3359: =item * &keyword($word)
1.46      matthew  3360: 
                   3361: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3362: than the average number of times in the thesaurus database.  Calls 
                   3363: &initialize_keywords
                   3364: 
                   3365: =cut
                   3366: 
                   3367: ###################################################
1.20      www      3368: 
                   3369: sub keyword {
1.46      matthew  3370:     return if (!&initialize_keywords());
                   3371:     my $word=lc(shift());
                   3372:     $word=~s/\W//g;
                   3373:     return exists($Keywords{$word});
1.20      www      3374: }
1.46      matthew  3375: 
                   3376: ###############################################################
                   3377: 
                   3378: =pod 
1.20      www      3379: 
1.648     raeburn  3380: =item * &get_related_words()
1.46      matthew  3381: 
1.160     matthew  3382: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3383: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3384: will be returned.  The order of the words returned is determined by the
                   3385: database which holds them.
                   3386: 
                   3387: Uses global $thesaurus_db_file.
                   3388: 
1.1057    foxr     3389: 
1.46      matthew  3390: =cut
                   3391: 
                   3392: ###############################################################
                   3393: sub get_related_words {
                   3394:     my $keyword = shift;
                   3395:     my %thesaurus_db;
                   3396:     if (! -e $thesaurus_db_file) {
                   3397:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3398:                                  "failed because the file does not exist");
                   3399:         return ();
                   3400:     }
                   3401:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3402:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3403:         return ();
                   3404:     } 
                   3405:     my @Words=();
1.429     www      3406:     my $count=0;
1.46      matthew  3407:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3408: 	# The first element is the number of times
                   3409: 	# the word appears.  We do not need it now.
1.429     www      3410: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3411: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3412: 	my $threshold=$mostfrequentcount/10;
                   3413:         foreach my $possibleword (@RelatedWords) {
                   3414:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3415:             if ($wordcount>$threshold) {
                   3416: 		push(@Words,$word);
                   3417:                 $count++;
                   3418:                 if ($count>10) { last; }
                   3419: 	    }
1.20      www      3420:         }
                   3421:     }
1.46      matthew  3422:     untie %thesaurus_db;
                   3423:     return @Words;
1.14      harris41 3424: }
1.46      matthew  3425: 
1.112     bowersj2 3426: =pod
                   3427: 
                   3428: =back
                   3429: 
                   3430: =cut
1.61      www      3431: 
                   3432: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3433: =pod
                   3434: 
1.112     bowersj2 3435: =head1 User Name Functions
                   3436: 
                   3437: =over 4
                   3438: 
1.648     raeburn  3439: =item * &plainname($uname,$udom,$first)
1.81      albertel 3440: 
1.112     bowersj2 3441: Takes a users logon name and returns it as a string in
1.226     albertel 3442: "first middle last generation" form 
                   3443: if $first is set to 'lastname' then it returns it as
                   3444: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3445: 
                   3446: =cut
1.61      www      3447: 
1.295     www      3448: 
1.81      albertel 3449: ###############################################################
1.61      www      3450: sub plainname {
1.226     albertel 3451:     my ($uname,$udom,$first)=@_;
1.537     albertel 3452:     return if (!defined($uname) || !defined($udom));
1.295     www      3453:     my %names=&getnames($uname,$udom);
1.226     albertel 3454:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3455: 					  $names{'middlename'},
                   3456: 					  $names{'lastname'},
                   3457: 					  $names{'generation'},$first);
                   3458:     $name=~s/^\s+//;
1.62      www      3459:     $name=~s/\s+$//;
                   3460:     $name=~s/\s+/ /g;
1.353     albertel 3461:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3462:     return $name;
1.61      www      3463: }
1.66      www      3464: 
                   3465: # -------------------------------------------------------------------- Nickname
1.81      albertel 3466: =pod
                   3467: 
1.648     raeburn  3468: =item * &nickname($uname,$udom)
1.81      albertel 3469: 
                   3470: Gets a users name and returns it as a string as
                   3471: 
                   3472: "&quot;nickname&quot;"
1.66      www      3473: 
1.81      albertel 3474: if the user has a nickname or
                   3475: 
                   3476: "first middle last generation"
                   3477: 
                   3478: if the user does not
                   3479: 
                   3480: =cut
1.66      www      3481: 
                   3482: sub nickname {
                   3483:     my ($uname,$udom)=@_;
1.537     albertel 3484:     return if (!defined($uname) || !defined($udom));
1.295     www      3485:     my %names=&getnames($uname,$udom);
1.68      albertel 3486:     my $name=$names{'nickname'};
1.66      www      3487:     if ($name) {
                   3488:        $name='&quot;'.$name.'&quot;'; 
                   3489:     } else {
                   3490:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3491: 	     $names{'lastname'}.' '.$names{'generation'};
                   3492:        $name=~s/\s+$//;
                   3493:        $name=~s/\s+/ /g;
                   3494:     }
                   3495:     return $name;
                   3496: }
                   3497: 
1.295     www      3498: sub getnames {
                   3499:     my ($uname,$udom)=@_;
1.537     albertel 3500:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3501:     if ($udom eq 'public' && $uname eq 'public') {
                   3502: 	return ('lastname' => &mt('Public'));
                   3503:     }
1.295     www      3504:     my $id=$uname.':'.$udom;
                   3505:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3506:     if ($cached) {
                   3507: 	return %{$names};
                   3508:     } else {
                   3509: 	my %loadnames=&Apache::lonnet::get('environment',
                   3510:                     ['firstname','middlename','lastname','generation','nickname'],
                   3511: 					 $udom,$uname);
                   3512: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3513: 	return %loadnames;
                   3514:     }
                   3515: }
1.61      www      3516: 
1.542     raeburn  3517: # -------------------------------------------------------------------- getemails
1.648     raeburn  3518: 
1.542     raeburn  3519: =pod
                   3520: 
1.648     raeburn  3521: =item * &getemails($uname,$udom)
1.542     raeburn  3522: 
                   3523: Gets a user's email information and returns it as a hash with keys:
                   3524: notification, critnotification, permanentemail
                   3525: 
                   3526: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3527: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3528:  
1.648     raeburn  3529: 
1.542     raeburn  3530: =cut
                   3531: 
1.648     raeburn  3532: 
1.466     albertel 3533: sub getemails {
                   3534:     my ($uname,$udom)=@_;
                   3535:     if ($udom eq 'public' && $uname eq 'public') {
                   3536: 	return;
                   3537:     }
1.467     www      3538:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3539:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3540:     my $id=$uname.':'.$udom;
                   3541:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3542:     if ($cached) {
                   3543: 	return %{$names};
                   3544:     } else {
                   3545: 	my %loadnames=&Apache::lonnet::get('environment',
                   3546:                     			   ['notification','critnotification',
                   3547: 					    'permanentemail'],
                   3548: 					   $udom,$uname);
                   3549: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3550: 	return %loadnames;
                   3551:     }
                   3552: }
                   3553: 
1.551     albertel 3554: sub flush_email_cache {
                   3555:     my ($uname,$udom)=@_;
                   3556:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3557:     if (!$uname) { $uname=$env{'user.name'};   }
                   3558:     return if ($udom eq 'public' && $uname eq 'public');
                   3559:     my $id=$uname.':'.$udom;
                   3560:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3561: }
                   3562: 
1.728     raeburn  3563: # -------------------------------------------------------------------- getlangs
                   3564: 
                   3565: =pod
                   3566: 
                   3567: =item * &getlangs($uname,$udom)
                   3568: 
                   3569: Gets a user's language preference and returns it as a hash with key:
                   3570: language.
                   3571: 
                   3572: =cut
                   3573: 
                   3574: 
                   3575: sub getlangs {
                   3576:     my ($uname,$udom) = @_;
                   3577:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3578:     if (!$uname) { $uname=$env{'user.name'};   }
                   3579:     my $id=$uname.':'.$udom;
                   3580:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3581:     if ($cached) {
                   3582:         return %{$langs};
                   3583:     } else {
                   3584:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3585:                                            $udom,$uname);
                   3586:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3587:         return %loadlangs;
                   3588:     }
                   3589: }
                   3590: 
                   3591: sub flush_langs_cache {
                   3592:     my ($uname,$udom)=@_;
                   3593:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3594:     if (!$uname) { $uname=$env{'user.name'};   }
                   3595:     return if ($udom eq 'public' && $uname eq 'public');
                   3596:     my $id=$uname.':'.$udom;
                   3597:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3598: }
                   3599: 
1.61      www      3600: # ------------------------------------------------------------------ Screenname
1.81      albertel 3601: 
                   3602: =pod
                   3603: 
1.648     raeburn  3604: =item * &screenname($uname,$udom)
1.81      albertel 3605: 
                   3606: Gets a users screenname and returns it as a string
                   3607: 
                   3608: =cut
1.61      www      3609: 
                   3610: sub screenname {
                   3611:     my ($uname,$udom)=@_;
1.258     albertel 3612:     if ($uname eq $env{'user.name'} &&
                   3613: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3614:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3615:     return $names{'screenname'};
1.62      www      3616: }
                   3617: 
1.212     albertel 3618: 
1.802     bisitz   3619: # ------------------------------------------------------------- Confirm Wrapper
                   3620: =pod
                   3621: 
1.1075.2.42  raeburn  3622: =item * &confirmwrapper($message)
1.802     bisitz   3623: 
                   3624: Wrap messages about completion of operation in box
                   3625: 
                   3626: =cut
                   3627: 
                   3628: sub confirmwrapper {
                   3629:     my ($message)=@_;
                   3630:     if ($message) {
                   3631:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3632:                .$message."\n"
                   3633:                .'</div>'."\n";
                   3634:     } else {
                   3635:         return $message;
                   3636:     }
                   3637: }
                   3638: 
1.62      www      3639: # ------------------------------------------------------------- Message Wrapper
                   3640: 
                   3641: sub messagewrapper {
1.369     www      3642:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3643:     return 
1.441     albertel 3644:         '<a href="/adm/email?compose=individual&amp;'.
                   3645:         'recname='.$username.'&amp;recdom='.$domain.
                   3646: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3647:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3648: }
1.802     bisitz   3649: 
1.74      www      3650: # --------------------------------------------------------------- Notes Wrapper
                   3651: 
                   3652: sub noteswrapper {
                   3653:     my ($link,$un,$do)=@_;
                   3654:     return 
1.896     amueller 3655: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3656: }
1.802     bisitz   3657: 
1.62      www      3658: # ------------------------------------------------------------- Aboutme Wrapper
                   3659: 
                   3660: sub aboutmewrapper {
1.1070    raeburn  3661:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3662:     if (!defined($username)  && !defined($domain)) {
                   3663:         return;
                   3664:     }
1.1075.2.15  raeburn  3665:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3666: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3667: }
                   3668: 
                   3669: # ------------------------------------------------------------ Syllabus Wrapper
                   3670: 
                   3671: sub syllabuswrapper {
1.707     bisitz   3672:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3673:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3674: }
1.14      harris41 3675: 
1.802     bisitz   3676: # -----------------------------------------------------------------------------
                   3677: 
1.208     matthew  3678: sub track_student_link {
1.887     raeburn  3679:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3680:     my $link ="/adm/trackstudent?";
1.208     matthew  3681:     my $title = 'View recent activity';
                   3682:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3683:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3684:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3685:         $title .= ' of this student';
1.268     albertel 3686:     } 
1.208     matthew  3687:     if (defined($target) && $target !~ /^\s*$/) {
                   3688:         $target = qq{target="$target"};
                   3689:     } else {
                   3690:         $target = '';
                   3691:     }
1.268     albertel 3692:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3693:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3694:     $title = &mt($title);
                   3695:     $linktext = &mt($linktext);
1.448     albertel 3696:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3697: 	&help_open_topic('View_recent_activity');
1.208     matthew  3698: }
                   3699: 
1.781     raeburn  3700: sub slot_reservations_link {
                   3701:     my ($linktext,$sname,$sdom,$target) = @_;
                   3702:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3703:     my $title = 'View slot reservation history';
                   3704:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3705:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3706:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3707:         $title .= ' of this student';
                   3708:     }
                   3709:     if (defined($target) && $target !~ /^\s*$/) {
                   3710:         $target = qq{target="$target"};
                   3711:     } else {
                   3712:         $target = '';
                   3713:     }
                   3714:     $title = &mt($title);
                   3715:     $linktext = &mt($linktext);
                   3716:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3717: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3718: 
                   3719: }
                   3720: 
1.508     www      3721: # ===================================================== Display a student photo
                   3722: 
                   3723: 
1.509     albertel 3724: sub student_image_tag {
1.508     www      3725:     my ($domain,$user)=@_;
                   3726:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3727:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3728: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3729:     } else {
                   3730: 	return '';
                   3731:     }
                   3732: }
                   3733: 
1.112     bowersj2 3734: =pod
                   3735: 
                   3736: =back
                   3737: 
                   3738: =head1 Access .tab File Data
                   3739: 
                   3740: =over 4
                   3741: 
1.648     raeburn  3742: =item * &languageids() 
1.112     bowersj2 3743: 
                   3744: returns list of all language ids
                   3745: 
                   3746: =cut
                   3747: 
1.14      harris41 3748: sub languageids {
1.16      harris41 3749:     return sort(keys(%language));
1.14      harris41 3750: }
                   3751: 
1.112     bowersj2 3752: =pod
                   3753: 
1.648     raeburn  3754: =item * &languagedescription() 
1.112     bowersj2 3755: 
                   3756: returns description of a specified language id
                   3757: 
                   3758: =cut
                   3759: 
1.14      harris41 3760: sub languagedescription {
1.125     www      3761:     my $code=shift;
                   3762:     return  ($supported_language{$code}?'* ':'').
                   3763:             $language{$code}.
1.126     www      3764: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3765: }
                   3766: 
1.1048    foxr     3767: =pod
                   3768: 
                   3769: =item * &plainlanguagedescription
                   3770: 
                   3771: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3772: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3773: 
                   3774: =cut
                   3775: 
1.145     www      3776: sub plainlanguagedescription {
                   3777:     my $code=shift;
                   3778:     return $language{$code};
                   3779: }
                   3780: 
1.1048    foxr     3781: =pod
                   3782: 
                   3783: =item * &supportedlanguagecode
                   3784: 
                   3785: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3786: code.
                   3787: 
                   3788: =cut
                   3789: 
1.145     www      3790: sub supportedlanguagecode {
                   3791:     my $code=shift;
                   3792:     return $supported_language{$code};
1.97      www      3793: }
                   3794: 
1.112     bowersj2 3795: =pod
                   3796: 
1.1048    foxr     3797: =item * &latexlanguage()
                   3798: 
                   3799: Given a language key code returns the correspondnig language to use
                   3800: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3801: is no supported hyphenation for the language code.
                   3802: 
                   3803: =cut
                   3804: 
                   3805: sub latexlanguage {
                   3806:     my $code = shift;
                   3807:     return $latex_language{$code};
                   3808: }
                   3809: 
                   3810: =pod
                   3811: 
                   3812: =item * &latexhyphenation()
                   3813: 
                   3814: Same as above but what's supplied is the language as it might be stored
                   3815: in the metadata.
                   3816: 
                   3817: =cut
                   3818: 
                   3819: sub latexhyphenation {
                   3820:     my $key = shift;
                   3821:     return $latex_language_bykey{$key};
                   3822: }
                   3823: 
                   3824: =pod
                   3825: 
1.648     raeburn  3826: =item * &copyrightids() 
1.112     bowersj2 3827: 
                   3828: returns list of all copyrights
                   3829: 
                   3830: =cut
                   3831: 
                   3832: sub copyrightids {
                   3833:     return sort(keys(%cprtag));
                   3834: }
                   3835: 
                   3836: =pod
                   3837: 
1.648     raeburn  3838: =item * &copyrightdescription() 
1.112     bowersj2 3839: 
                   3840: returns description of a specified copyright id
                   3841: 
                   3842: =cut
                   3843: 
                   3844: sub copyrightdescription {
1.166     www      3845:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3846: }
1.197     matthew  3847: 
                   3848: =pod
                   3849: 
1.648     raeburn  3850: =item * &source_copyrightids() 
1.192     taceyjo1 3851: 
                   3852: returns list of all source copyrights
                   3853: 
                   3854: =cut
                   3855: 
                   3856: sub source_copyrightids {
                   3857:     return sort(keys(%scprtag));
                   3858: }
                   3859: 
                   3860: =pod
                   3861: 
1.648     raeburn  3862: =item * &source_copyrightdescription() 
1.192     taceyjo1 3863: 
                   3864: returns description of a specified source copyright id
                   3865: 
                   3866: =cut
                   3867: 
                   3868: sub source_copyrightdescription {
                   3869:     return &mt($scprtag{shift(@_)});
                   3870: }
1.112     bowersj2 3871: 
                   3872: =pod
                   3873: 
1.648     raeburn  3874: =item * &filecategories() 
1.112     bowersj2 3875: 
                   3876: returns list of all file categories
                   3877: 
                   3878: =cut
                   3879: 
                   3880: sub filecategories {
                   3881:     return sort(keys(%category_extensions));
                   3882: }
                   3883: 
                   3884: =pod
                   3885: 
1.648     raeburn  3886: =item * &filecategorytypes() 
1.112     bowersj2 3887: 
                   3888: returns list of file types belonging to a given file
                   3889: category
                   3890: 
                   3891: =cut
                   3892: 
                   3893: sub filecategorytypes {
1.356     albertel 3894:     my ($cat) = @_;
                   3895:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3896: }
                   3897: 
                   3898: =pod
                   3899: 
1.648     raeburn  3900: =item * &fileembstyle() 
1.112     bowersj2 3901: 
                   3902: returns embedding style for a specified file type
                   3903: 
                   3904: =cut
                   3905: 
                   3906: sub fileembstyle {
                   3907:     return $fe{lc(shift(@_))};
1.169     www      3908: }
                   3909: 
1.351     www      3910: sub filemimetype {
                   3911:     return $fm{lc(shift(@_))};
                   3912: }
                   3913: 
1.169     www      3914: 
                   3915: sub filecategoryselect {
                   3916:     my ($name,$value)=@_;
1.189     matthew  3917:     return &select_form($value,$name,
1.970     raeburn  3918:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3919: }
                   3920: 
                   3921: =pod
                   3922: 
1.648     raeburn  3923: =item * &filedescription() 
1.112     bowersj2 3924: 
                   3925: returns description for a specified file type
                   3926: 
                   3927: =cut
                   3928: 
                   3929: sub filedescription {
1.188     matthew  3930:     my $file_description = $fd{lc(shift())};
                   3931:     $file_description =~ s:([\[\]]):~$1:g;
                   3932:     return &mt($file_description);
1.112     bowersj2 3933: }
                   3934: 
                   3935: =pod
                   3936: 
1.648     raeburn  3937: =item * &filedescriptionex() 
1.112     bowersj2 3938: 
                   3939: returns description for a specified file type with
                   3940: extra formatting
                   3941: 
                   3942: =cut
                   3943: 
                   3944: sub filedescriptionex {
                   3945:     my $ex=shift;
1.188     matthew  3946:     my $file_description = $fd{lc($ex)};
                   3947:     $file_description =~ s:([\[\]]):~$1:g;
                   3948:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3949: }
                   3950: 
                   3951: # End of .tab access
                   3952: =pod
                   3953: 
                   3954: =back
                   3955: 
                   3956: =cut
                   3957: 
                   3958: # ------------------------------------------------------------------ File Types
                   3959: sub fileextensions {
                   3960:     return sort(keys(%fe));
                   3961: }
                   3962: 
1.97      www      3963: # ----------------------------------------------------------- Display Languages
                   3964: # returns a hash with all desired display languages
                   3965: #
                   3966: 
                   3967: sub display_languages {
                   3968:     my %languages=();
1.695     raeburn  3969:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3970: 	$languages{$lang}=1;
1.97      www      3971:     }
                   3972:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3973:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3974: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3975: 	    $languages{$lang}=1;
1.97      www      3976:         }
                   3977:     }
                   3978:     return %languages;
1.14      harris41 3979: }
                   3980: 
1.582     albertel 3981: sub languages {
                   3982:     my ($possible_langs) = @_;
1.695     raeburn  3983:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3984:     if (!ref($possible_langs)) {
                   3985: 	if( wantarray ) {
                   3986: 	    return @preferred_langs;
                   3987: 	} else {
                   3988: 	    return $preferred_langs[0];
                   3989: 	}
                   3990:     }
                   3991:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3992:     my @preferred_possibilities;
                   3993:     foreach my $preferred_lang (@preferred_langs) {
                   3994: 	if (exists($possibilities{$preferred_lang})) {
                   3995: 	    push(@preferred_possibilities, $preferred_lang);
                   3996: 	}
                   3997:     }
                   3998:     if( wantarray ) {
                   3999: 	return @preferred_possibilities;
                   4000:     }
                   4001:     return $preferred_possibilities[0];
                   4002: }
                   4003: 
1.742     raeburn  4004: sub user_lang {
                   4005:     my ($touname,$toudom,$fromcid) = @_;
                   4006:     my @userlangs;
                   4007:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4008:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4009:                     $env{'course.'.$fromcid.'.languages'}));
                   4010:     } else {
                   4011:         my %langhash = &getlangs($touname,$toudom);
                   4012:         if ($langhash{'languages'} ne '') {
                   4013:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4014:         } else {
                   4015:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4016:             if ($domdefs{'lang_def'} ne '') {
                   4017:                 @userlangs = ($domdefs{'lang_def'});
                   4018:             }
                   4019:         }
                   4020:     }
                   4021:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4022:     my $user_lh = Apache::localize->get_handle(@languages);
                   4023:     return $user_lh;
                   4024: }
                   4025: 
                   4026: 
1.112     bowersj2 4027: ###############################################################
                   4028: ##               Student Answer Attempts                     ##
                   4029: ###############################################################
                   4030: 
                   4031: =pod
                   4032: 
                   4033: =head1 Alternate Problem Views
                   4034: 
                   4035: =over 4
                   4036: 
1.648     raeburn  4037: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  4038:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4039: 
                   4040: Return string with previous attempt on problem. Arguments:
                   4041: 
                   4042: =over 4
                   4043: 
                   4044: =item * $symb: Problem, including path
                   4045: 
                   4046: =item * $username: username of the desired student
                   4047: 
                   4048: =item * $domain: domain of the desired student
1.14      harris41 4049: 
1.112     bowersj2 4050: =item * $course: Course ID
1.14      harris41 4051: 
1.112     bowersj2 4052: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4053:     something
1.14      harris41 4054: 
1.112     bowersj2 4055: =item * $regexp: if string matches this regexp, the string will be
                   4056:     sent to $gradesub
1.14      harris41 4057: 
1.112     bowersj2 4058: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4059: 
1.1075.2.86  raeburn  4060: =item * $usec: section of the desired student
                   4061: 
                   4062: =item * $identifier: counter for student (multiple students one problem) or
                   4063:     problem (one student; whole sequence).
                   4064: 
1.112     bowersj2 4065: =back
1.14      harris41 4066: 
1.112     bowersj2 4067: The output string is a table containing all desired attempts, if any.
1.16      harris41 4068: 
1.112     bowersj2 4069: =cut
1.1       albertel 4070: 
                   4071: sub get_previous_attempt {
1.1075.2.86  raeburn  4072:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4073:   my $prevattempts='';
1.43      ng       4074:   no strict 'refs';
1.1       albertel 4075:   if ($symb) {
1.3       albertel 4076:     my (%returnhash)=
                   4077:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4078:     if ($returnhash{'version'}) {
                   4079:       my %lasthash=();
                   4080:       my $version;
                   4081:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  4082:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4083:             if ($key =~ /\.rawrndseed$/) {
                   4084:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4085:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4086:             } else {
                   4087:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4088:             }
1.19      harris41 4089:         }
1.1       albertel 4090:       }
1.596     albertel 4091:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4092:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4093:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4094:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4095:       foreach my $key (sort(keys(%lasthash))) {
                   4096: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4097: 	if ($#parts > 0) {
1.31      albertel 4098: 	  my $data=$parts[-1];
1.989     raeburn  4099:           next if ($data eq 'foilorder');
1.31      albertel 4100: 	  pop(@parts);
1.1010    www      4101:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4102:           if ($data eq 'type') {
                   4103:               unless ($showsurv) {
                   4104:                   my $id = join(',',@parts);
                   4105:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4106:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4107:                       $lasthidden{$ign.'.'.$id} = 1;
                   4108:                   }
1.945     raeburn  4109:               }
1.1075.2.86  raeburn  4110:               if ($identifier ne '') {
                   4111:                   my $id = join(',',@parts);
                   4112:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4113:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4114:                       $hidestatus{$ign.'.'.$id} = 1;
                   4115:                   }
                   4116:               }
                   4117:           } elsif ($data eq 'regrader') {
                   4118:               if (($identifier ne '') && (@parts)) {
                   4119:                   my $id = join(',',@parts);
                   4120:                   $regraded{$ign.'.'.$id} = 1;
                   4121:               }
1.1010    www      4122:           } 
1.31      albertel 4123: 	} else {
1.41      ng       4124: 	  if ($#parts == 0) {
                   4125: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4126: 	  } else {
                   4127: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4128: 	  }
1.31      albertel 4129: 	}
1.16      harris41 4130:       }
1.596     albertel 4131:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4132:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4133:         my (%solved,%resets,%probstatus);
                   4134:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4135:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4136:                 foreach my $id (keys(%regraded)) {
                   4137:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4138:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4139:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4140:                         push(@{$resets{$id}},$version);
                   4141:                     }
                   4142:                 }
                   4143:             }
                   4144:         }
1.40      ng       4145: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4146:             my (@hidden,@unsolved);
1.945     raeburn  4147:             if (%typeparts) {
                   4148:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4149:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4150:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4151:                         push(@hidden,$id);
1.1075.2.86  raeburn  4152:                     } elsif ($identifier ne '') {
                   4153:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4154:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4155:                                 ($hidestatus{$id})) {
                   4156:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4157:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4158:                                 push(@{$solved{$id}},$version);
                   4159:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4160:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4161:                                 my $skip;
                   4162:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4163:                                     foreach my $reset (@{$resets{$id}}) {
                   4164:                                         if ($reset > $solved{$id}[-1]) {
                   4165:                                             $skip=1;
                   4166:                                             last;
                   4167:                                         }
                   4168:                                     }
                   4169:                                 }
                   4170:                                 unless ($skip) {
                   4171:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4172:                                     push(@unsolved,$partslist);
                   4173:                                 }
                   4174:                             }
                   4175:                         }
1.945     raeburn  4176:                     }
                   4177:                 }
                   4178:             }
                   4179:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4180:                            '<td>'.&mt('Transaction [_1]',$version);
                   4181:             if (@unsolved) {
                   4182:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4183:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4184:                                  &mt('Hide').'</label></span>';
                   4185:             }
                   4186:             $prevattempts .= '</td>';
1.945     raeburn  4187:             if (@hidden) {
                   4188:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4189:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4190:                     my $hide;
                   4191:                     foreach my $id (@hidden) {
                   4192:                         if ($key =~ /^\Q$id\E/) {
                   4193:                             $hide = 1;
                   4194:                             last;
                   4195:                         }
                   4196:                     }
                   4197:                     if ($hide) {
                   4198:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4199:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4200:                             my $value = &format_previous_attempt_value($key,
                   4201:                                              $returnhash{$version.':'.$key});
                   4202:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4203:                         } else {
                   4204:                             $prevattempts.='<td>&nbsp;</td>';
                   4205:                         }
                   4206:                     } else {
                   4207:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4208:                             my $value = $returnhash{$version.':'.$key};
                   4209:                             if ($key =~ /\.rndseed$/) {
                   4210:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4211:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4212:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4213:                                 }
                   4214:                             }
                   4215:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4216:                                            '&nbsp;</td>';
1.945     raeburn  4217:                         } else {
                   4218:                             $prevattempts.='<td>&nbsp;</td>';
                   4219:                         }
                   4220:                     }
                   4221:                 }
                   4222:             } else {
                   4223: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4224:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4225:                     my $value = $returnhash{$version.':'.$key};
                   4226:                     if ($key =~ /\.rndseed$/) {
                   4227:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4228:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4229:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4230:                         }
                   4231:                     }
                   4232:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4233:                                    '&nbsp;</td>';
1.945     raeburn  4234: 	        }
                   4235:             }
                   4236: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4237: 	 }
1.1       albertel 4238:       }
1.945     raeburn  4239:       my @currhidden = keys(%lasthidden);
1.596     albertel 4240:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4241:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4242:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4243:           if (%typeparts) {
                   4244:               my $hidden;
                   4245:               foreach my $id (@currhidden) {
                   4246:                   if ($key =~ /^\Q$id\E/) {
                   4247:                       $hidden = 1;
                   4248:                       last;
                   4249:                   }
                   4250:               }
                   4251:               if ($hidden) {
                   4252:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4253:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4254:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4255:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4256:                           $value = &$gradesub($value);
                   4257:                       }
                   4258:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4259:                   } else {
                   4260:                       $prevattempts.='<td>&nbsp;</td>';
                   4261:                   }
                   4262:               } else {
                   4263:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4264:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4265:                       $value = &$gradesub($value);
                   4266:                   }
                   4267:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4268:               }
                   4269:           } else {
                   4270: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4271: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4272:                   $value = &$gradesub($value);
                   4273:               }
                   4274: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4275:           }
1.16      harris41 4276:       }
1.596     albertel 4277:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4278:     } else {
1.596     albertel 4279:       $prevattempts=
                   4280: 	  &start_data_table().&start_data_table_row().
                   4281: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4282: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4283:     }
                   4284:   } else {
1.596     albertel 4285:     $prevattempts=
                   4286: 	  &start_data_table().&start_data_table_row().
                   4287: 	  '<td>'.&mt('No data.').'</td>'.
                   4288: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4289:   }
1.10      albertel 4290: }
                   4291: 
1.581     albertel 4292: sub format_previous_attempt_value {
                   4293:     my ($key,$value) = @_;
1.1011    www      4294:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4295: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4296:     } elsif (ref($value) eq 'ARRAY') {
                   4297: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4298:     } elsif ($key =~ /answerstring$/) {
                   4299:         my %answers = &Apache::lonnet::str2hash($value);
                   4300:         my @anskeys = sort(keys(%answers));
                   4301:         if (@anskeys == 1) {
                   4302:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4303:             if ($answer =~ m{\0}) {
                   4304:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4305:             }
                   4306:             my $tag_internal_answer_name = 'INTERNAL';
                   4307:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4308:                 $value = $answer; 
                   4309:             } else {
                   4310:                 $value = $anskeys[0].'='.$answer;
                   4311:             }
                   4312:         } else {
                   4313:             foreach my $ans (@anskeys) {
                   4314:                 my $answer = $answers{$ans};
1.1001    raeburn  4315:                 if ($answer =~ m{\0}) {
                   4316:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4317:                 }
                   4318:                 $value .=  $ans.'='.$answer.'<br />';;
                   4319:             } 
                   4320:         }
1.581     albertel 4321:     } else {
                   4322: 	$value = &unescape($value);
                   4323:     }
                   4324:     return $value;
                   4325: }
                   4326: 
                   4327: 
1.107     albertel 4328: sub relative_to_absolute {
                   4329:     my ($url,$output)=@_;
                   4330:     my $parser=HTML::TokeParser->new(\$output);
                   4331:     my $token;
                   4332:     my $thisdir=$url;
                   4333:     my @rlinks=();
                   4334:     while ($token=$parser->get_token) {
                   4335: 	if ($token->[0] eq 'S') {
                   4336: 	    if ($token->[1] eq 'a') {
                   4337: 		if ($token->[2]->{'href'}) {
                   4338: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4339: 		}
                   4340: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4341: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4342: 	    } elsif ($token->[1] eq 'base') {
                   4343: 		$thisdir=$token->[2]->{'href'};
                   4344: 	    }
                   4345: 	}
                   4346:     }
                   4347:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4348:     foreach my $link (@rlinks) {
1.726     raeburn  4349: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4350: 		($link=~/^\//) ||
                   4351: 		($link=~/^javascript:/i) ||
                   4352: 		($link=~/^mailto:/i) ||
                   4353: 		($link=~/^\#/)) {
                   4354: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4355: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4356: 	}
                   4357:     }
                   4358: # -------------------------------------------------- Deal with Applet codebases
                   4359:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4360:     return $output;
                   4361: }
                   4362: 
1.112     bowersj2 4363: =pod
                   4364: 
1.648     raeburn  4365: =item * &get_student_view()
1.112     bowersj2 4366: 
                   4367: show a snapshot of what student was looking at
                   4368: 
                   4369: =cut
                   4370: 
1.10      albertel 4371: sub get_student_view {
1.186     albertel 4372:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4373:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4374:   my (%form);
1.10      albertel 4375:   my @elements=('symb','courseid','domain','username');
                   4376:   foreach my $element (@elements) {
1.186     albertel 4377:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4378:   }
1.186     albertel 4379:   if (defined($moreenv)) {
                   4380:       %form=(%form,%{$moreenv});
                   4381:   }
1.236     albertel 4382:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4383:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4384:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4385:   $userview=~s/\<body[^\>]*\>//gi;
                   4386:   $userview=~s/\<\/body\>//gi;
                   4387:   $userview=~s/\<html\>//gi;
                   4388:   $userview=~s/\<\/html\>//gi;
                   4389:   $userview=~s/\<head\>//gi;
                   4390:   $userview=~s/\<\/head\>//gi;
                   4391:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4392:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4393:   if (wantarray) {
                   4394:      return ($userview,$response);
                   4395:   } else {
                   4396:      return $userview;
                   4397:   }
                   4398: }
                   4399: 
                   4400: sub get_student_view_with_retries {
                   4401:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4402: 
                   4403:     my $ok = 0;                 # True if we got a good response.
                   4404:     my $content;
                   4405:     my $response;
                   4406: 
                   4407:     # Try to get the student_view done. within the retries count:
                   4408:     
                   4409:     do {
                   4410:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4411:          $ok      = $response->is_success;
                   4412:          if (!$ok) {
                   4413:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4414:          }
                   4415:          $retries--;
                   4416:     } while (!$ok && ($retries > 0));
                   4417:     
                   4418:     if (!$ok) {
                   4419:        $content = '';          # On error return an empty content.
                   4420:     }
1.651     www      4421:     if (wantarray) {
                   4422:        return ($content, $response);
                   4423:     } else {
                   4424:        return $content;
                   4425:     }
1.11      albertel 4426: }
                   4427: 
1.112     bowersj2 4428: =pod
                   4429: 
1.648     raeburn  4430: =item * &get_student_answers() 
1.112     bowersj2 4431: 
                   4432: show a snapshot of how student was answering problem
                   4433: 
                   4434: =cut
                   4435: 
1.11      albertel 4436: sub get_student_answers {
1.100     sakharuk 4437:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4438:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4439:   my (%moreenv);
1.11      albertel 4440:   my @elements=('symb','courseid','domain','username');
                   4441:   foreach my $element (@elements) {
1.186     albertel 4442:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4443:   }
1.186     albertel 4444:   $moreenv{'grade_target'}='answer';
                   4445:   %moreenv=(%form,%moreenv);
1.497     raeburn  4446:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4447:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4448:   return $userview;
1.1       albertel 4449: }
1.116     albertel 4450: 
                   4451: =pod
                   4452: 
                   4453: =item * &submlink()
                   4454: 
1.242     albertel 4455: Inputs: $text $uname $udom $symb $target
1.116     albertel 4456: 
                   4457: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4458: 
                   4459: =cut
                   4460: 
                   4461: ###############################################
                   4462: sub submlink {
1.242     albertel 4463:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4464:     if (!($uname && $udom)) {
                   4465: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4466: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4467: 	if (!$symb) { $symb=$cursymb; }
                   4468:     }
1.254     matthew  4469:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4470:     $symb=&escape($symb);
1.960     bisitz   4471:     if ($target) { $target=" target=\"$target\""; }
                   4472:     return
                   4473:         '<a href="/adm/grades?command=submission'.
                   4474:         '&amp;symb='.$symb.
                   4475:         '&amp;student='.$uname.
                   4476:         '&amp;userdom='.$udom.'"'.
                   4477:         $target.'>'.$text.'</a>';
1.242     albertel 4478: }
                   4479: ##############################################
                   4480: 
                   4481: =pod
                   4482: 
                   4483: =item * &pgrdlink()
                   4484: 
                   4485: Inputs: $text $uname $udom $symb $target
                   4486: 
                   4487: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4488: 
                   4489: =cut
                   4490: 
                   4491: ###############################################
                   4492: sub pgrdlink {
                   4493:     my $link=&submlink(@_);
                   4494:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4495:     return $link;
                   4496: }
                   4497: ##############################################
                   4498: 
                   4499: =pod
                   4500: 
                   4501: =item * &pprmlink()
                   4502: 
                   4503: Inputs: $text $uname $udom $symb $target
                   4504: 
                   4505: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4506: student and a specific resource
1.242     albertel 4507: 
                   4508: =cut
                   4509: 
                   4510: ###############################################
                   4511: sub pprmlink {
                   4512:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4513:     if (!($uname && $udom)) {
                   4514: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4515: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4516: 	if (!$symb) { $symb=$cursymb; }
                   4517:     }
1.254     matthew  4518:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4519:     $symb=&escape($symb);
1.242     albertel 4520:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4521:     return '<a href="/adm/parmset?command=set&amp;'.
                   4522: 	'symb='.$symb.'&amp;uname='.$uname.
                   4523: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4524: }
                   4525: ##############################################
1.37      matthew  4526: 
1.112     bowersj2 4527: =pod
                   4528: 
                   4529: =back
                   4530: 
                   4531: =cut
                   4532: 
1.37      matthew  4533: ###############################################
1.51      www      4534: 
                   4535: 
                   4536: sub timehash {
1.687     raeburn  4537:     my ($thistime) = @_;
                   4538:     my $timezone = &Apache::lonlocal::gettimezone();
                   4539:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4540:                      ->set_time_zone($timezone);
                   4541:     my $wday = $dt->day_of_week();
                   4542:     if ($wday == 7) { $wday = 0; }
                   4543:     return ( 'second' => $dt->second(),
                   4544:              'minute' => $dt->minute(),
                   4545:              'hour'   => $dt->hour(),
                   4546:              'day'     => $dt->day_of_month(),
                   4547:              'month'   => $dt->month(),
                   4548:              'year'    => $dt->year(),
                   4549:              'weekday' => $wday,
                   4550:              'dayyear' => $dt->day_of_year(),
                   4551:              'dlsav'   => $dt->is_dst() );
1.51      www      4552: }
                   4553: 
1.370     www      4554: sub utc_string {
                   4555:     my ($date)=@_;
1.371     www      4556:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4557: }
                   4558: 
1.51      www      4559: sub maketime {
                   4560:     my %th=@_;
1.687     raeburn  4561:     my ($epoch_time,$timezone,$dt);
                   4562:     $timezone = &Apache::lonlocal::gettimezone();
                   4563:     eval {
                   4564:         $dt = DateTime->new( year   => $th{'year'},
                   4565:                              month  => $th{'month'},
                   4566:                              day    => $th{'day'},
                   4567:                              hour   => $th{'hour'},
                   4568:                              minute => $th{'minute'},
                   4569:                              second => $th{'second'},
                   4570:                              time_zone => $timezone,
                   4571:                          );
                   4572:     };
                   4573:     if (!$@) {
                   4574:         $epoch_time = $dt->epoch;
                   4575:         if ($epoch_time) {
                   4576:             return $epoch_time;
                   4577:         }
                   4578:     }
1.51      www      4579:     return POSIX::mktime(
                   4580:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4581:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4582: }
                   4583: 
                   4584: #########################################
1.51      www      4585: 
                   4586: sub findallcourses {
1.482     raeburn  4587:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4588:     my %roles;
                   4589:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4590:     my %courses;
1.51      www      4591:     my $now=time;
1.482     raeburn  4592:     if (!defined($uname)) {
                   4593:         $uname = $env{'user.name'};
                   4594:     }
                   4595:     if (!defined($udom)) {
                   4596:         $udom = $env{'user.domain'};
                   4597:     }
                   4598:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4599:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4600:         if (!%roles) {
                   4601:             %roles = (
                   4602:                        cc => 1,
1.907     raeburn  4603:                        co => 1,
1.482     raeburn  4604:                        in => 1,
                   4605:                        ep => 1,
                   4606:                        ta => 1,
                   4607:                        cr => 1,
                   4608:                        st => 1,
                   4609:              );
                   4610:         }
                   4611:         foreach my $entry (keys(%roleshash)) {
                   4612:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4613:             if ($trole =~ /^cr/) { 
                   4614:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4615:             } else {
                   4616:                 next if (!exists($roles{$trole}));
                   4617:             }
                   4618:             if ($tend) {
                   4619:                 next if ($tend < $now);
                   4620:             }
                   4621:             if ($tstart) {
                   4622:                 next if ($tstart > $now);
                   4623:             }
1.1058    raeburn  4624:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4625:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4626:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4627:             if ($secpart eq '') {
                   4628:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4629:                 $sec = 'none';
1.1058    raeburn  4630:                 $value .= $cnum.'/';
1.482     raeburn  4631:             } else {
                   4632:                 $cnum = $cnumpart;
                   4633:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4634:                 $value .= $cnum.'/'.$sec;
                   4635:             }
                   4636:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4637:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4638:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4639:                 }
                   4640:             } else {
                   4641:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4642:             }
1.482     raeburn  4643:         }
                   4644:     } else {
                   4645:         foreach my $key (keys(%env)) {
1.483     albertel 4646: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4647:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4648: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4649: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4650: 	        next if (%roles && !exists($roles{$role}));
                   4651: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4652:                 my $active=1;
                   4653:                 if ($starttime) {
                   4654: 		    if ($now<$starttime) { $active=0; }
                   4655:                 }
                   4656:                 if ($endtime) {
                   4657:                     if ($now>$endtime) { $active=0; }
                   4658:                 }
                   4659:                 if ($active) {
1.1058    raeburn  4660:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4661:                     if ($sec eq '') {
                   4662:                         $sec = 'none';
1.1058    raeburn  4663:                     } else {
                   4664:                         $value .= $sec;
                   4665:                     }
                   4666:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4667:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4668:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4669:                         }
                   4670:                     } else {
                   4671:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4672:                     }
1.474     raeburn  4673:                 }
                   4674:             }
1.51      www      4675:         }
                   4676:     }
1.474     raeburn  4677:     return %courses;
1.51      www      4678: }
1.37      matthew  4679: 
1.54      www      4680: ###############################################
1.474     raeburn  4681: 
                   4682: sub blockcheck {
1.1075.2.73  raeburn  4683:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4684: 
1.1075.2.73  raeburn  4685:     if (defined($udom) && defined($uname)) {
                   4686:         # If uname and udom are for a course, check for blocks in the course.
                   4687:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4688:             my ($startblock,$endblock,$triggerblock) =
                   4689:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4690:             return ($startblock,$endblock,$triggerblock);
                   4691:         }
                   4692:     } else {
1.490     raeburn  4693:         $udom = $env{'user.domain'};
                   4694:         $uname = $env{'user.name'};
                   4695:     }
                   4696: 
1.502     raeburn  4697:     my $startblock = 0;
                   4698:     my $endblock = 0;
1.1062    raeburn  4699:     my $triggerblock = '';
1.482     raeburn  4700:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4701: 
1.490     raeburn  4702:     # If uname is for a user, and activity is course-specific, i.e.,
                   4703:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4704: 
1.490     raeburn  4705:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.73  raeburn  4706:          $activity eq 'groups' || $activity eq 'printout') &&
                   4707:         ($env{'request.course.id'})) {
1.490     raeburn  4708:         foreach my $key (keys(%live_courses)) {
                   4709:             if ($key ne $env{'request.course.id'}) {
                   4710:                 delete($live_courses{$key});
                   4711:             }
                   4712:         }
                   4713:     }
                   4714: 
                   4715:     my $otheruser = 0;
                   4716:     my %own_courses;
                   4717:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4718:         # Resource belongs to user other than current user.
                   4719:         $otheruser = 1;
                   4720:         # Gather courses for current user
                   4721:         %own_courses = 
                   4722:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4723:     }
                   4724: 
                   4725:     # Gather active course roles - course coordinator, instructor, 
                   4726:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4727: 
                   4728:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4729:         my ($cdom,$cnum);
                   4730:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4731:             $cdom = $env{'course.'.$course.'.domain'};
                   4732:             $cnum = $env{'course.'.$course.'.num'};
                   4733:         } else {
1.490     raeburn  4734:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4735:         }
                   4736:         my $no_ownblock = 0;
                   4737:         my $no_userblock = 0;
1.533     raeburn  4738:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4739:             # Check if current user has 'evb' priv for this
                   4740:             if (defined($own_courses{$course})) {
                   4741:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4742:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4743:                     if ($sec ne 'none') {
                   4744:                         $checkrole .= '/'.$sec;
                   4745:                     }
                   4746:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4747:                         $no_ownblock = 1;
                   4748:                         last;
                   4749:                     }
                   4750:                 }
                   4751:             }
                   4752:             # if they have 'evb' priv and are currently not playing student
                   4753:             next if (($no_ownblock) &&
                   4754:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4755:         }
1.474     raeburn  4756:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4757:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4758:             if ($sec ne 'none') {
1.482     raeburn  4759:                 $checkrole .= '/'.$sec;
1.474     raeburn  4760:             }
1.490     raeburn  4761:             if ($otheruser) {
                   4762:                 # Resource belongs to user other than current user.
                   4763:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4764:                 my (%allroles,%userroles);
                   4765:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4766:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4767:                         my ($trole,$tdom,$tnum,$tsec);
                   4768:                         if ($entry =~ /^cr/) {
                   4769:                             ($trole,$tdom,$tnum,$tsec) = 
                   4770:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4771:                         } else {
                   4772:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4773:                         }
                   4774:                         my ($spec,$area,$trest);
                   4775:                         $area = '/'.$tdom.'/'.$tnum;
                   4776:                         $trest = $tnum;
                   4777:                         if ($tsec ne '') {
                   4778:                             $area .= '/'.$tsec;
                   4779:                             $trest .= '/'.$tsec;
                   4780:                         }
                   4781:                         $spec = $trole.'.'.$area;
                   4782:                         if ($trole =~ /^cr/) {
                   4783:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4784:                                                               $tdom,$spec,$trest,$area);
                   4785:                         } else {
                   4786:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4787:                                                                 $tdom,$spec,$trest,$area);
                   4788:                         }
                   4789:                     }
1.1075.2.124  raeburn  4790:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  4791:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4792:                         if ($1) {
                   4793:                             $no_userblock = 1;
                   4794:                             last;
                   4795:                         }
1.486     raeburn  4796:                     }
                   4797:                 }
1.490     raeburn  4798:             } else {
                   4799:                 # Resource belongs to current user
                   4800:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4801:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4802:                     $no_ownblock = 1;
                   4803:                     last;
                   4804:                 }
1.474     raeburn  4805:             }
                   4806:         }
                   4807:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4808:         next if (($no_ownblock) &&
1.491     albertel 4809:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4810:         next if ($no_userblock);
1.474     raeburn  4811: 
1.1075.2.128  raeburn  4812:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  4813:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4814:         
1.1062    raeburn  4815:         my ($start,$end,$trigger) = 
                   4816:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4817:         if (($start != 0) && 
                   4818:             (($startblock == 0) || ($startblock > $start))) {
                   4819:             $startblock = $start;
1.1062    raeburn  4820:             if ($trigger ne '') {
                   4821:                 $triggerblock = $trigger;
                   4822:             }
1.502     raeburn  4823:         }
                   4824:         if (($end != 0)  &&
                   4825:             (($endblock == 0) || ($endblock < $end))) {
                   4826:             $endblock = $end;
1.1062    raeburn  4827:             if ($trigger ne '') {
                   4828:                 $triggerblock = $trigger;
                   4829:             }
1.502     raeburn  4830:         }
1.490     raeburn  4831:     }
1.1062    raeburn  4832:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4833: }
                   4834: 
                   4835: sub get_blocks {
1.1062    raeburn  4836:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4837:     my $startblock = 0;
                   4838:     my $endblock = 0;
1.1062    raeburn  4839:     my $triggerblock = '';
1.490     raeburn  4840:     my $course = $cdom.'_'.$cnum;
                   4841:     $setters->{$course} = {};
                   4842:     $setters->{$course}{'staff'} = [];
                   4843:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4844:     $setters->{$course}{'triggers'} = [];
                   4845:     my (@blockers,%triggered);
                   4846:     my $now = time;
                   4847:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4848:     if ($activity eq 'docs') {
                   4849:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4850:         foreach my $block (@blockers) {
                   4851:             if ($block =~ /^firstaccess____(.+)$/) {
                   4852:                 my $item = $1;
                   4853:                 my $type = 'map';
                   4854:                 my $timersymb = $item;
                   4855:                 if ($item eq 'course') {
                   4856:                     $type = 'course';
                   4857:                 } elsif ($item =~ /___\d+___/) {
                   4858:                     $type = 'resource';
                   4859:                 } else {
                   4860:                     $timersymb = &Apache::lonnet::symbread($item);
                   4861:                 }
                   4862:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4863:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4864:                 $triggered{$block} = {
                   4865:                                        start => $start,
                   4866:                                        end   => $end,
                   4867:                                        type  => $type,
                   4868:                                      };
                   4869:             }
                   4870:         }
                   4871:     } else {
                   4872:         foreach my $block (keys(%commblocks)) {
                   4873:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4874:                 my ($start,$end) = ($1,$2);
                   4875:                 if ($start <= time && $end >= time) {
                   4876:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4877:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4878:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4879:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4880:                                     push(@blockers,$block);
                   4881:                                 }
                   4882:                             }
                   4883:                         }
                   4884:                     }
                   4885:                 }
                   4886:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4887:                 my $item = $1;
                   4888:                 my $timersymb = $item; 
                   4889:                 my $type = 'map';
                   4890:                 if ($item eq 'course') {
                   4891:                     $type = 'course';
                   4892:                 } elsif ($item =~ /___\d+___/) {
                   4893:                     $type = 'resource';
                   4894:                 } else {
                   4895:                     $timersymb = &Apache::lonnet::symbread($item);
                   4896:                 }
                   4897:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4898:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4899:                 if ($start && $end) {
                   4900:                     if (($start <= time) && ($end >= time)) {
                   4901:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4902:                             push(@blockers,$block);
                   4903:                             $triggered{$block} = {
                   4904:                                                    start => $start,
                   4905:                                                    end   => $end,
                   4906:                                                    type  => $type,
                   4907:                                                  };
                   4908:                         }
                   4909:                     }
1.490     raeburn  4910:                 }
1.1062    raeburn  4911:             }
                   4912:         }
                   4913:     }
                   4914:     foreach my $blocker (@blockers) {
                   4915:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4916:             &parse_block_record($commblocks{$blocker});
                   4917:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4918:         my ($start,$end,$triggertype);
                   4919:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4920:             ($start,$end) = ($1,$2);
                   4921:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4922:             $start = $triggered{$blocker}{'start'};
                   4923:             $end = $triggered{$blocker}{'end'};
                   4924:             $triggertype = $triggered{$blocker}{'type'};
                   4925:         }
                   4926:         if ($start) {
                   4927:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4928:             if ($triggertype) {
                   4929:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4930:             } else {
                   4931:                 push(@{$$setters{$course}{'triggers'}},0);
                   4932:             }
                   4933:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4934:                 $startblock = $start;
                   4935:                 if ($triggertype) {
                   4936:                     $triggerblock = $blocker;
1.474     raeburn  4937:                 }
                   4938:             }
1.1062    raeburn  4939:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4940:                $endblock = $end;
                   4941:                if ($triggertype) {
                   4942:                    $triggerblock = $blocker;
                   4943:                }
                   4944:             }
1.474     raeburn  4945:         }
                   4946:     }
1.1062    raeburn  4947:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4948: }
                   4949: 
                   4950: sub parse_block_record {
                   4951:     my ($record) = @_;
                   4952:     my ($setuname,$setudom,$title,$blocks);
                   4953:     if (ref($record) eq 'HASH') {
                   4954:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4955:         $title = &unescape($record->{'event'});
                   4956:         $blocks = $record->{'blocks'};
                   4957:     } else {
                   4958:         my @data = split(/:/,$record,3);
                   4959:         if (scalar(@data) eq 2) {
                   4960:             $title = $data[1];
                   4961:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4962:         } else {
                   4963:             ($setuname,$setudom,$title) = @data;
                   4964:         }
                   4965:         $blocks = { 'com' => 'on' };
                   4966:     }
                   4967:     return ($setuname,$setudom,$title,$blocks);
                   4968: }
                   4969: 
1.854     kalberla 4970: sub blocking_status {
1.1075.2.73  raeburn  4971:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  4972:     my %setters;
1.890     droeschl 4973: 
1.1061    raeburn  4974: # check for active blocking
1.1062    raeburn  4975:     my ($startblock,$endblock,$triggerblock) = 
1.1075.2.73  raeburn  4976:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  4977:     my $blocked = 0;
                   4978:     if ($startblock && $endblock) {
                   4979:         $blocked = 1;
                   4980:     }
1.890     droeschl 4981: 
1.1061    raeburn  4982: # caller just wants to know whether a block is active
                   4983:     if (!wantarray) { return $blocked; }
                   4984: 
                   4985: # build a link to a popup window containing the details
                   4986:     my $querystring  = "?activity=$activity";
                   4987: # $uname and $udom decide whose portfolio the user is trying to look at
1.1075.2.97  raeburn  4988:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   4989:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   4990:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  4991:     } elsif ($activity eq 'docs') {
                   4992:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4993:     }
1.1061    raeburn  4994: 
                   4995:     my $output .= <<'END_MYBLOCK';
                   4996: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4997:     var options = "width=" + w + ",height=" + h + ",";
                   4998:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4999:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5000:     var newWin = window.open(url, wdwName, options);
                   5001:     newWin.focus();
                   5002: }
1.890     droeschl 5003: END_MYBLOCK
1.854     kalberla 5004: 
1.1061    raeburn  5005:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5006:   
1.1061    raeburn  5007:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5008:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  5009:     my $class = 'LC_comblock';
1.1062    raeburn  5010:     if ($activity eq 'docs') {
                   5011:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  5012:         $class = '';
1.1063    raeburn  5013:     } elsif ($activity eq 'printout') {
                   5014:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  5015:     } elsif ($activity eq 'passwd') {
                   5016:         $text = &mt('Password Changing Blocked');
1.1062    raeburn  5017:     }
1.1061    raeburn  5018:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  5019: <div class='$class'>
1.869     kalberla 5020:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5021:   title='$text'>
                   5022:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5023:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5024:   title='$text'>$text</a>
1.867     kalberla 5025: </div>
                   5026: 
                   5027: END_BLOCK
1.474     raeburn  5028: 
1.1061    raeburn  5029:     return ($blocked, $output);
1.854     kalberla 5030: }
1.490     raeburn  5031: 
1.60      matthew  5032: ###############################################
                   5033: 
1.682     raeburn  5034: sub check_ip_acc {
1.1075.2.105  raeburn  5035:     my ($acc,$clientip)=@_;
1.682     raeburn  5036:     &Apache::lonxml::debug("acc is $acc");
                   5037:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5038:         return 1;
                   5039:     }
1.1075.2.141.  .1(raebu 5040:20):     my $allowed;
1.1075.2.111  raeburn  5041:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
1.682     raeburn  5042: 
                   5043:     my $name;
1.1075.2.141.  .1(raebu 5044:20):     my %access = (
                   5045:20):                      allowfrom => 1,
                   5046:20):                      denyfrom  => 0,
                   5047:20):                  );
                   5048:20):     my @allows;
                   5049:20):     my @denies;
                   5050:20):     foreach my $item (split(',',$acc)) {
                   5051:20):         $item =~ s/^\s*//;
                   5052:20):         $item =~ s/\s*$//;
                   5053:20):         if ($item =~ /^\!(.+)$/) {
                   5054:20):             push(@denies,$1);
                   5055:20):         } else {
                   5056:20):             push(@allows,$item);
                   5057:20):         }
                   5058:20):     }
                   5059:20):     my $numdenies = scalar(@denies);
                   5060:20):     my $numallows = scalar(@allows);
                   5061:20):     my $count = 0;
                   5062:20):     foreach my $pattern (@denies,@allows) {
                   5063:20):         $count ++;
                   5064:20):         my $acctype = 'allowfrom';
                   5065:20):         if ($count <= $numdenies) {
                   5066:20):             $acctype = 'denyfrom';
                   5067:20):         }
1.682     raeburn  5068:         if ($pattern =~ /\*$/) {
                   5069:             #35.8.*
                   5070:             $pattern=~s/\*//;
1.1075.2.141.  .1(raebu 5071:20):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5072:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5073:             #35.8.3.[34-56]
                   5074:             my $low=$2;
                   5075:             my $high=$3;
                   5076:             $pattern=$1;
                   5077:             if ($ip =~ /^\Q$pattern\E/) {
                   5078:                 my $last=(split(/\./,$ip))[3];
1.1075.2.141.  .1(raebu 5079:20):                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5080:             }
                   5081:         } elsif ($pattern =~ /^\*/) {
                   5082:             #*.msu.edu
                   5083:             $pattern=~s/\*//;
                   5084:             if (!defined($name)) {
                   5085:                 use Socket;
                   5086:                 my $netaddr=inet_aton($ip);
                   5087:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5088:             }
1.1075.2.141.  .1(raebu 5089:20):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5090:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5091:             #127.0.0.1
1.1075.2.141.  .1(raebu 5092:20):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5093:         } else {
                   5094:             #some.name.com
                   5095:             if (!defined($name)) {
                   5096:                 use Socket;
                   5097:                 my $netaddr=inet_aton($ip);
                   5098:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5099:             }
1.1075.2.141.  .1(raebu 5100:20):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5101:20):         }
                   5102:20):         if ($allowed =~ /^(0|1)$/) { last; }
                   5103:20):     }
                   5104:20):     if ($allowed eq '') {
                   5105:20):         if ($numdenies && !$numallows) {
                   5106:20):             $allowed = 1;
                   5107:20):         } else {
                   5108:20):             $allowed = 0;
1.682     raeburn  5109:         }
                   5110:     }
                   5111:     return $allowed;
                   5112: }
                   5113: 
                   5114: ###############################################
                   5115: 
1.60      matthew  5116: =pod
                   5117: 
1.112     bowersj2 5118: =head1 Domain Template Functions
                   5119: 
                   5120: =over 4
                   5121: 
                   5122: =item * &determinedomain()
1.60      matthew  5123: 
                   5124: Inputs: $domain (usually will be undef)
                   5125: 
1.63      www      5126: Returns: Determines which domain should be used for designs
1.60      matthew  5127: 
                   5128: =cut
1.54      www      5129: 
1.60      matthew  5130: ###############################################
1.63      www      5131: sub determinedomain {
                   5132:     my $domain=shift;
1.531     albertel 5133:     if (! $domain) {
1.60      matthew  5134:         # Determine domain if we have not been given one
1.893     raeburn  5135:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5136:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5137:         if ($env{'request.role.domain'}) { 
                   5138:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5139:         }
                   5140:     }
1.63      www      5141:     return $domain;
                   5142: }
                   5143: ###############################################
1.517     raeburn  5144: 
1.518     albertel 5145: sub devalidate_domconfig_cache {
                   5146:     my ($udom)=@_;
                   5147:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5148: }
                   5149: 
                   5150: # ---------------------- Get domain configuration for a domain
                   5151: sub get_domainconf {
                   5152:     my ($udom) = @_;
                   5153:     my $cachetime=1800;
                   5154:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5155:     if (defined($cached)) { return %{$result}; }
                   5156: 
                   5157:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5158: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5159:     my (%designhash,%legacy);
1.518     albertel 5160:     if (keys(%domconfig) > 0) {
                   5161:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5162:             if (keys(%{$domconfig{'login'}})) {
                   5163:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5164:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5165:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5166:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5167:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5168:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5169:                                         if ($key eq 'loginvia') {
                   5170:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5171:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5172:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5173:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5174:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5175:                                                 } else {
                   5176:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5177:                                                 }
1.948     raeburn  5178:                                             }
1.1075.2.87  raeburn  5179:                                         } elsif ($key eq 'headtag') {
                   5180:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5181:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5182:                                             }
1.946     raeburn  5183:                                         }
1.1075.2.87  raeburn  5184:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5185:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5186:                                         }
1.946     raeburn  5187:                                     }
                   5188:                                 }
                   5189:                             }
                   5190:                         } else {
                   5191:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5192:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5193:                                     $domconfig{'login'}{$key}{$img};
                   5194:                             }
1.699     raeburn  5195:                         }
                   5196:                     } else {
                   5197:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5198:                     }
1.632     raeburn  5199:                 }
                   5200:             } else {
                   5201:                 $legacy{'login'} = 1;
1.518     albertel 5202:             }
1.632     raeburn  5203:         } else {
                   5204:             $legacy{'login'} = 1;
1.518     albertel 5205:         }
                   5206:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5207:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5208:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5209:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5210:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5211:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5212:                         }
1.518     albertel 5213:                     }
                   5214:                 }
1.632     raeburn  5215:             } else {
                   5216:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5217:             }
1.632     raeburn  5218:         } else {
                   5219:             $legacy{'rolecolors'} = 1;
1.518     albertel 5220:         }
1.948     raeburn  5221:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5222:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5223:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5224:             }
                   5225:         }
1.632     raeburn  5226:         if (keys(%legacy) > 0) {
                   5227:             my %legacyhash = &get_legacy_domconf($udom);
                   5228:             foreach my $item (keys(%legacyhash)) {
                   5229:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5230:                     if ($legacy{'login'}) { 
                   5231:                         $designhash{$item} = $legacyhash{$item};
                   5232:                     }
                   5233:                 } else {
                   5234:                     if ($legacy{'rolecolors'}) {
                   5235:                         $designhash{$item} = $legacyhash{$item};
                   5236:                     }
1.518     albertel 5237:                 }
                   5238:             }
                   5239:         }
1.632     raeburn  5240:     } else {
                   5241:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5242:     }
                   5243:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5244: 				  $cachetime);
                   5245:     return %designhash;
                   5246: }
                   5247: 
1.632     raeburn  5248: sub get_legacy_domconf {
                   5249:     my ($udom) = @_;
                   5250:     my %legacyhash;
                   5251:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5252:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5253:     if (-e $designfile) {
1.1075.2.128  raeburn  5254:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5255:             while (my $line = <$fh>) {
                   5256:                 next if ($line =~ /^\#/);
                   5257:                 chomp($line);
                   5258:                 my ($key,$val)=(split(/\=/,$line));
                   5259:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5260:             }
                   5261:             close($fh);
                   5262:         }
                   5263:     }
1.1026    raeburn  5264:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5265:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5266:     }
                   5267:     return %legacyhash;
                   5268: }
                   5269: 
1.63      www      5270: =pod
                   5271: 
1.112     bowersj2 5272: =item * &domainlogo()
1.63      www      5273: 
                   5274: Inputs: $domain (usually will be undef)
                   5275: 
                   5276: Returns: A link to a domain logo, if the domain logo exists.
                   5277: If the domain logo does not exist, a description of the domain.
                   5278: 
                   5279: =cut
1.112     bowersj2 5280: 
1.63      www      5281: ###############################################
                   5282: sub domainlogo {
1.517     raeburn  5283:     my $domain = &determinedomain(shift);
1.518     albertel 5284:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5285:     # See if there is a logo
                   5286:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5287:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5288:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5289: 	    if ($imgsrc =~ m{^/res/}) {
                   5290: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5291: 		&Apache::lonnet::repcopy($local_name);
                   5292: 	    }
                   5293: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5294:         } 
                   5295:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5296:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5297:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5298:     } else {
1.60      matthew  5299:         return '';
1.59      www      5300:     }
                   5301: }
1.63      www      5302: ##############################################
                   5303: 
                   5304: =pod
                   5305: 
1.112     bowersj2 5306: =item * &designparm()
1.63      www      5307: 
                   5308: Inputs: $which parameter; $domain (usually will be undef)
                   5309: 
                   5310: Returns: value of designparamter $which
                   5311: 
                   5312: =cut
1.112     bowersj2 5313: 
1.397     albertel 5314: 
1.400     albertel 5315: ##############################################
1.397     albertel 5316: sub designparm {
                   5317:     my ($which,$domain)=@_;
                   5318:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5319:         return $env{'environment.color.'.$which};
1.96      www      5320:     }
1.63      www      5321:     $domain=&determinedomain($domain);
1.1016    raeburn  5322:     my %domdesign;
                   5323:     unless ($domain eq 'public') {
                   5324:         %domdesign = &get_domainconf($domain);
                   5325:     }
1.520     raeburn  5326:     my $output;
1.517     raeburn  5327:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5328:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5329:     } else {
1.520     raeburn  5330:         $output = $defaultdesign{$which};
                   5331:     }
                   5332:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5333:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5334:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5335:             if ($output =~ m{^/res/}) {
                   5336:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5337:                 &Apache::lonnet::repcopy($local_name);
                   5338:             }
1.520     raeburn  5339:             $output = &lonhttpdurl($output);
                   5340:         }
1.63      www      5341:     }
1.520     raeburn  5342:     return $output;
1.63      www      5343: }
1.59      www      5344: 
1.822     bisitz   5345: ##############################################
                   5346: =pod
                   5347: 
1.832     bisitz   5348: =item * &authorspace()
                   5349: 
1.1028    raeburn  5350: Inputs: $url (usually will be undef).
1.832     bisitz   5351: 
1.1075.2.40  raeburn  5352: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5353:          directory being viewed (or for which action is being taken). 
                   5354:          If $url is provided, and begins /priv/<domain>/<uname>
                   5355:          the path will be that portion of the $context argument.
                   5356:          Otherwise the path will be for the author space of the current
                   5357:          user when the current role is author, or for that of the 
                   5358:          co-author/assistant co-author space when the current role 
                   5359:          is co-author or assistant co-author.
1.832     bisitz   5360: 
                   5361: =cut
                   5362: 
                   5363: sub authorspace {
1.1028    raeburn  5364:     my ($url) = @_;
                   5365:     if ($url ne '') {
                   5366:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5367:            return $1;
                   5368:         }
                   5369:     }
1.832     bisitz   5370:     my $caname = '';
1.1024    www      5371:     my $cadom = '';
1.1028    raeburn  5372:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5373:         ($cadom,$caname) =
1.832     bisitz   5374:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5375:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5376:         $caname = $env{'user.name'};
1.1024    www      5377:         $cadom = $env{'user.domain'};
1.832     bisitz   5378:     }
1.1028    raeburn  5379:     if (($caname ne '') && ($cadom ne '')) {
                   5380:         return "/priv/$cadom/$caname/";
                   5381:     }
                   5382:     return;
1.832     bisitz   5383: }
                   5384: 
                   5385: ##############################################
                   5386: =pod
                   5387: 
1.822     bisitz   5388: =item * &head_subbox()
                   5389: 
                   5390: Inputs: $content (contains HTML code with page functions, etc.)
                   5391: 
                   5392: Returns: HTML div with $content
                   5393:          To be included in page header
                   5394: 
                   5395: =cut
                   5396: 
                   5397: sub head_subbox {
                   5398:     my ($content)=@_;
                   5399:     my $output =
1.993     raeburn  5400:         '<div class="LC_head_subbox">'
1.822     bisitz   5401:        .$content
                   5402:        .'</div>'
                   5403: }
                   5404: 
                   5405: ##############################################
                   5406: =pod
                   5407: 
                   5408: =item * &CSTR_pageheader()
                   5409: 
1.1026    raeburn  5410: Input: (optional) filename from which breadcrumb trail is built.
                   5411:        In most cases no input as needed, as $env{'request.filename'}
                   5412:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5413: 
                   5414: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5415:          To be included on Authoring Space pages
1.822     bisitz   5416: 
                   5417: =cut
                   5418: 
                   5419: sub CSTR_pageheader {
1.1026    raeburn  5420:     my ($trailfile) = @_;
                   5421:     if ($trailfile eq '') {
                   5422:         $trailfile = $env{'request.filename'};
                   5423:     }
                   5424: 
                   5425: # this is for resources; directories have customtitle, and crumbs
                   5426: # and select recent are created in lonpubdir.pm
                   5427: 
                   5428:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5429:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5430:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5431:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5432:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5433: 
                   5434:     my $parentpath = '';
                   5435:     my $lastitem = '';
                   5436:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5437:         $parentpath = $1;
                   5438:         $lastitem = $2;
                   5439:     } else {
                   5440:         $lastitem = $thisdisfn;
                   5441:     }
1.921     bisitz   5442: 
                   5443:     my $output =
1.822     bisitz   5444:          '<div>'
                   5445:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5446:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5447:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5448:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5449:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5450: 
                   5451:     if ($lastitem) {
                   5452:         $output .=
                   5453:              '<span class="LC_filename">'
                   5454:             .$lastitem
                   5455:             .'</span>';
                   5456:     }
                   5457:     $output .=
                   5458:          '<br />'
1.822     bisitz   5459:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5460:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5461:         .'</form>'
                   5462:         .&Apache::lonmenu::constspaceform()
                   5463:         .'</div>';
1.921     bisitz   5464: 
                   5465:     return $output;
1.822     bisitz   5466: }
                   5467: 
1.60      matthew  5468: ###############################################
                   5469: ###############################################
                   5470: 
                   5471: =pod
                   5472: 
1.112     bowersj2 5473: =back
                   5474: 
1.549     albertel 5475: =head1 HTML Helpers
1.112     bowersj2 5476: 
                   5477: =over 4
                   5478: 
                   5479: =item * &bodytag()
1.60      matthew  5480: 
                   5481: Returns a uniform header for LON-CAPA web pages.
                   5482: 
                   5483: Inputs: 
                   5484: 
1.112     bowersj2 5485: =over 4
                   5486: 
                   5487: =item * $title, A title to be displayed on the page.
                   5488: 
                   5489: =item * $function, the current role (can be undef).
                   5490: 
                   5491: =item * $addentries, extra parameters for the <body> tag.
                   5492: 
                   5493: =item * $bodyonly, if defined, only return the <body> tag.
                   5494: 
                   5495: =item * $domain, if defined, force a given domain.
                   5496: 
                   5497: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5498:             text interface only)
1.60      matthew  5499: 
1.814     bisitz   5500: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5501:                      navigational links
1.317     albertel 5502: 
1.338     albertel 5503: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5504: 
1.1075.2.12  raeburn  5505: =item * $no_inline_link, if true and in remote mode, don't show the
                   5506:          'Switch To Inline Menu' link
                   5507: 
1.460     albertel 5508: =item * $args, optional argument valid values are
                   5509:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1075.2.133  raeburn  5510:             use_absolute     -> for external resource or syllabus, this will
                   5511:                                 contain https://<hostname> if server uses
                   5512:                                 https (as per hosts.tab), but request is for http
                   5513:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5514: 
1.1075.2.15  raeburn  5515: =item * $advtoolsref, optional argument, ref to an array containing
                   5516:             inlineremote items to be added in "Functions" menu below
                   5517:             breadcrumbs.
                   5518: 
1.112     bowersj2 5519: =back
                   5520: 
1.60      matthew  5521: Returns: A uniform header for LON-CAPA web pages.  
                   5522: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5523: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5524: other decorations will be returned.
                   5525: 
                   5526: =cut
                   5527: 
1.54      www      5528: sub bodytag {
1.831     bisitz   5529:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5530:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5531: 
1.954     raeburn  5532:     my $public;
                   5533:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5534:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5535:         $public = 1;
                   5536:     }
1.460     albertel 5537:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5538:     my $httphost = $args->{'use_absolute'};
1.1075.2.133  raeburn  5539:     my $hostname = $args->{'hostname'};
1.339     albertel 5540: 
1.183     matthew  5541:     $function = &get_users_function() if (!$function);
1.339     albertel 5542:     my $img =    &designparm($function.'.img',$domain);
                   5543:     my $font =   &designparm($function.'.font',$domain);
                   5544:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5545: 
1.803     bisitz   5546:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5547: 		   'bgcolor' => $pgbg,
1.339     albertel 5548: 		   'text'    => $font,
                   5549:                    'alink'   => &designparm($function.'.alink',$domain),
                   5550: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5551: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5552:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5553: 
1.63      www      5554:  # role and realm
1.1075.2.68  raeburn  5555:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5556:     if ($realm) {
                   5557:         $realm = '/'.$realm;
                   5558:     }
1.378     raeburn  5559:     if ($role  eq 'ca') {
1.479     albertel 5560:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5561:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5562:     } 
1.55      www      5563: # realm
1.258     albertel 5564:     if ($env{'request.course.id'}) {
1.378     raeburn  5565:         if ($env{'request.role'} !~ /^cr/) {
                   5566:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  5567:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  5568:             if ($env{'request.role.desc'}) {
                   5569:                 $role = $env{'request.role.desc'};
                   5570:             } else {
                   5571:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5572:             }
1.1075.2.115  raeburn  5573:         } else {
                   5574:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  5575:         }
1.898     raeburn  5576:         if ($env{'request.course.sec'}) {
                   5577:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5578:         }   
1.359     albertel 5579: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5580:     } else {
                   5581:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5582:     }
1.433     albertel 5583: 
1.359     albertel 5584:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5585: 
1.438     albertel 5586:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5587: 
1.101     www      5588: # construct main body tag
1.359     albertel 5589:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  5590: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5591: 
1.1075.2.38  raeburn  5592:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5593: 
                   5594:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5595:         return $bodytag;
1.1075.2.38  raeburn  5596:     }
1.359     albertel 5597: 
1.954     raeburn  5598:     if ($public) {
1.433     albertel 5599: 	undef($role);
                   5600:     }
1.359     albertel 5601:     
1.762     bisitz   5602:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5603:     #
                   5604:     # Extra info if you are the DC
                   5605:     my $dc_info = '';
                   5606:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5607:                         $env{'course.'.$env{'request.course.id'}.
                   5608:                                  '.domain'}.'/'})) {
                   5609:         my $cid = $env{'request.course.id'};
1.917     raeburn  5610:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5611:         $dc_info =~ s/\s+$//;
1.359     albertel 5612:     }
                   5613: 
1.1075.2.108  raeburn  5614:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 5615: 
1.1075.2.13  raeburn  5616:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5617: 
1.1075.2.38  raeburn  5618: 
                   5619: 
1.1075.2.21  raeburn  5620:     my $funclist;
                   5621:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5622:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5623:                     Apache::lonmenu::serverform();
                   5624:         my $forbodytag;
                   5625:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5626:                                             $forcereg,$args->{'group'},
                   5627:                                             $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5628:                                             $advtoolsref,'','',\$forbodytag);
1.1075.2.21  raeburn  5629:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5630:             $funclist = $forbodytag;
                   5631:         }
                   5632:     } else {
1.903     droeschl 5633: 
                   5634:         #    if ($env{'request.state'} eq 'construct') {
                   5635:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5636:         #    }
                   5637: 
1.1075.2.38  raeburn  5638:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5639:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5640: 
1.1075.2.38  raeburn  5641:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5642: 
1.916     droeschl 5643:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5644:             if ($dc_info) {
                   5645:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5646:             }
1.1075.2.38  raeburn  5647:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5648:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5649:             return $bodytag;
                   5650:         }
1.894     droeschl 5651: 
1.927     raeburn  5652:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5653:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5654:         }
1.916     droeschl 5655: 
1.1075.2.38  raeburn  5656:         $bodytag .= $right;
1.852     droeschl 5657: 
1.917     raeburn  5658:         if ($dc_info) {
                   5659:             $dc_info = &dc_courseid_toggle($dc_info);
                   5660:         }
                   5661:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5662: 
1.1075.2.61  raeburn  5663:         #if directed to not display the secondary menu, don't.
                   5664:         if ($args->{'no_secondary_menu'}) {
                   5665:             return $bodytag;
                   5666:         }
1.903     droeschl 5667:         #don't show menus for public users
1.954     raeburn  5668:         if (!$public){
1.1075.2.52  raeburn  5669:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5670:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5671:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5672:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5673:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1075.2.133  raeburn  5674:                                 $args->{'bread_crumbs'},'','',$hostname);
1.1075.2.116  raeburn  5675:             } elsif ($forcereg) {
1.1075.2.22  raeburn  5676:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.116  raeburn  5677:                                                             $args->{'group'},
1.1075.2.133  raeburn  5678:                                                             $args->{'hide_buttons',
                   5679:                                                             $hostname});
1.1075.2.15  raeburn  5680:             } else {
1.1075.2.21  raeburn  5681:                 my $forbodytag;
                   5682:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5683:                                                     $forcereg,$args->{'group'},
                   5684:                                                     $args->{'bread_crumbs'},
1.1075.2.133  raeburn  5685:                                                     $advtoolsref,'',$hostname,
                   5686:                                                     \$forbodytag);
1.1075.2.21  raeburn  5687:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5688:                     $bodytag .= $forbodytag;
                   5689:                 }
1.920     raeburn  5690:             }
1.903     droeschl 5691:         }else{
                   5692:             # this is to seperate menu from content when there's no secondary
                   5693:             # menu. Especially needed for public accessible ressources.
                   5694:             $bodytag .= '<hr style="clear:both" />';
                   5695:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5696:         }
1.903     droeschl 5697: 
1.235     raeburn  5698:         return $bodytag;
1.1075.2.12  raeburn  5699:     }
                   5700: 
                   5701: #
                   5702: # Top frame rendering, Remote is up
                   5703: #
                   5704: 
                   5705:     my $imgsrc = $img;
                   5706:     if ($img =~ /^\/adm/) {
                   5707:         $imgsrc = &lonhttpdurl($img);
                   5708:     }
                   5709:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5710: 
1.1075.2.60  raeburn  5711:     my $help=($no_inline_link?''
                   5712:               :&Apache::loncommon::top_nav_help('Help'));
                   5713: 
1.1075.2.12  raeburn  5714:     # Explicit link to get inline menu
                   5715:     my $menu= ($no_inline_link?''
                   5716:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5717: 
                   5718:     if ($dc_info) {
                   5719:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5720:     }
                   5721: 
1.1075.2.38  raeburn  5722:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5723:     unless ($public) {
                   5724:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5725:                                 undef,'LC_menubuttons_link');
                   5726:     }
                   5727: 
1.1075.2.12  raeburn  5728:     unless ($env{'form.inhibitmenu'}) {
                   5729:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5730:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5731:                        <li>$help</li>
1.1075.2.12  raeburn  5732:                        <li>$menu</li>
                   5733:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5734:     }
1.1075.2.13  raeburn  5735:     if ($env{'request.state'} eq 'construct') {
                   5736:         if (!$public){
                   5737:             if ($env{'request.state'} eq 'construct') {
                   5738:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5739:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5740:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5741:                             &Apache::lonmenu::innerregister($forcereg,
                   5742:                                                             $args->{'bread_crumbs'});
                   5743:             }
                   5744:         }
                   5745:     }
1.1075.2.21  raeburn  5746:     return $bodytag."\n".$funclist;
1.182     matthew  5747: }
                   5748: 
1.917     raeburn  5749: sub dc_courseid_toggle {
                   5750:     my ($dc_info) = @_;
1.980     raeburn  5751:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5752:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5753:            &mt('(More ...)').'</a></span>'.
                   5754:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5755: }
                   5756: 
1.330     albertel 5757: sub make_attr_string {
                   5758:     my ($register,$attr_ref) = @_;
                   5759: 
                   5760:     if ($attr_ref && !ref($attr_ref)) {
                   5761: 	die("addentries Must be a hash ref ".
                   5762: 	    join(':',caller(1))." ".
                   5763: 	    join(':',caller(0))." ");
                   5764:     }
                   5765: 
                   5766:     if ($register) {
1.339     albertel 5767: 	my ($on_load,$on_unload);
                   5768: 	foreach my $key (keys(%{$attr_ref})) {
                   5769: 	    if      (lc($key) eq 'onload') {
                   5770: 		$on_load.=$attr_ref->{$key}.';';
                   5771: 		delete($attr_ref->{$key});
                   5772: 
                   5773: 	    } elsif (lc($key) eq 'onunload') {
                   5774: 		$on_unload.=$attr_ref->{$key}.';';
                   5775: 		delete($attr_ref->{$key});
                   5776: 	    }
                   5777: 	}
1.1075.2.12  raeburn  5778:         if ($env{'environment.remote'} eq 'on') {
                   5779:             $attr_ref->{'onload'}  =
                   5780:                 &Apache::lonmenu::loadevents().  $on_load;
                   5781:             $attr_ref->{'onunload'}=
                   5782:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5783:         } else {  
                   5784: 	    $attr_ref->{'onload'}  = $on_load;
                   5785: 	    $attr_ref->{'onunload'}= $on_unload;
                   5786:         }
1.330     albertel 5787:     }
1.339     albertel 5788: 
1.330     albertel 5789:     my $attr_string;
1.1075.2.56  raeburn  5790:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5791: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5792:     }
                   5793:     return $attr_string;
                   5794: }
                   5795: 
                   5796: 
1.182     matthew  5797: ###############################################
1.251     albertel 5798: ###############################################
                   5799: 
                   5800: =pod
                   5801: 
                   5802: =item * &endbodytag()
                   5803: 
                   5804: Returns a uniform footer for LON-CAPA web pages.
                   5805: 
1.635     raeburn  5806: Inputs: 1 - optional reference to an args hash
                   5807: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5808: a 'Continue' link is not displayed if the page contains an
                   5809: internal redirect in the <head></head> section,
                   5810: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5811: 
                   5812: =cut
                   5813: 
                   5814: sub endbodytag {
1.635     raeburn  5815:     my ($args) = @_;
1.1075.2.6  raeburn  5816:     my $endbodytag;
                   5817:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5818:         $endbodytag='</body>';
                   5819:     }
1.315     albertel 5820:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5821:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5822: 	    $endbodytag=
                   5823: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5824: 	        &mt('Continue').'</a>'.
                   5825: 	        $endbodytag;
                   5826:         }
1.315     albertel 5827:     }
1.251     albertel 5828:     return $endbodytag;
                   5829: }
                   5830: 
1.352     albertel 5831: =pod
                   5832: 
                   5833: =item * &standard_css()
                   5834: 
                   5835: Returns a style sheet
                   5836: 
                   5837: Inputs: (all optional)
                   5838:             domain         -> force to color decorate a page for a specific
                   5839:                                domain
                   5840:             function       -> force usage of a specific rolish color scheme
                   5841:             bgcolor        -> override the default page bgcolor
                   5842: 
                   5843: =cut
                   5844: 
1.343     albertel 5845: sub standard_css {
1.345     albertel 5846:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5847:     $function  = &get_users_function() if (!$function);
                   5848:     my $img    = &designparm($function.'.img',   $domain);
                   5849:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5850:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5851:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5852: #second colour for later usage
1.345     albertel 5853:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5854:     my $pgbg_or_bgcolor =
                   5855: 	         $bgcolor ||
1.352     albertel 5856: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5857:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5858:     my $alink  = &designparm($function.'.alink', $domain);
                   5859:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5860:     my $link   = &designparm($function.'.link',  $domain);
                   5861: 
1.602     albertel 5862:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5863:     my $mono                 = 'monospace';
1.850     bisitz   5864:     my $data_table_head      = $sidebg;
                   5865:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5866:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5867:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5868:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5869:     my $mail_new             = '#FFBB77';
                   5870:     my $mail_new_hover       = '#DD9955';
                   5871:     my $mail_read            = '#BBBB77';
                   5872:     my $mail_read_hover      = '#999944';
                   5873:     my $mail_replied         = '#AAAA88';
                   5874:     my $mail_replied_hover   = '#888855';
                   5875:     my $mail_other           = '#99BBBB';
                   5876:     my $mail_other_hover     = '#669999';
1.391     albertel 5877:     my $table_header         = '#DDDDDD';
1.489     raeburn  5878:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5879:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5880:     my $button_hover         = '#BF2317';
1.392     albertel 5881: 
1.608     albertel 5882:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5883:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5884:                                              : '0 3px 0 4px';
1.448     albertel 5885: 
1.523     albertel 5886: 
1.343     albertel 5887:     return <<END;
1.947     droeschl 5888: 
                   5889: /* needed for iframe to allow 100% height in FF */
                   5890: body, html { 
                   5891:     margin: 0;
                   5892:     padding: 0 0.5%;
                   5893:     height: 99%; /* to avoid scrollbars */
                   5894: }
                   5895: 
1.795     www      5896: body {
1.911     bisitz   5897:   font-family: $sans;
                   5898:   line-height:130%;
                   5899:   font-size:0.83em;
                   5900:   color:$font;
1.795     www      5901: }
                   5902: 
1.959     onken    5903: a:focus,
                   5904: a:focus img {
1.795     www      5905:   color: red;
                   5906: }
1.698     harmsja  5907: 
1.911     bisitz   5908: form, .inline {
                   5909:   display: inline;
1.795     www      5910: }
1.721     harmsja  5911: 
1.795     www      5912: .LC_right {
1.911     bisitz   5913:   text-align:right;
1.795     www      5914: }
                   5915: 
                   5916: .LC_middle {
1.911     bisitz   5917:   vertical-align:middle;
1.795     www      5918: }
1.721     harmsja  5919: 
1.1075.2.38  raeburn  5920: .LC_floatleft {
                   5921:   float: left;
                   5922: }
                   5923: 
                   5924: .LC_floatright {
                   5925:   float: right;
                   5926: }
                   5927: 
1.911     bisitz   5928: .LC_400Box {
                   5929:   width:400px;
                   5930: }
1.721     harmsja  5931: 
1.947     droeschl 5932: .LC_iframecontainer {
                   5933:     width: 98%;
                   5934:     margin: 0;
                   5935:     position: fixed;
                   5936:     top: 8.5em;
                   5937:     bottom: 0;
                   5938: }
                   5939: 
                   5940: .LC_iframecontainer iframe{
                   5941:     border: none;
                   5942:     width: 100%;
                   5943:     height: 100%;
                   5944: }
                   5945: 
1.778     bisitz   5946: .LC_filename {
                   5947:   font-family: $mono;
                   5948:   white-space:pre;
1.921     bisitz   5949:   font-size: 120%;
1.778     bisitz   5950: }
                   5951: 
                   5952: .LC_fileicon {
                   5953:   border: none;
                   5954:   height: 1.3em;
                   5955:   vertical-align: text-bottom;
                   5956:   margin-right: 0.3em;
                   5957:   text-decoration:none;
                   5958: }
                   5959: 
1.1008    www      5960: .LC_setting {
                   5961:   text-decoration:underline;
                   5962: }
                   5963: 
1.350     albertel 5964: .LC_error {
                   5965:   color: red;
                   5966: }
1.795     www      5967: 
1.1075.2.15  raeburn  5968: .LC_warning {
                   5969:   color: darkorange;
                   5970: }
                   5971: 
1.457     albertel 5972: .LC_diff_removed {
1.733     bisitz   5973:   color: red;
1.394     albertel 5974: }
1.532     albertel 5975: 
                   5976: .LC_info,
1.457     albertel 5977: .LC_success,
                   5978: .LC_diff_added {
1.350     albertel 5979:   color: green;
                   5980: }
1.795     www      5981: 
1.802     bisitz   5982: div.LC_confirm_box {
                   5983:   background-color: #FAFAFA;
                   5984:   border: 1px solid $lg_border_color;
                   5985:   margin-right: 0;
                   5986:   padding: 5px;
                   5987: }
                   5988: 
                   5989: div.LC_confirm_box .LC_error img,
                   5990: div.LC_confirm_box .LC_success img {
                   5991:   vertical-align: middle;
                   5992: }
                   5993: 
1.1075.2.108  raeburn  5994: .LC_maxwidth {
                   5995:   max-width: 100%;
                   5996:   height: auto;
                   5997: }
                   5998: 
                   5999: .LC_textsize_mobile {
                   6000:   \@media only screen and (max-device-width: 480px) {
                   6001:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6002:   }
                   6003: }
                   6004: 
1.440     albertel 6005: .LC_icon {
1.771     droeschl 6006:   border: none;
1.790     droeschl 6007:   vertical-align: middle;
1.771     droeschl 6008: }
                   6009: 
1.543     albertel 6010: .LC_docs_spacer {
                   6011:   width: 25px;
                   6012:   height: 1px;
1.771     droeschl 6013:   border: none;
1.543     albertel 6014: }
1.346     albertel 6015: 
1.532     albertel 6016: .LC_internal_info {
1.735     bisitz   6017:   color: #999999;
1.532     albertel 6018: }
                   6019: 
1.794     www      6020: .LC_discussion {
1.1050    www      6021:   background: $data_table_dark;
1.911     bisitz   6022:   border: 1px solid black;
                   6023:   margin: 2px;
1.794     www      6024: }
                   6025: 
                   6026: .LC_disc_action_left {
1.1050    www      6027:   background: $sidebg;
1.911     bisitz   6028:   text-align: left;
1.1050    www      6029:   padding: 4px;
                   6030:   margin: 2px;
1.794     www      6031: }
                   6032: 
                   6033: .LC_disc_action_right {
1.1050    www      6034:   background: $sidebg;
1.911     bisitz   6035:   text-align: right;
1.1050    www      6036:   padding: 4px;
                   6037:   margin: 2px;
1.794     www      6038: }
                   6039: 
                   6040: .LC_disc_new_item {
1.911     bisitz   6041:   background: white;
                   6042:   border: 2px solid red;
1.1050    www      6043:   margin: 4px;
                   6044:   padding: 4px;
1.794     www      6045: }
                   6046: 
                   6047: .LC_disc_old_item {
1.911     bisitz   6048:   background: white;
1.1050    www      6049:   margin: 4px;
                   6050:   padding: 4px;
1.794     www      6051: }
                   6052: 
1.458     albertel 6053: table.LC_pastsubmission {
                   6054:   border: 1px solid black;
                   6055:   margin: 2px;
                   6056: }
                   6057: 
1.924     bisitz   6058: table#LC_menubuttons {
1.345     albertel 6059:   width: 100%;
                   6060:   background: $pgbg;
1.392     albertel 6061:   border: 2px;
1.402     albertel 6062:   border-collapse: separate;
1.803     bisitz   6063:   padding: 0;
1.345     albertel 6064: }
1.392     albertel 6065: 
1.801     tempelho 6066: table#LC_title_bar a {
                   6067:   color: $fontmenu;
                   6068: }
1.836     bisitz   6069: 
1.807     droeschl 6070: table#LC_title_bar {
1.819     tempelho 6071:   clear: both;
1.836     bisitz   6072:   display: none;
1.807     droeschl 6073: }
                   6074: 
1.795     www      6075: table#LC_title_bar,
1.933     droeschl 6076: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6077: table#LC_title_bar.LC_with_remote {
1.359     albertel 6078:   width: 100%;
1.392     albertel 6079:   border-color: $pgbg;
                   6080:   border-style: solid;
                   6081:   border-width: $border;
1.379     albertel 6082:   background: $pgbg;
1.801     tempelho 6083:   color: $fontmenu;
1.392     albertel 6084:   border-collapse: collapse;
1.803     bisitz   6085:   padding: 0;
1.819     tempelho 6086:   margin: 0;
1.359     albertel 6087: }
1.795     www      6088: 
1.933     droeschl 6089: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6090:     margin: 0;
                   6091:     padding: 0;
1.933     droeschl 6092:     position: relative;
                   6093:     list-style: none;
1.913     droeschl 6094: }
1.933     droeschl 6095: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6096:     display: inline;
                   6097: }
1.933     droeschl 6098: 
                   6099: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6100:     padding: 0;
1.933     droeschl 6101:     margin: 0;
                   6102:     float: left;
1.913     droeschl 6103: }
1.933     droeschl 6104: .LC_breadcrumb_tools_tools {
                   6105:     padding: 0;
                   6106:     margin: 0;
1.913     droeschl 6107:     float: right;
                   6108: }
                   6109: 
1.359     albertel 6110: table#LC_title_bar td {
                   6111:   background: $tabbg;
                   6112: }
1.795     www      6113: 
1.911     bisitz   6114: table#LC_menubuttons img {
1.803     bisitz   6115:   border: none;
1.346     albertel 6116: }
1.795     www      6117: 
1.842     droeschl 6118: .LC_breadcrumbs_component {
1.911     bisitz   6119:   float: right;
                   6120:   margin: 0 1em;
1.357     albertel 6121: }
1.842     droeschl 6122: .LC_breadcrumbs_component img {
1.911     bisitz   6123:   vertical-align: middle;
1.777     tempelho 6124: }
1.795     www      6125: 
1.1075.2.108  raeburn  6126: .LC_breadcrumbs_hoverable {
                   6127:   background: $sidebg;
                   6128: }
                   6129: 
1.383     albertel 6130: td.LC_table_cell_checkbox {
                   6131:   text-align: center;
                   6132: }
1.795     www      6133: 
                   6134: .LC_fontsize_small {
1.911     bisitz   6135:   font-size: 70%;
1.705     tempelho 6136: }
                   6137: 
1.844     bisitz   6138: #LC_breadcrumbs {
1.911     bisitz   6139:   clear:both;
                   6140:   background: $sidebg;
                   6141:   border-bottom: 1px solid $lg_border_color;
                   6142:   line-height: 2.5em;
1.933     droeschl 6143:   overflow: hidden;
1.911     bisitz   6144:   margin: 0;
                   6145:   padding: 0;
1.995     raeburn  6146:   text-align: left;
1.819     tempelho 6147: }
1.862     bisitz   6148: 
1.1075.2.16  raeburn  6149: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6150:   clear:both;
                   6151:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6152:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6153:   margin: 0 0 10px 0;
1.966     bisitz   6154:   padding: 3px;
1.995     raeburn  6155:   text-align: left;
1.822     bisitz   6156: }
                   6157: 
1.795     www      6158: .LC_fontsize_medium {
1.911     bisitz   6159:   font-size: 85%;
1.705     tempelho 6160: }
                   6161: 
1.795     www      6162: .LC_fontsize_large {
1.911     bisitz   6163:   font-size: 120%;
1.705     tempelho 6164: }
                   6165: 
1.346     albertel 6166: .LC_menubuttons_inline_text {
                   6167:   color: $font;
1.698     harmsja  6168:   font-size: 90%;
1.701     harmsja  6169:   padding-left:3px;
1.346     albertel 6170: }
                   6171: 
1.934     droeschl 6172: .LC_menubuttons_inline_text img{
                   6173:   vertical-align: middle;
                   6174: }
                   6175: 
1.1051    www      6176: li.LC_menubuttons_inline_text img {
1.951     onken    6177:   cursor:pointer;
1.1002    droeschl 6178:   text-decoration: none;
1.951     onken    6179: }
                   6180: 
1.526     www      6181: .LC_menubuttons_link {
                   6182:   text-decoration: none;
                   6183: }
1.795     www      6184: 
1.522     albertel 6185: .LC_menubuttons_category {
1.521     www      6186:   color: $font;
1.526     www      6187:   background: $pgbg;
1.521     www      6188:   font-size: larger;
                   6189:   font-weight: bold;
                   6190: }
                   6191: 
1.346     albertel 6192: td.LC_menubuttons_text {
1.911     bisitz   6193:   color: $font;
1.346     albertel 6194: }
1.706     harmsja  6195: 
1.346     albertel 6196: .LC_current_location {
                   6197:   background: $tabbg;
                   6198: }
1.795     www      6199: 
1.1075.2.134  raeburn  6200: td.LC_zero_height {
                   6201:   line-height: 0;
                   6202:   cellpadding: 0;
                   6203: }
                   6204: 
1.938     bisitz   6205: table.LC_data_table {
1.347     albertel 6206:   border: 1px solid #000000;
1.402     albertel 6207:   border-collapse: separate;
1.426     albertel 6208:   border-spacing: 1px;
1.610     albertel 6209:   background: $pgbg;
1.347     albertel 6210: }
1.795     www      6211: 
1.422     albertel 6212: .LC_data_table_dense {
                   6213:   font-size: small;
                   6214: }
1.795     www      6215: 
1.507     raeburn  6216: table.LC_nested_outer {
                   6217:   border: 1px solid #000000;
1.589     raeburn  6218:   border-collapse: collapse;
1.803     bisitz   6219:   border-spacing: 0;
1.507     raeburn  6220:   width: 100%;
                   6221: }
1.795     www      6222: 
1.879     raeburn  6223: table.LC_innerpickbox,
1.507     raeburn  6224: table.LC_nested {
1.803     bisitz   6225:   border: none;
1.589     raeburn  6226:   border-collapse: collapse;
1.803     bisitz   6227:   border-spacing: 0;
1.507     raeburn  6228:   width: 100%;
                   6229: }
1.795     www      6230: 
1.911     bisitz   6231: table.LC_data_table tr th,
                   6232: table.LC_calendar tr th,
1.879     raeburn  6233: table.LC_prior_tries tr th,
                   6234: table.LC_innerpickbox tr th {
1.349     albertel 6235:   font-weight: bold;
                   6236:   background-color: $data_table_head;
1.801     tempelho 6237:   color:$fontmenu;
1.701     harmsja  6238:   font-size:90%;
1.347     albertel 6239: }
1.795     www      6240: 
1.879     raeburn  6241: table.LC_innerpickbox tr th,
                   6242: table.LC_innerpickbox tr td {
                   6243:   vertical-align: top;
                   6244: }
                   6245: 
1.711     raeburn  6246: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6247:   background-color: #CCCCCC;
1.711     raeburn  6248:   font-weight: bold;
                   6249:   text-align: left;
                   6250: }
1.795     www      6251: 
1.912     bisitz   6252: table.LC_data_table tr.LC_odd_row > td {
                   6253:   background-color: $data_table_light;
                   6254:   padding: 2px;
                   6255:   vertical-align: top;
                   6256: }
                   6257: 
1.809     bisitz   6258: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6259:   background-color: $data_table_light;
1.912     bisitz   6260:   vertical-align: top;
                   6261: }
                   6262: 
                   6263: table.LC_data_table tr.LC_even_row > td {
                   6264:   background-color: $data_table_dark;
1.425     albertel 6265:   padding: 2px;
1.900     bisitz   6266:   vertical-align: top;
1.347     albertel 6267: }
1.795     www      6268: 
1.809     bisitz   6269: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6270:   background-color: $data_table_dark;
1.900     bisitz   6271:   vertical-align: top;
1.347     albertel 6272: }
1.795     www      6273: 
1.425     albertel 6274: table.LC_data_table tr.LC_data_table_highlight td {
                   6275:   background-color: $data_table_darker;
                   6276: }
1.795     www      6277: 
1.639     raeburn  6278: table.LC_data_table tr td.LC_leftcol_header {
                   6279:   background-color: $data_table_head;
                   6280:   font-weight: bold;
                   6281: }
1.795     www      6282: 
1.451     albertel 6283: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6284: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6285:   font-weight: bold;
                   6286:   font-style: italic;
                   6287:   text-align: center;
                   6288:   padding: 8px;
1.347     albertel 6289: }
1.795     www      6290: 
1.1075.2.30  raeburn  6291: table.LC_data_table tr.LC_empty_row td,
                   6292: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6293:   background-color: $sidebg;
                   6294: }
                   6295: 
                   6296: table.LC_nested tr.LC_empty_row td {
                   6297:   background-color: #FFFFFF;
                   6298: }
                   6299: 
1.890     droeschl 6300: table.LC_caption {
                   6301: }
                   6302: 
1.507     raeburn  6303: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6304:   padding: 4ex
                   6305: }
1.795     www      6306: 
1.507     raeburn  6307: table.LC_nested_outer tr th {
                   6308:   font-weight: bold;
1.801     tempelho 6309:   color:$fontmenu;
1.507     raeburn  6310:   background-color: $data_table_head;
1.701     harmsja  6311:   font-size: small;
1.507     raeburn  6312:   border-bottom: 1px solid #000000;
                   6313: }
1.795     www      6314: 
1.507     raeburn  6315: table.LC_nested_outer tr td.LC_subheader {
                   6316:   background-color: $data_table_head;
                   6317:   font-weight: bold;
                   6318:   font-size: small;
                   6319:   border-bottom: 1px solid #000000;
                   6320:   text-align: right;
1.451     albertel 6321: }
1.795     www      6322: 
1.507     raeburn  6323: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6324:   background-color: #CCCCCC;
1.451     albertel 6325:   font-weight: bold;
                   6326:   font-size: small;
1.507     raeburn  6327:   text-align: center;
                   6328: }
1.795     www      6329: 
1.589     raeburn  6330: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6331: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6332:   text-align: left;
1.451     albertel 6333: }
1.795     www      6334: 
1.507     raeburn  6335: table.LC_nested td {
1.735     bisitz   6336:   background-color: #FFFFFF;
1.451     albertel 6337:   font-size: small;
1.507     raeburn  6338: }
1.795     www      6339: 
1.507     raeburn  6340: table.LC_nested_outer tr th.LC_right_item,
                   6341: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6342: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6343: table.LC_nested tr td.LC_right_item {
1.451     albertel 6344:   text-align: right;
                   6345: }
                   6346: 
1.507     raeburn  6347: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6348:   background-color: #EEEEEE;
1.451     albertel 6349: }
                   6350: 
1.473     raeburn  6351: table.LC_createuser {
                   6352: }
                   6353: 
                   6354: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6355:   font-size: small;
1.473     raeburn  6356: }
                   6357: 
                   6358: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6359:   background-color: #CCCCCC;
1.473     raeburn  6360:   font-weight: bold;
                   6361:   text-align: center;
                   6362: }
                   6363: 
1.349     albertel 6364: table.LC_calendar {
                   6365:   border: 1px solid #000000;
                   6366:   border-collapse: collapse;
1.917     raeburn  6367:   width: 98%;
1.349     albertel 6368: }
1.795     www      6369: 
1.349     albertel 6370: table.LC_calendar_pickdate {
                   6371:   font-size: xx-small;
                   6372: }
1.795     www      6373: 
1.349     albertel 6374: table.LC_calendar tr td {
                   6375:   border: 1px solid #000000;
                   6376:   vertical-align: top;
1.917     raeburn  6377:   width: 14%;
1.349     albertel 6378: }
1.795     www      6379: 
1.349     albertel 6380: table.LC_calendar tr td.LC_calendar_day_empty {
                   6381:   background-color: $data_table_dark;
                   6382: }
1.795     www      6383: 
1.779     bisitz   6384: table.LC_calendar tr td.LC_calendar_day_current {
                   6385:   background-color: $data_table_highlight;
1.777     tempelho 6386: }
1.795     www      6387: 
1.938     bisitz   6388: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6389:   background-color: $mail_new;
                   6390: }
1.795     www      6391: 
1.938     bisitz   6392: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6393:   background-color: $mail_new_hover;
                   6394: }
1.795     www      6395: 
1.938     bisitz   6396: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6397:   background-color: $mail_read;
                   6398: }
1.795     www      6399: 
1.938     bisitz   6400: /*
                   6401: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6402:   background-color: $mail_read_hover;
                   6403: }
1.938     bisitz   6404: */
1.795     www      6405: 
1.938     bisitz   6406: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6407:   background-color: $mail_replied;
                   6408: }
1.795     www      6409: 
1.938     bisitz   6410: /*
                   6411: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6412:   background-color: $mail_replied_hover;
                   6413: }
1.938     bisitz   6414: */
1.795     www      6415: 
1.938     bisitz   6416: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6417:   background-color: $mail_other;
                   6418: }
1.795     www      6419: 
1.938     bisitz   6420: /*
                   6421: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6422:   background-color: $mail_other_hover;
                   6423: }
1.938     bisitz   6424: */
1.494     raeburn  6425: 
1.777     tempelho 6426: table.LC_data_table tr > td.LC_browser_file,
                   6427: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6428:   background: #AAEE77;
1.389     albertel 6429: }
1.795     www      6430: 
1.777     tempelho 6431: table.LC_data_table tr > td.LC_browser_file_locked,
                   6432: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6433:   background: #FFAA99;
1.387     albertel 6434: }
1.795     www      6435: 
1.777     tempelho 6436: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6437:   background: #888888;
1.779     bisitz   6438: }
1.795     www      6439: 
1.777     tempelho 6440: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6441: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6442:   background: #F8F866;
1.777     tempelho 6443: }
1.795     www      6444: 
1.696     bisitz   6445: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6446:   background: #E0E8FF;
1.387     albertel 6447: }
1.696     bisitz   6448: 
1.707     bisitz   6449: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6450:   /* background: #77FF77; */
1.707     bisitz   6451: }
1.795     www      6452: 
1.707     bisitz   6453: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6454:   border-right: 8px solid #FFFF77;
1.707     bisitz   6455: }
1.795     www      6456: 
1.707     bisitz   6457: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6458:   border-right: 8px solid #FFAA77;
1.707     bisitz   6459: }
1.795     www      6460: 
1.707     bisitz   6461: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6462:   border-right: 8px solid #FF7777;
1.707     bisitz   6463: }
1.795     www      6464: 
1.707     bisitz   6465: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6466:   border-right: 8px solid #AAFF77;
1.707     bisitz   6467: }
1.795     www      6468: 
1.707     bisitz   6469: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6470:   border-right: 8px solid #11CC55;
1.707     bisitz   6471: }
                   6472: 
1.388     albertel 6473: span.LC_current_location {
1.701     harmsja  6474:   font-size:larger;
1.388     albertel 6475:   background: $pgbg;
                   6476: }
1.387     albertel 6477: 
1.1029    www      6478: span.LC_current_nav_location {
                   6479:   font-weight:bold;
                   6480:   background: $sidebg;
                   6481: }
                   6482: 
1.395     albertel 6483: span.LC_parm_menu_item {
                   6484:   font-size: larger;
                   6485: }
1.795     www      6486: 
1.395     albertel 6487: span.LC_parm_scope_all {
                   6488:   color: red;
                   6489: }
1.795     www      6490: 
1.395     albertel 6491: span.LC_parm_scope_folder {
                   6492:   color: green;
                   6493: }
1.795     www      6494: 
1.395     albertel 6495: span.LC_parm_scope_resource {
                   6496:   color: orange;
                   6497: }
1.795     www      6498: 
1.395     albertel 6499: span.LC_parm_part {
                   6500:   color: blue;
                   6501: }
1.795     www      6502: 
1.911     bisitz   6503: span.LC_parm_folder,
                   6504: span.LC_parm_symb {
1.395     albertel 6505:   font-size: x-small;
                   6506:   font-family: $mono;
                   6507:   color: #AAAAAA;
                   6508: }
                   6509: 
1.977     bisitz   6510: ul.LC_parm_parmlist li {
                   6511:   display: inline-block;
                   6512:   padding: 0.3em 0.8em;
                   6513:   vertical-align: top;
                   6514:   width: 150px;
                   6515:   border-top:1px solid $lg_border_color;
                   6516: }
                   6517: 
1.795     www      6518: td.LC_parm_overview_level_menu,
                   6519: td.LC_parm_overview_map_menu,
                   6520: td.LC_parm_overview_parm_selectors,
                   6521: td.LC_parm_overview_restrictions  {
1.396     albertel 6522:   border: 1px solid black;
                   6523:   border-collapse: collapse;
                   6524: }
1.795     www      6525: 
1.396     albertel 6526: table.LC_parm_overview_restrictions td {
                   6527:   border-width: 1px 4px 1px 4px;
                   6528:   border-style: solid;
                   6529:   border-color: $pgbg;
                   6530:   text-align: center;
                   6531: }
1.795     www      6532: 
1.396     albertel 6533: table.LC_parm_overview_restrictions th {
                   6534:   background: $tabbg;
                   6535:   border-width: 1px 4px 1px 4px;
                   6536:   border-style: solid;
                   6537:   border-color: $pgbg;
                   6538: }
1.795     www      6539: 
1.398     albertel 6540: table#LC_helpmenu {
1.803     bisitz   6541:   border: none;
1.398     albertel 6542:   height: 55px;
1.803     bisitz   6543:   border-spacing: 0;
1.398     albertel 6544: }
                   6545: 
                   6546: table#LC_helpmenu fieldset legend {
                   6547:   font-size: larger;
                   6548: }
1.795     www      6549: 
1.397     albertel 6550: table#LC_helpmenu_links {
                   6551:   width: 100%;
                   6552:   border: 1px solid black;
                   6553:   background: $pgbg;
1.803     bisitz   6554:   padding: 0;
1.397     albertel 6555:   border-spacing: 1px;
                   6556: }
1.795     www      6557: 
1.397     albertel 6558: table#LC_helpmenu_links tr td {
                   6559:   padding: 1px;
                   6560:   background: $tabbg;
1.399     albertel 6561:   text-align: center;
                   6562:   font-weight: bold;
1.397     albertel 6563: }
1.396     albertel 6564: 
1.795     www      6565: table#LC_helpmenu_links a:link,
                   6566: table#LC_helpmenu_links a:visited,
1.397     albertel 6567: table#LC_helpmenu_links a:active {
                   6568:   text-decoration: none;
                   6569:   color: $font;
                   6570: }
1.795     www      6571: 
1.397     albertel 6572: table#LC_helpmenu_links a:hover {
                   6573:   text-decoration: underline;
                   6574:   color: $vlink;
                   6575: }
1.396     albertel 6576: 
1.417     albertel 6577: .LC_chrt_popup_exists {
                   6578:   border: 1px solid #339933;
                   6579:   margin: -1px;
                   6580: }
1.795     www      6581: 
1.417     albertel 6582: .LC_chrt_popup_up {
                   6583:   border: 1px solid yellow;
                   6584:   margin: -1px;
                   6585: }
1.795     www      6586: 
1.417     albertel 6587: .LC_chrt_popup {
                   6588:   border: 1px solid #8888FF;
                   6589:   background: #CCCCFF;
                   6590: }
1.795     www      6591: 
1.421     albertel 6592: table.LC_pick_box {
                   6593:   border-collapse: separate;
                   6594:   background: white;
                   6595:   border: 1px solid black;
                   6596:   border-spacing: 1px;
                   6597: }
1.795     www      6598: 
1.421     albertel 6599: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6600:   background: $sidebg;
1.421     albertel 6601:   font-weight: bold;
1.900     bisitz   6602:   text-align: left;
1.740     bisitz   6603:   vertical-align: top;
1.421     albertel 6604:   width: 184px;
                   6605:   padding: 8px;
                   6606: }
1.795     www      6607: 
1.579     raeburn  6608: table.LC_pick_box td.LC_pick_box_value {
                   6609:   text-align: left;
                   6610:   padding: 8px;
                   6611: }
1.795     www      6612: 
1.579     raeburn  6613: table.LC_pick_box td.LC_pick_box_select {
                   6614:   text-align: left;
                   6615:   padding: 8px;
                   6616: }
1.795     www      6617: 
1.424     albertel 6618: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6619:   padding: 0;
1.421     albertel 6620:   height: 1px;
                   6621:   background: black;
                   6622: }
1.795     www      6623: 
1.421     albertel 6624: table.LC_pick_box td.LC_pick_box_submit {
                   6625:   text-align: right;
                   6626: }
1.795     www      6627: 
1.579     raeburn  6628: table.LC_pick_box td.LC_evenrow_value {
                   6629:   text-align: left;
                   6630:   padding: 8px;
                   6631:   background-color: $data_table_light;
                   6632: }
1.795     www      6633: 
1.579     raeburn  6634: table.LC_pick_box td.LC_oddrow_value {
                   6635:   text-align: left;
                   6636:   padding: 8px;
                   6637:   background-color: $data_table_light;
                   6638: }
1.795     www      6639: 
1.579     raeburn  6640: span.LC_helpform_receipt_cat {
                   6641:   font-weight: bold;
                   6642: }
1.795     www      6643: 
1.424     albertel 6644: table.LC_group_priv_box {
                   6645:   background: white;
                   6646:   border: 1px solid black;
                   6647:   border-spacing: 1px;
                   6648: }
1.795     www      6649: 
1.424     albertel 6650: table.LC_group_priv_box td.LC_pick_box_title {
                   6651:   background: $tabbg;
                   6652:   font-weight: bold;
                   6653:   text-align: right;
                   6654:   width: 184px;
                   6655: }
1.795     www      6656: 
1.424     albertel 6657: table.LC_group_priv_box td.LC_groups_fixed {
                   6658:   background: $data_table_light;
                   6659:   text-align: center;
                   6660: }
1.795     www      6661: 
1.424     albertel 6662: table.LC_group_priv_box td.LC_groups_optional {
                   6663:   background: $data_table_dark;
                   6664:   text-align: center;
                   6665: }
1.795     www      6666: 
1.424     albertel 6667: table.LC_group_priv_box td.LC_groups_functionality {
                   6668:   background: $data_table_darker;
                   6669:   text-align: center;
                   6670:   font-weight: bold;
                   6671: }
1.795     www      6672: 
1.424     albertel 6673: table.LC_group_priv td {
                   6674:   text-align: left;
1.803     bisitz   6675:   padding: 0;
1.424     albertel 6676: }
                   6677: 
                   6678: .LC_navbuttons {
                   6679:   margin: 2ex 0ex 2ex 0ex;
                   6680: }
1.795     www      6681: 
1.423     albertel 6682: .LC_topic_bar {
                   6683:   font-weight: bold;
                   6684:   background: $tabbg;
1.918     wenzelju 6685:   margin: 1em 0em 1em 2em;
1.805     bisitz   6686:   padding: 3px;
1.918     wenzelju 6687:   font-size: 1.2em;
1.423     albertel 6688: }
1.795     www      6689: 
1.423     albertel 6690: .LC_topic_bar span {
1.918     wenzelju 6691:   left: 0.5em;
                   6692:   position: absolute;
1.423     albertel 6693:   vertical-align: middle;
1.918     wenzelju 6694:   font-size: 1.2em;
1.423     albertel 6695: }
1.795     www      6696: 
1.423     albertel 6697: table.LC_course_group_status {
                   6698:   margin: 20px;
                   6699: }
1.795     www      6700: 
1.423     albertel 6701: table.LC_status_selector td {
                   6702:   vertical-align: top;
                   6703:   text-align: center;
1.424     albertel 6704:   padding: 4px;
                   6705: }
1.795     www      6706: 
1.599     albertel 6707: div.LC_feedback_link {
1.616     albertel 6708:   clear: both;
1.829     kalberla 6709:   background: $sidebg;
1.779     bisitz   6710:   width: 100%;
1.829     kalberla 6711:   padding-bottom: 10px;
                   6712:   border: 1px $tabbg solid;
1.833     kalberla 6713:   height: 22px;
                   6714:   line-height: 22px;
                   6715:   padding-top: 5px;
                   6716: }
                   6717: 
                   6718: div.LC_feedback_link img {
                   6719:   height: 22px;
1.867     kalberla 6720:   vertical-align:middle;
1.829     kalberla 6721: }
                   6722: 
1.911     bisitz   6723: div.LC_feedback_link a {
1.829     kalberla 6724:   text-decoration: none;
1.489     raeburn  6725: }
1.795     www      6726: 
1.867     kalberla 6727: div.LC_comblock {
1.911     bisitz   6728:   display:inline;
1.867     kalberla 6729:   color:$font;
                   6730:   font-size:90%;
                   6731: }
                   6732: 
                   6733: div.LC_feedback_link div.LC_comblock {
                   6734:   padding-left:5px;
                   6735: }
                   6736: 
                   6737: div.LC_feedback_link div.LC_comblock a {
                   6738:   color:$font;
                   6739: }
                   6740: 
1.489     raeburn  6741: span.LC_feedback_link {
1.858     bisitz   6742:   /* background: $feedback_link_bg; */
1.599     albertel 6743:   font-size: larger;
                   6744: }
1.795     www      6745: 
1.599     albertel 6746: span.LC_message_link {
1.858     bisitz   6747:   /* background: $feedback_link_bg; */
1.599     albertel 6748:   font-size: larger;
                   6749:   position: absolute;
                   6750:   right: 1em;
1.489     raeburn  6751: }
1.421     albertel 6752: 
1.515     albertel 6753: table.LC_prior_tries {
1.524     albertel 6754:   border: 1px solid #000000;
                   6755:   border-collapse: separate;
                   6756:   border-spacing: 1px;
1.515     albertel 6757: }
1.523     albertel 6758: 
1.515     albertel 6759: table.LC_prior_tries td {
1.524     albertel 6760:   padding: 2px;
1.515     albertel 6761: }
1.523     albertel 6762: 
                   6763: .LC_answer_correct {
1.795     www      6764:   background: lightgreen;
                   6765:   color: darkgreen;
                   6766:   padding: 6px;
1.523     albertel 6767: }
1.795     www      6768: 
1.523     albertel 6769: .LC_answer_charged_try {
1.797     www      6770:   background: #FFAAAA;
1.795     www      6771:   color: darkred;
                   6772:   padding: 6px;
1.523     albertel 6773: }
1.795     www      6774: 
1.779     bisitz   6775: .LC_answer_not_charged_try,
1.523     albertel 6776: .LC_answer_no_grade,
                   6777: .LC_answer_late {
1.795     www      6778:   background: lightyellow;
1.523     albertel 6779:   color: black;
1.795     www      6780:   padding: 6px;
1.523     albertel 6781: }
1.795     www      6782: 
1.523     albertel 6783: .LC_answer_previous {
1.795     www      6784:   background: lightblue;
                   6785:   color: darkblue;
                   6786:   padding: 6px;
1.523     albertel 6787: }
1.795     www      6788: 
1.779     bisitz   6789: .LC_answer_no_message {
1.777     tempelho 6790:   background: #FFFFFF;
                   6791:   color: black;
1.795     www      6792:   padding: 6px;
1.779     bisitz   6793: }
1.795     www      6794: 
1.1075.2.140  raeburn  6795: .LC_answer_unknown,
                   6796: .LC_answer_warning {
1.779     bisitz   6797:   background: orange;
                   6798:   color: black;
1.795     www      6799:   padding: 6px;
1.777     tempelho 6800: }
1.795     www      6801: 
1.529     albertel 6802: span.LC_prior_numerical,
                   6803: span.LC_prior_string,
                   6804: span.LC_prior_custom,
                   6805: span.LC_prior_reaction,
                   6806: span.LC_prior_math {
1.925     bisitz   6807:   font-family: $mono;
1.523     albertel 6808:   white-space: pre;
                   6809: }
                   6810: 
1.525     albertel 6811: span.LC_prior_string {
1.925     bisitz   6812:   font-family: $mono;
1.525     albertel 6813:   white-space: pre;
                   6814: }
                   6815: 
1.523     albertel 6816: table.LC_prior_option {
                   6817:   width: 100%;
                   6818:   border-collapse: collapse;
                   6819: }
1.795     www      6820: 
1.911     bisitz   6821: table.LC_prior_rank,
1.795     www      6822: table.LC_prior_match {
1.528     albertel 6823:   border-collapse: collapse;
                   6824: }
1.795     www      6825: 
1.528     albertel 6826: table.LC_prior_option tr td,
                   6827: table.LC_prior_rank tr td,
                   6828: table.LC_prior_match tr td {
1.524     albertel 6829:   border: 1px solid #000000;
1.515     albertel 6830: }
                   6831: 
1.855     bisitz   6832: .LC_nobreak {
1.544     albertel 6833:   white-space: nowrap;
1.519     raeburn  6834: }
                   6835: 
1.576     raeburn  6836: span.LC_cusr_emph {
                   6837:   font-style: italic;
                   6838: }
                   6839: 
1.633     raeburn  6840: span.LC_cusr_subheading {
                   6841:   font-weight: normal;
                   6842:   font-size: 85%;
                   6843: }
                   6844: 
1.861     bisitz   6845: div.LC_docs_entry_move {
1.859     bisitz   6846:   border: 1px solid #BBBBBB;
1.545     albertel 6847:   background: #DDDDDD;
1.861     bisitz   6848:   width: 22px;
1.859     bisitz   6849:   padding: 1px;
                   6850:   margin: 0;
1.545     albertel 6851: }
                   6852: 
1.861     bisitz   6853: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6854: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6855:   font-size: x-small;
                   6856: }
1.795     www      6857: 
1.861     bisitz   6858: .LC_docs_entry_parameter {
                   6859:   white-space: nowrap;
                   6860: }
                   6861: 
1.544     albertel 6862: .LC_docs_copy {
1.545     albertel 6863:   color: #000099;
1.544     albertel 6864: }
1.795     www      6865: 
1.544     albertel 6866: .LC_docs_cut {
1.545     albertel 6867:   color: #550044;
1.544     albertel 6868: }
1.795     www      6869: 
1.544     albertel 6870: .LC_docs_rename {
1.545     albertel 6871:   color: #009900;
1.544     albertel 6872: }
1.795     www      6873: 
1.544     albertel 6874: .LC_docs_remove {
1.545     albertel 6875:   color: #990000;
                   6876: }
                   6877: 
1.1075.2.134  raeburn  6878: .LC_domprefs_email,
1.547     albertel 6879: .LC_docs_reinit_warn,
                   6880: .LC_docs_ext_edit {
                   6881:   font-size: x-small;
                   6882: }
                   6883: 
1.545     albertel 6884: table.LC_docs_adddocs td,
                   6885: table.LC_docs_adddocs th {
                   6886:   border: 1px solid #BBBBBB;
                   6887:   padding: 4px;
                   6888:   background: #DDDDDD;
1.543     albertel 6889: }
                   6890: 
1.584     albertel 6891: table.LC_sty_begin {
                   6892:   background: #BBFFBB;
                   6893: }
1.795     www      6894: 
1.584     albertel 6895: table.LC_sty_end {
                   6896:   background: #FFBBBB;
                   6897: }
                   6898: 
1.589     raeburn  6899: table.LC_double_column {
1.803     bisitz   6900:   border-width: 0;
1.589     raeburn  6901:   border-collapse: collapse;
                   6902:   width: 100%;
                   6903:   padding: 2px;
                   6904: }
                   6905: 
                   6906: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6907:   top: 2px;
1.589     raeburn  6908:   left: 2px;
                   6909:   width: 47%;
                   6910:   vertical-align: top;
                   6911: }
                   6912: 
                   6913: table.LC_double_column tr td.LC_right_col {
                   6914:   top: 2px;
1.779     bisitz   6915:   right: 2px;
1.589     raeburn  6916:   width: 47%;
                   6917:   vertical-align: top;
                   6918: }
                   6919: 
1.591     raeburn  6920: div.LC_left_float {
                   6921:   float: left;
                   6922:   padding-right: 5%;
1.597     albertel 6923:   padding-bottom: 4px;
1.591     raeburn  6924: }
                   6925: 
                   6926: div.LC_clear_float_header {
1.597     albertel 6927:   padding-bottom: 2px;
1.591     raeburn  6928: }
                   6929: 
                   6930: div.LC_clear_float_footer {
1.597     albertel 6931:   padding-top: 10px;
1.591     raeburn  6932:   clear: both;
                   6933: }
                   6934: 
1.597     albertel 6935: div.LC_grade_show_user {
1.941     bisitz   6936: /*  border-left: 5px solid $sidebg; */
                   6937:   border-top: 5px solid #000000;
                   6938:   margin: 50px 0 0 0;
1.936     bisitz   6939:   padding: 15px 0 5px 10px;
1.597     albertel 6940: }
1.795     www      6941: 
1.936     bisitz   6942: div.LC_grade_show_user_odd_row {
1.941     bisitz   6943: /*  border-left: 5px solid #000000; */
                   6944: }
                   6945: 
                   6946: div.LC_grade_show_user div.LC_Box {
                   6947:   margin-right: 50px;
1.597     albertel 6948: }
                   6949: 
                   6950: div.LC_grade_submissions,
                   6951: div.LC_grade_message_center,
1.936     bisitz   6952: div.LC_grade_info_links {
1.597     albertel 6953:   margin: 5px;
                   6954:   width: 99%;
                   6955:   background: #FFFFFF;
                   6956: }
1.795     www      6957: 
1.597     albertel 6958: div.LC_grade_submissions_header,
1.936     bisitz   6959: div.LC_grade_message_center_header {
1.705     tempelho 6960:   font-weight: bold;
                   6961:   font-size: large;
1.597     albertel 6962: }
1.795     www      6963: 
1.597     albertel 6964: div.LC_grade_submissions_body,
1.936     bisitz   6965: div.LC_grade_message_center_body {
1.597     albertel 6966:   border: 1px solid black;
                   6967:   width: 99%;
                   6968:   background: #FFFFFF;
                   6969: }
1.795     www      6970: 
1.613     albertel 6971: table.LC_scantron_action {
                   6972:   width: 100%;
                   6973: }
1.795     www      6974: 
1.613     albertel 6975: table.LC_scantron_action tr th {
1.698     harmsja  6976:   font-weight:bold;
                   6977:   font-style:normal;
1.613     albertel 6978: }
1.795     www      6979: 
1.779     bisitz   6980: .LC_edit_problem_header,
1.614     albertel 6981: div.LC_edit_problem_footer {
1.705     tempelho 6982:   font-weight: normal;
                   6983:   font-size:  medium;
1.602     albertel 6984:   margin: 2px;
1.1060    bisitz   6985:   background-color: $sidebg;
1.600     albertel 6986: }
1.795     www      6987: 
1.600     albertel 6988: div.LC_edit_problem_header,
1.602     albertel 6989: div.LC_edit_problem_header div,
1.614     albertel 6990: div.LC_edit_problem_footer,
                   6991: div.LC_edit_problem_footer div,
1.602     albertel 6992: div.LC_edit_problem_editxml_header,
                   6993: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  6994:   z-index: 100;
1.600     albertel 6995: }
1.795     www      6996: 
1.600     albertel 6997: div.LC_edit_problem_header_title {
1.705     tempelho 6998:   font-weight: bold;
                   6999:   font-size: larger;
1.602     albertel 7000:   background: $tabbg;
                   7001:   padding: 3px;
1.1060    bisitz   7002:   margin: 0 0 5px 0;
1.602     albertel 7003: }
1.795     www      7004: 
1.602     albertel 7005: table.LC_edit_problem_header_title {
                   7006:   width: 100%;
1.600     albertel 7007:   background: $tabbg;
1.602     albertel 7008: }
                   7009: 
1.1075.2.112  raeburn  7010: div.LC_edit_actionbar {
                   7011:     background-color: $sidebg;
                   7012:     margin: 0;
                   7013:     padding: 0;
                   7014:     line-height: 200%;
1.602     albertel 7015: }
1.795     www      7016: 
1.1075.2.112  raeburn  7017: div.LC_edit_actionbar div{
                   7018:     padding: 0;
                   7019:     margin: 0;
                   7020:     display: inline-block;
1.600     albertel 7021: }
1.795     www      7022: 
1.1075.2.34  raeburn  7023: .LC_edit_opt {
                   7024:   padding-left: 1em;
                   7025:   white-space: nowrap;
                   7026: }
                   7027: 
1.1075.2.57  raeburn  7028: .LC_edit_problem_latexhelper{
                   7029:     text-align: right;
                   7030: }
                   7031: 
                   7032: #LC_edit_problem_colorful div{
                   7033:     margin-left: 40px;
                   7034: }
                   7035: 
1.1075.2.112  raeburn  7036: #LC_edit_problem_codemirror div{
                   7037:     margin-left: 0px;
                   7038: }
                   7039: 
1.911     bisitz   7040: img.stift {
1.803     bisitz   7041:   border-width: 0;
                   7042:   vertical-align: middle;
1.677     riegler  7043: }
1.680     riegler  7044: 
1.923     bisitz   7045: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7046:   vertical-align: top;
1.777     tempelho 7047: }
1.795     www      7048: 
1.716     raeburn  7049: div.LC_createcourse {
1.911     bisitz   7050:   margin: 10px 10px 10px 10px;
1.716     raeburn  7051: }
                   7052: 
1.917     raeburn  7053: .LC_dccid {
1.1075.2.38  raeburn  7054:   float: right;
1.917     raeburn  7055:   margin: 0.2em 0 0 0;
                   7056:   padding: 0;
                   7057:   font-size: 90%;
                   7058:   display:none;
                   7059: }
                   7060: 
1.897     wenzelju 7061: ol.LC_primary_menu a:hover,
1.721     harmsja  7062: ol#LC_MenuBreadcrumbs a:hover,
                   7063: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7064: ul#LC_secondary_menu a:hover,
1.721     harmsja  7065: .LC_FormSectionClearButton input:hover
1.795     www      7066: ul.LC_TabContent   li:hover a {
1.952     onken    7067:   color:$button_hover;
1.911     bisitz   7068:   text-decoration:none;
1.693     droeschl 7069: }
                   7070: 
1.779     bisitz   7071: h1 {
1.911     bisitz   7072:   padding: 0;
                   7073:   line-height:130%;
1.693     droeschl 7074: }
1.698     harmsja  7075: 
1.911     bisitz   7076: h2,
                   7077: h3,
                   7078: h4,
                   7079: h5,
                   7080: h6 {
                   7081:   margin: 5px 0 5px 0;
                   7082:   padding: 0;
                   7083:   line-height:130%;
1.693     droeschl 7084: }
1.795     www      7085: 
                   7086: .LC_hcell {
1.911     bisitz   7087:   padding:3px 15px 3px 15px;
                   7088:   margin: 0;
                   7089:   background-color:$tabbg;
                   7090:   color:$fontmenu;
                   7091:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7092: }
1.795     www      7093: 
1.840     bisitz   7094: .LC_Box > .LC_hcell {
1.911     bisitz   7095:   margin: 0 -10px 10px -10px;
1.835     bisitz   7096: }
                   7097: 
1.721     harmsja  7098: .LC_noBorder {
1.911     bisitz   7099:   border: 0;
1.698     harmsja  7100: }
1.693     droeschl 7101: 
1.721     harmsja  7102: .LC_FormSectionClearButton input {
1.911     bisitz   7103:   background-color:transparent;
                   7104:   border: none;
                   7105:   cursor:pointer;
                   7106:   text-decoration:underline;
1.693     droeschl 7107: }
1.763     bisitz   7108: 
                   7109: .LC_help_open_topic {
1.911     bisitz   7110:   color: #FFFFFF;
                   7111:   background-color: #EEEEFF;
                   7112:   margin: 1px;
                   7113:   padding: 4px;
                   7114:   border: 1px solid #000033;
                   7115:   white-space: nowrap;
                   7116:   /* vertical-align: middle; */
1.759     neumanie 7117: }
1.693     droeschl 7118: 
1.911     bisitz   7119: dl,
                   7120: ul,
                   7121: div,
                   7122: fieldset {
                   7123:   margin: 10px 10px 10px 0;
                   7124:   /* overflow: hidden; */
1.693     droeschl 7125: }
1.795     www      7126: 
1.1075.2.90  raeburn  7127: article.geogebraweb div {
                   7128:     margin: 0;
                   7129: }
                   7130: 
1.838     bisitz   7131: fieldset > legend {
1.911     bisitz   7132:   font-weight: bold;
                   7133:   padding: 0 5px 0 5px;
1.838     bisitz   7134: }
                   7135: 
1.813     bisitz   7136: #LC_nav_bar {
1.911     bisitz   7137:   float: left;
1.995     raeburn  7138:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7139:   margin: 0 0 2px 0;
1.807     droeschl 7140: }
                   7141: 
1.916     droeschl 7142: #LC_realm {
                   7143:   margin: 0.2em 0 0 0;
                   7144:   padding: 0;
                   7145:   font-weight: bold;
                   7146:   text-align: center;
1.995     raeburn  7147:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7148: }
                   7149: 
1.911     bisitz   7150: #LC_nav_bar em {
                   7151:   font-weight: bold;
                   7152:   font-style: normal;
1.807     droeschl 7153: }
                   7154: 
1.897     wenzelju 7155: ol.LC_primary_menu {
1.934     droeschl 7156:   margin: 0;
1.1075.2.2  raeburn  7157:   padding: 0;
1.807     droeschl 7158: }
                   7159: 
1.852     droeschl 7160: ol#LC_PathBreadcrumbs {
1.911     bisitz   7161:   margin: 0;
1.693     droeschl 7162: }
                   7163: 
1.897     wenzelju 7164: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7165:   color: RGB(80, 80, 80);
                   7166:   vertical-align: middle;
                   7167:   text-align: left;
                   7168:   list-style: none;
1.1075.2.112  raeburn  7169:   position: relative;
1.1075.2.2  raeburn  7170:   float: left;
1.1075.2.112  raeburn  7171:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7172:   line-height: 1.5em;
1.1075.2.2  raeburn  7173: }
                   7174: 
1.1075.2.113  raeburn  7175: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7176: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7177:   display: block;
                   7178:   margin: 0;
                   7179:   padding: 0 5px 0 10px;
                   7180:   text-decoration: none;
                   7181: }
                   7182: 
1.1075.2.112  raeburn  7183: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7184:   display: inline-block;
                   7185:   width: 95%;
                   7186:   text-align: left;
                   7187: }
                   7188: 
                   7189: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7190:   display: inline-block;
                   7191:   width: 5%;
                   7192:   float: right;
                   7193:   text-align: right;
                   7194:   font-size: 70%;
                   7195: }
                   7196: 
                   7197: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7198:   display: none;
1.1075.2.112  raeburn  7199:   width: 15em;
1.1075.2.2  raeburn  7200:   background-color: $data_table_light;
1.1075.2.112  raeburn  7201:   position: absolute;
                   7202:   top: 100%;
                   7203: }
                   7204: 
                   7205: ol.LC_primary_menu ul ul {
                   7206:   left: 100%;
                   7207:   top: 0;
1.1075.2.2  raeburn  7208: }
                   7209: 
1.1075.2.112  raeburn  7210: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7211:   display: block;
                   7212:   position: absolute;
                   7213:   margin: 0;
                   7214:   padding: 0;
1.1075.2.5  raeburn  7215:   z-index: 2;
1.1075.2.2  raeburn  7216: }
                   7217: 
                   7218: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7219: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7220:   font-size: 90%;
1.911     bisitz   7221:   vertical-align: top;
1.1075.2.2  raeburn  7222:   float: none;
1.1075.2.5  raeburn  7223:   border-left: 1px solid black;
                   7224:   border-right: 1px solid black;
1.1075.2.112  raeburn  7225: /* A dark bottom border to visualize different menu options;
                   7226: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7227:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7228: }
                   7229: 
1.1075.2.112  raeburn  7230: ol.LC_primary_menu li li p:hover {
                   7231:   color:$button_hover;
                   7232:   text-decoration:none;
                   7233:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7234: }
                   7235: 
                   7236: ol.LC_primary_menu li li a:hover {
                   7237:    color:$button_hover;
                   7238:    background-color:$data_table_dark;
1.693     droeschl 7239: }
                   7240: 
1.1075.2.112  raeburn  7241: /* Font-size equal to the size of the predecessors*/
                   7242: ol.LC_primary_menu li:hover li li {
                   7243:   font-size: 100%;
                   7244: }
                   7245: 
1.897     wenzelju 7246: ol.LC_primary_menu li img {
1.911     bisitz   7247:   vertical-align: bottom;
1.934     droeschl 7248:   height: 1.1em;
1.1075.2.3  raeburn  7249:   margin: 0.2em 0 0 0;
1.693     droeschl 7250: }
                   7251: 
1.897     wenzelju 7252: ol.LC_primary_menu a {
1.911     bisitz   7253:   color: RGB(80, 80, 80);
                   7254:   text-decoration: none;
1.693     droeschl 7255: }
1.795     www      7256: 
1.949     droeschl 7257: ol.LC_primary_menu a.LC_new_message {
                   7258:   font-weight:bold;
                   7259:   color: darkred;
                   7260: }
                   7261: 
1.975     raeburn  7262: ol.LC_docs_parameters {
                   7263:   margin-left: 0;
                   7264:   padding: 0;
                   7265:   list-style: none;
                   7266: }
                   7267: 
                   7268: ol.LC_docs_parameters li {
                   7269:   margin: 0;
                   7270:   padding-right: 20px;
                   7271:   display: inline;
                   7272: }
                   7273: 
1.976     raeburn  7274: ol.LC_docs_parameters li:before {
                   7275:   content: "\\002022 \\0020";
                   7276: }
                   7277: 
                   7278: li.LC_docs_parameters_title {
                   7279:   font-weight: bold;
                   7280: }
                   7281: 
                   7282: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7283:   content: "";
                   7284: }
                   7285: 
1.897     wenzelju 7286: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7287:   clear: right;
1.911     bisitz   7288:   color: $fontmenu;
                   7289:   background: $tabbg;
                   7290:   list-style: none;
                   7291:   padding: 0;
                   7292:   margin: 0;
                   7293:   width: 100%;
1.995     raeburn  7294:   text-align: left;
1.1075.2.4  raeburn  7295:   float: left;
1.808     droeschl 7296: }
                   7297: 
1.897     wenzelju 7298: ul#LC_secondary_menu li {
1.911     bisitz   7299:   font-weight: bold;
                   7300:   line-height: 1.8em;
                   7301:   border-right: 1px solid black;
1.1075.2.4  raeburn  7302:   float: left;
                   7303: }
                   7304: 
                   7305: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7306:   background-color: $data_table_light;
                   7307: }
                   7308: 
                   7309: ul#LC_secondary_menu li a {
                   7310:   padding: 0 0.8em;
                   7311: }
                   7312: 
                   7313: ul#LC_secondary_menu li ul {
                   7314:   display: none;
                   7315: }
                   7316: 
                   7317: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7318:   display: block;
                   7319:   position: absolute;
                   7320:   margin: 0;
                   7321:   padding: 0;
                   7322:   list-style:none;
                   7323:   float: none;
                   7324:   background-color: $data_table_light;
1.1075.2.5  raeburn  7325:   z-index: 2;
1.1075.2.10  raeburn  7326:   margin-left: -1px;
1.1075.2.4  raeburn  7327: }
                   7328: 
                   7329: ul#LC_secondary_menu li ul li {
                   7330:   font-size: 90%;
                   7331:   vertical-align: top;
                   7332:   border-left: 1px solid black;
                   7333:   border-right: 1px solid black;
1.1075.2.33  raeburn  7334:   background-color: $data_table_light;
1.1075.2.4  raeburn  7335:   list-style:none;
                   7336:   float: none;
                   7337: }
                   7338: 
                   7339: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7340:   background-color: $data_table_dark;
1.807     droeschl 7341: }
                   7342: 
1.847     tempelho 7343: ul.LC_TabContent {
1.911     bisitz   7344:   display:block;
                   7345:   background: $sidebg;
                   7346:   border-bottom: solid 1px $lg_border_color;
                   7347:   list-style:none;
1.1020    raeburn  7348:   margin: -1px -10px 0 -10px;
1.911     bisitz   7349:   padding: 0;
1.693     droeschl 7350: }
                   7351: 
1.795     www      7352: ul.LC_TabContent li,
                   7353: ul.LC_TabContentBigger li {
1.911     bisitz   7354:   float:left;
1.741     harmsja  7355: }
1.795     www      7356: 
1.897     wenzelju 7357: ul#LC_secondary_menu li a {
1.911     bisitz   7358:   color: $fontmenu;
                   7359:   text-decoration: none;
1.693     droeschl 7360: }
1.795     www      7361: 
1.721     harmsja  7362: ul.LC_TabContent {
1.952     onken    7363:   min-height:20px;
1.721     harmsja  7364: }
1.795     www      7365: 
                   7366: ul.LC_TabContent li {
1.911     bisitz   7367:   vertical-align:middle;
1.959     onken    7368:   padding: 0 16px 0 10px;
1.911     bisitz   7369:   background-color:$tabbg;
                   7370:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7371:   border-left: solid 1px $font;
1.721     harmsja  7372: }
1.795     www      7373: 
1.847     tempelho 7374: ul.LC_TabContent .right {
1.911     bisitz   7375:   float:right;
1.847     tempelho 7376: }
                   7377: 
1.911     bisitz   7378: ul.LC_TabContent li a,
                   7379: ul.LC_TabContent li {
                   7380:   color:rgb(47,47,47);
                   7381:   text-decoration:none;
                   7382:   font-size:95%;
                   7383:   font-weight:bold;
1.952     onken    7384:   min-height:20px;
                   7385: }
                   7386: 
1.959     onken    7387: ul.LC_TabContent li a:hover,
                   7388: ul.LC_TabContent li a:focus {
1.952     onken    7389:   color: $button_hover;
1.959     onken    7390:   background:none;
                   7391:   outline:none;
1.952     onken    7392: }
                   7393: 
                   7394: ul.LC_TabContent li:hover {
                   7395:   color: $button_hover;
                   7396:   cursor:pointer;
1.721     harmsja  7397: }
1.795     www      7398: 
1.911     bisitz   7399: ul.LC_TabContent li.active {
1.952     onken    7400:   color: $font;
1.911     bisitz   7401:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7402:   border-bottom:solid 1px #FFFFFF;
                   7403:   cursor: default;
1.744     ehlerst  7404: }
1.795     www      7405: 
1.959     onken    7406: ul.LC_TabContent li.active a {
                   7407:   color:$font;
                   7408:   background:#FFFFFF;
                   7409:   outline: none;
                   7410: }
1.1047    raeburn  7411: 
                   7412: ul.LC_TabContent li.goback {
                   7413:   float: left;
                   7414:   border-left: none;
                   7415: }
                   7416: 
1.870     tempelho 7417: #maincoursedoc {
1.911     bisitz   7418:   clear:both;
1.870     tempelho 7419: }
                   7420: 
                   7421: ul.LC_TabContentBigger {
1.911     bisitz   7422:   display:block;
                   7423:   list-style:none;
                   7424:   padding: 0;
1.870     tempelho 7425: }
                   7426: 
1.795     www      7427: ul.LC_TabContentBigger li {
1.911     bisitz   7428:   vertical-align:bottom;
                   7429:   height: 30px;
                   7430:   font-size:110%;
                   7431:   font-weight:bold;
                   7432:   color: #737373;
1.841     tempelho 7433: }
                   7434: 
1.957     onken    7435: ul.LC_TabContentBigger li.active {
                   7436:   position: relative;
                   7437:   top: 1px;
                   7438: }
                   7439: 
1.870     tempelho 7440: ul.LC_TabContentBigger li a {
1.911     bisitz   7441:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7442:   height: 30px;
                   7443:   line-height: 30px;
                   7444:   text-align: center;
                   7445:   display: block;
                   7446:   text-decoration: none;
1.958     onken    7447:   outline: none;  
1.741     harmsja  7448: }
1.795     www      7449: 
1.870     tempelho 7450: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7451:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7452:   color:$font;
1.744     ehlerst  7453: }
1.795     www      7454: 
1.870     tempelho 7455: ul.LC_TabContentBigger li b {
1.911     bisitz   7456:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7457:   display: block;
                   7458:   float: left;
                   7459:   padding: 0 30px;
1.957     onken    7460:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7461: }
                   7462: 
1.956     onken    7463: ul.LC_TabContentBigger li:hover b {
                   7464:   color:$button_hover;
                   7465: }
                   7466: 
1.870     tempelho 7467: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7468:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7469:   color:$font;
1.957     onken    7470:   border: 0;
1.741     harmsja  7471: }
1.693     droeschl 7472: 
1.870     tempelho 7473: 
1.862     bisitz   7474: ul.LC_CourseBreadcrumbs {
                   7475:   background: $sidebg;
1.1020    raeburn  7476:   height: 2em;
1.862     bisitz   7477:   padding-left: 10px;
1.1020    raeburn  7478:   margin: 0;
1.862     bisitz   7479:   list-style-position: inside;
                   7480: }
                   7481: 
1.911     bisitz   7482: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7483: ol#LC_PathBreadcrumbs {
1.911     bisitz   7484:   padding-left: 10px;
                   7485:   margin: 0;
1.933     droeschl 7486:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7487: }
                   7488: 
1.911     bisitz   7489: ol#LC_MenuBreadcrumbs li,
                   7490: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7491: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7492:   display: inline;
1.933     droeschl 7493:   white-space: normal;  
1.693     droeschl 7494: }
                   7495: 
1.823     bisitz   7496: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7497: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7498:   text-decoration: none;
                   7499:   font-size:90%;
1.693     droeschl 7500: }
1.795     www      7501: 
1.969     droeschl 7502: ol#LC_MenuBreadcrumbs h1 {
                   7503:   display: inline;
                   7504:   font-size: 90%;
                   7505:   line-height: 2.5em;
                   7506:   margin: 0;
                   7507:   padding: 0;
                   7508: }
                   7509: 
1.795     www      7510: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7511:   text-decoration:none;
                   7512:   font-size:100%;
                   7513:   font-weight:bold;
1.693     droeschl 7514: }
1.795     www      7515: 
1.840     bisitz   7516: .LC_Box {
1.911     bisitz   7517:   border: solid 1px $lg_border_color;
                   7518:   padding: 0 10px 10px 10px;
1.746     neumanie 7519: }
1.795     www      7520: 
1.1020    raeburn  7521: .LC_DocsBox {
                   7522:   border: solid 1px $lg_border_color;
                   7523:   padding: 0 0 10px 10px;
                   7524: }
                   7525: 
1.795     www      7526: .LC_AboutMe_Image {
1.911     bisitz   7527:   float:left;
                   7528:   margin-right:10px;
1.747     neumanie 7529: }
1.795     www      7530: 
                   7531: .LC_Clear_AboutMe_Image {
1.911     bisitz   7532:   clear:left;
1.747     neumanie 7533: }
1.795     www      7534: 
1.721     harmsja  7535: dl.LC_ListStyleClean dt {
1.911     bisitz   7536:   padding-right: 5px;
                   7537:   display: table-header-group;
1.693     droeschl 7538: }
                   7539: 
1.721     harmsja  7540: dl.LC_ListStyleClean dd {
1.911     bisitz   7541:   display: table-row;
1.693     droeschl 7542: }
                   7543: 
1.721     harmsja  7544: .LC_ListStyleClean,
                   7545: .LC_ListStyleSimple,
                   7546: .LC_ListStyleNormal,
1.795     www      7547: .LC_ListStyleSpecial {
1.911     bisitz   7548:   /* display:block; */
                   7549:   list-style-position: inside;
                   7550:   list-style-type: none;
                   7551:   overflow: hidden;
                   7552:   padding: 0;
1.693     droeschl 7553: }
                   7554: 
1.721     harmsja  7555: .LC_ListStyleSimple li,
                   7556: .LC_ListStyleSimple dd,
                   7557: .LC_ListStyleNormal li,
                   7558: .LC_ListStyleNormal dd,
                   7559: .LC_ListStyleSpecial li,
1.795     www      7560: .LC_ListStyleSpecial dd {
1.911     bisitz   7561:   margin: 0;
                   7562:   padding: 5px 5px 5px 10px;
                   7563:   clear: both;
1.693     droeschl 7564: }
                   7565: 
1.721     harmsja  7566: .LC_ListStyleClean li,
                   7567: .LC_ListStyleClean dd {
1.911     bisitz   7568:   padding-top: 0;
                   7569:   padding-bottom: 0;
1.693     droeschl 7570: }
                   7571: 
1.721     harmsja  7572: .LC_ListStyleSimple dd,
1.795     www      7573: .LC_ListStyleSimple li {
1.911     bisitz   7574:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7575: }
                   7576: 
1.721     harmsja  7577: .LC_ListStyleSpecial li,
                   7578: .LC_ListStyleSpecial dd {
1.911     bisitz   7579:   list-style-type: none;
                   7580:   background-color: RGB(220, 220, 220);
                   7581:   margin-bottom: 4px;
1.693     droeschl 7582: }
                   7583: 
1.721     harmsja  7584: table.LC_SimpleTable {
1.911     bisitz   7585:   margin:5px;
                   7586:   border:solid 1px $lg_border_color;
1.795     www      7587: }
1.693     droeschl 7588: 
1.721     harmsja  7589: table.LC_SimpleTable tr {
1.911     bisitz   7590:   padding: 0;
                   7591:   border:solid 1px $lg_border_color;
1.693     droeschl 7592: }
1.795     www      7593: 
                   7594: table.LC_SimpleTable thead {
1.911     bisitz   7595:   background:rgb(220,220,220);
1.693     droeschl 7596: }
                   7597: 
1.721     harmsja  7598: div.LC_columnSection {
1.911     bisitz   7599:   display: block;
                   7600:   clear: both;
                   7601:   overflow: hidden;
                   7602:   margin: 0;
1.693     droeschl 7603: }
                   7604: 
1.721     harmsja  7605: div.LC_columnSection>* {
1.911     bisitz   7606:   float: left;
                   7607:   margin: 10px 20px 10px 0;
                   7608:   overflow:hidden;
1.693     droeschl 7609: }
1.721     harmsja  7610: 
1.795     www      7611: table em {
1.911     bisitz   7612:   font-weight: bold;
                   7613:   font-style: normal;
1.748     schulted 7614: }
1.795     www      7615: 
1.779     bisitz   7616: table.LC_tableBrowseRes,
1.795     www      7617: table.LC_tableOfContent {
1.911     bisitz   7618:   border:none;
                   7619:   border-spacing: 1px;
                   7620:   padding: 3px;
                   7621:   background-color: #FFFFFF;
                   7622:   font-size: 90%;
1.753     droeschl 7623: }
1.789     droeschl 7624: 
1.911     bisitz   7625: table.LC_tableOfContent {
                   7626:   border-collapse: collapse;
1.789     droeschl 7627: }
                   7628: 
1.771     droeschl 7629: table.LC_tableBrowseRes a,
1.768     schulted 7630: table.LC_tableOfContent a {
1.911     bisitz   7631:   background-color: transparent;
                   7632:   text-decoration: none;
1.753     droeschl 7633: }
                   7634: 
1.795     www      7635: table.LC_tableOfContent img {
1.911     bisitz   7636:   border: none;
                   7637:   height: 1.3em;
                   7638:   vertical-align: text-bottom;
                   7639:   margin-right: 0.3em;
1.753     droeschl 7640: }
1.757     schulted 7641: 
1.795     www      7642: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7643:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7644: }
                   7645: 
1.795     www      7646: a#LC_content_toolbar_everything {
1.911     bisitz   7647:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7648: }
                   7649: 
1.795     www      7650: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7651:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7652: }
                   7653: 
1.795     www      7654: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7655:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7656: }
                   7657: 
1.795     www      7658: a#LC_content_toolbar_changefolder {
1.911     bisitz   7659:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7660: }
                   7661: 
1.795     www      7662: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7663:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7664: }
                   7665: 
1.1043    raeburn  7666: a#LC_content_toolbar_edittoplevel {
                   7667:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7668: }
                   7669: 
1.795     www      7670: ul#LC_toolbar li a:hover {
1.911     bisitz   7671:   background-position: bottom center;
1.757     schulted 7672: }
                   7673: 
1.795     www      7674: ul#LC_toolbar {
1.911     bisitz   7675:   padding: 0;
                   7676:   margin: 2px;
                   7677:   list-style:none;
                   7678:   position:relative;
                   7679:   background-color:white;
1.1075.2.9  raeburn  7680:   overflow: auto;
1.757     schulted 7681: }
                   7682: 
1.795     www      7683: ul#LC_toolbar li {
1.911     bisitz   7684:   border:1px solid white;
                   7685:   padding: 0;
                   7686:   margin: 0;
                   7687:   float: left;
                   7688:   display:inline;
                   7689:   vertical-align:middle;
1.1075.2.9  raeburn  7690:   white-space: nowrap;
1.911     bisitz   7691: }
1.757     schulted 7692: 
1.783     amueller 7693: 
1.795     www      7694: a.LC_toolbarItem {
1.911     bisitz   7695:   display:block;
                   7696:   padding: 0;
                   7697:   margin: 0;
                   7698:   height: 32px;
                   7699:   width: 32px;
                   7700:   color:white;
                   7701:   border: none;
                   7702:   background-repeat:no-repeat;
                   7703:   background-color:transparent;
1.757     schulted 7704: }
                   7705: 
1.915     droeschl 7706: ul.LC_funclist {
                   7707:     margin: 0;
                   7708:     padding: 0.5em 1em 0.5em 0;
                   7709: }
                   7710: 
1.933     droeschl 7711: ul.LC_funclist > li:first-child {
                   7712:     font-weight:bold; 
                   7713:     margin-left:0.8em;
                   7714: }
                   7715: 
1.915     droeschl 7716: ul.LC_funclist + ul.LC_funclist {
                   7717:     /* 
                   7718:        left border as a seperator if we have more than
                   7719:        one list 
                   7720:     */
                   7721:     border-left: 1px solid $sidebg;
                   7722:     /* 
                   7723:        this hides the left border behind the border of the 
                   7724:        outer box if element is wrapped to the next 'line' 
                   7725:     */
                   7726:     margin-left: -1px;
                   7727: }
                   7728: 
1.843     bisitz   7729: ul.LC_funclist li {
1.915     droeschl 7730:   display: inline;
1.782     bisitz   7731:   white-space: nowrap;
1.915     droeschl 7732:   margin: 0 0 0 25px;
                   7733:   line-height: 150%;
1.782     bisitz   7734: }
                   7735: 
1.974     wenzelju 7736: .LC_hidden {
                   7737:   display: none;
                   7738: }
                   7739: 
1.1030    www      7740: .LCmodal-overlay {
                   7741: 		position:fixed;
                   7742: 		top:0;
                   7743: 		right:0;
                   7744: 		bottom:0;
                   7745: 		left:0;
                   7746: 		height:100%;
                   7747: 		width:100%;
                   7748: 		margin:0;
                   7749: 		padding:0;
                   7750: 		background:#999;
                   7751: 		opacity:.75;
                   7752: 		filter: alpha(opacity=75);
                   7753: 		-moz-opacity: 0.75;
                   7754: 		z-index:101;
                   7755: }
                   7756: 
                   7757: * html .LCmodal-overlay {   
                   7758: 		position: absolute;
                   7759: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7760: }
                   7761: 
                   7762: .LCmodal-window {
                   7763: 		position:fixed;
                   7764: 		top:50%;
                   7765: 		left:50%;
                   7766: 		margin:0;
                   7767: 		padding:0;
                   7768: 		z-index:102;
                   7769: 	}
                   7770: 
                   7771: * html .LCmodal-window {
                   7772: 		position:absolute;
                   7773: }
                   7774: 
                   7775: .LCclose-window {
                   7776: 		position:absolute;
                   7777: 		width:32px;
                   7778: 		height:32px;
                   7779: 		right:8px;
                   7780: 		top:8px;
                   7781: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7782: 		text-indent:-99999px;
                   7783: 		overflow:hidden;
                   7784: 		cursor:pointer;
                   7785: }
                   7786: 
1.1075.2.141  raeburn  7787: pre.LC_wordwrap {
                   7788:   white-space: pre-wrap;
                   7789:   white-space: -moz-pre-wrap;
                   7790:   white-space: -pre-wrap;
                   7791:   white-space: -o-pre-wrap;
                   7792:   word-wrap: break-word;
                   7793: }
                   7794: 
1.1075.2.17  raeburn  7795: /*
                   7796:   styles used by TTH when "Default set of options to pass to tth/m
                   7797:   when converting TeX" in course settings has been set
                   7798: 
                   7799:   option passed: -t
                   7800: 
                   7801: */
                   7802: 
                   7803: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7804: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7805: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7806: td div.norm {line-height:normal;}
                   7807: 
                   7808: /*
                   7809:   option passed -y3
                   7810: */
                   7811: 
                   7812: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7813: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7814: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7815: 
1.1075.2.121  raeburn  7816: #LC_minitab_header {
                   7817:   float:left;
                   7818:   width:100%;
                   7819:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   7820:   font-size:93%;
                   7821:   line-height:normal;
                   7822:   margin: 0.5em 0 0.5em 0;
                   7823: }
                   7824: #LC_minitab_header ul {
                   7825:   margin:0;
                   7826:   padding:10px 10px 0;
                   7827:   list-style:none;
                   7828: }
                   7829: #LC_minitab_header li {
                   7830:   float:left;
                   7831:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   7832:   margin:0;
                   7833:   padding:0 0 0 9px;
                   7834: }
                   7835: #LC_minitab_header a {
                   7836:   display:block;
                   7837:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   7838:   padding:5px 15px 4px 6px;
                   7839: }
                   7840: #LC_minitab_header #LC_current_minitab {
                   7841:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   7842: }
                   7843: #LC_minitab_header #LC_current_minitab a {
                   7844:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   7845:   padding-bottom:5px;
                   7846: }
                   7847: 
                   7848: 
1.343     albertel 7849: END
                   7850: }
                   7851: 
1.306     albertel 7852: =pod
                   7853: 
                   7854: =item * &headtag()
                   7855: 
                   7856: Returns a uniform footer for LON-CAPA web pages.
                   7857: 
1.307     albertel 7858: Inputs: $title - optional title for the head
                   7859:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7860:         $args - optional arguments
1.319     albertel 7861:             force_register - if is true call registerurl so the remote is 
                   7862:                              informed
1.415     albertel 7863:             redirect       -> array ref of
                   7864:                                    1- seconds before redirect occurs
                   7865:                                    2- url to redirect to
                   7866:                                    3- whether the side effect should occur
1.315     albertel 7867:                            (side effect of setting 
                   7868:                                $env{'internal.head.redirect'} to the url 
                   7869:                                redirected too)
1.352     albertel 7870:             domain         -> force to color decorate a page for a specific
                   7871:                                domain
                   7872:             function       -> force usage of a specific rolish color scheme
                   7873:             bgcolor        -> override the default page bgcolor
1.460     albertel 7874:             no_auto_mt_title
                   7875:                            -> prevent &mt()ing the title arg
1.464     albertel 7876: 
1.306     albertel 7877: =cut
                   7878: 
                   7879: sub headtag {
1.313     albertel 7880:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7881:     
1.363     albertel 7882:     my $function = $args->{'function'} || &get_users_function();
                   7883:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7884:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7885:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7886:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7887: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7888: 		   #time(),
1.418     albertel 7889: 		   $env{'environment.color.timestamp'},
1.363     albertel 7890: 		   $function,$domain,$bgcolor);
                   7891: 
1.369     www      7892:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7893: 
1.308     albertel 7894:     my $result =
                   7895: 	'<head>'.
1.1075.2.56  raeburn  7896: 	&font_settings($args);
1.319     albertel 7897: 
1.1075.2.72  raeburn  7898:     my $inhibitprint;
                   7899:     if ($args->{'print_suppress'}) {
                   7900:         $inhibitprint = &print_suppression();
                   7901:     }
1.1064    raeburn  7902: 
1.461     albertel 7903:     if (!$args->{'frameset'}) {
                   7904: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7905:     }
1.1075.2.12  raeburn  7906:     if ($args->{'force_register'}) {
                   7907:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7908:     }
1.436     albertel 7909:     if (!$args->{'no_nav_bar'} 
                   7910: 	&& !$args->{'only_body'}
                   7911: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7912: 	$result .= &help_menu_js($httphost);
1.1032    www      7913:         $result.=&modal_window();
1.1038    www      7914:         $result.=&togglebox_script();
1.1034    www      7915:         $result.=&wishlist_window();
1.1041    www      7916:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7917:     } else {
                   7918:         if ($args->{'add_modal'}) {
                   7919:            $result.=&modal_window();
                   7920:         }
                   7921:         if ($args->{'add_wishlist'}) {
                   7922:            $result.=&wishlist_window();
                   7923:         }
1.1038    www      7924:         if ($args->{'add_togglebox'}) {
                   7925:            $result.=&togglebox_script();
                   7926:         }
1.1041    www      7927:         if ($args->{'add_progressbar'}) {
                   7928:            $result.=&LCprogressbarUpdate_script();
                   7929:         }
1.436     albertel 7930:     }
1.314     albertel 7931:     if (ref($args->{'redirect'})) {
1.414     albertel 7932: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7933: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7934: 	if (!$inhibit_continue) {
                   7935: 	    $env{'internal.head.redirect'} = $url;
                   7936: 	}
1.313     albertel 7937: 	$result.=<<ADDMETA
                   7938: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7939: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7940: ADDMETA
1.1075.2.89  raeburn  7941:     } else {
                   7942:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7943:             my $requrl = $env{'request.uri'};
                   7944:             if ($requrl eq '') {
                   7945:                 $requrl = $ENV{'REQUEST_URI'};
                   7946:                 $requrl =~ s/\?.+$//;
                   7947:             }
                   7948:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7949:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7950:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7951:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7952:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7953:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7954:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7955:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7956:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7957:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7958:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7959:                                 my $numsec = 5;
                   7960:                                 my $timeout = $numsec * 1000;
                   7961:                                 my ($newurl,$locknum,%locks,$msg);
                   7962:                                 if ($env{'request.role.adv'}) {
                   7963:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7964:                                 }
                   7965:                                 my $disable_submit = 0;
                   7966:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7967:                                     $disable_submit = 1;
                   7968:                                 }
                   7969:                                 if ($locknum) {
                   7970:                                     my @lockinfo = sort(values(%locks));
                   7971:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7972:                                            join(", ",sort(values(%locks)))."\\n".
                   7973:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7974:                                 } else {
                   7975:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7976:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7977:                                     }
                   7978:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7979:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7980:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7981:                                         $newurl .= '&role='.$env{'request.role'};
                   7982:                                     }
                   7983:                                     if ($env{'request.symb'}) {
                   7984:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7985:                                     } else {
                   7986:                                         $newurl .= '&origurl='.$requrl;
                   7987:                                     }
                   7988:                                 }
1.1075.2.98  raeburn  7989:                                 &js_escape(\$msg);
1.1075.2.89  raeburn  7990:                                 $result.=<<OFFLOAD
                   7991: <meta http-equiv="pragma" content="no-cache" />
                   7992: <script type="text/javascript">
1.1075.2.92  raeburn  7993: // <![CDATA[
1.1075.2.89  raeburn  7994: function LC_Offload_Now() {
                   7995:     var dest = "$newurl";
                   7996:     if (dest != '') {
                   7997:         window.location.href="$newurl";
                   7998:     }
                   7999: }
1.1075.2.92  raeburn  8000: \$(document).ready(function () {
                   8001:     window.alert('$msg');
                   8002:     if ($disable_submit) {
1.1075.2.89  raeburn  8003:         \$(".LC_hwk_submit").prop("disabled", true);
                   8004:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  8005:     }
                   8006:     setTimeout('LC_Offload_Now()', $timeout);
                   8007: });
                   8008: // ]]>
1.1075.2.89  raeburn  8009: </script>
                   8010: OFFLOAD
                   8011:                             }
                   8012:                         }
                   8013:                     }
                   8014:                 }
                   8015:             }
                   8016:         }
1.313     albertel 8017:     }
1.306     albertel 8018:     if (!defined($title)) {
                   8019: 	$title = 'The LearningOnline Network with CAPA';
                   8020:     }
1.460     albertel 8021:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8022:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  8023: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8024:     if (!$args->{'frameset'}) {
                   8025:         $result .= ' /';
                   8026:     }
                   8027:     $result .= '>'
1.1064    raeburn  8028:         .$inhibitprint
1.414     albertel 8029: 	.$head_extra;
1.1075.2.108  raeburn  8030:     my $clientmobile;
                   8031:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8032:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8033:     } else {
                   8034:         $clientmobile = $env{'browser.mobile'};
                   8035:     }
                   8036:     if ($clientmobile) {
1.1075.2.42  raeburn  8037:         $result .= '
                   8038: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8039: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8040:     }
1.1075.2.126  raeburn  8041:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8042:     return $result.'</head>';
1.306     albertel 8043: }
                   8044: 
                   8045: =pod
                   8046: 
1.340     albertel 8047: =item * &font_settings()
                   8048: 
                   8049: Returns neccessary <meta> to set the proper encoding
                   8050: 
1.1075.2.56  raeburn  8051: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8052: 
                   8053: =cut
                   8054: 
                   8055: sub font_settings {
1.1075.2.56  raeburn  8056:     my ($args) = @_;
1.340     albertel 8057:     my $headerstring='';
1.1075.2.56  raeburn  8058:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8059:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 8060: 	$headerstring.=
1.1075.2.61  raeburn  8061: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8062:         if (!$args->{'frameset'}) {
                   8063:             $headerstring.= ' /';
                   8064:         }
                   8065:         $headerstring .= '>'."\n";
1.340     albertel 8066:     }
                   8067:     return $headerstring;
                   8068: }
                   8069: 
1.341     albertel 8070: =pod
                   8071: 
1.1064    raeburn  8072: =item * &print_suppression()
                   8073: 
                   8074: In course context returns css which causes the body to be blank when media="print",
                   8075: if printout generation is unavailable for the current resource.
                   8076: 
                   8077: This could be because:
                   8078: 
                   8079: (a) printstartdate is in the future
                   8080: 
                   8081: (b) printenddate is in the past
                   8082: 
                   8083: (c) there is an active exam block with "printout"
                   8084: functionality blocked
                   8085: 
                   8086: Users with pav, pfo or evb privileges are exempt.
                   8087: 
                   8088: Inputs: none
                   8089: 
                   8090: =cut
                   8091: 
                   8092: 
                   8093: sub print_suppression {
                   8094:     my $noprint;
                   8095:     if ($env{'request.course.id'}) {
                   8096:         my $scope = $env{'request.course.id'};
                   8097:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8098:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8099:             return;
                   8100:         }
                   8101:         if ($env{'request.course.sec'} ne '') {
                   8102:             $scope .= "/$env{'request.course.sec'}";
                   8103:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8104:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8105:                 return;
1.1064    raeburn  8106:             }
                   8107:         }
                   8108:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8109:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.73  raeburn  8110:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8111:         if ($blocked) {
                   8112:             my $checkrole = "cm./$cdom/$cnum";
                   8113:             if ($env{'request.course.sec'} ne '') {
                   8114:                 $checkrole .= "/$env{'request.course.sec'}";
                   8115:             }
                   8116:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8117:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8118:                 $noprint = 1;
                   8119:             }
                   8120:         }
                   8121:         unless ($noprint) {
                   8122:             my $symb = &Apache::lonnet::symbread();
                   8123:             if ($symb ne '') {
                   8124:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8125:                 if (ref($navmap)) {
                   8126:                     my $res = $navmap->getBySymb($symb);
                   8127:                     if (ref($res)) {
                   8128:                         if (!$res->resprintable()) {
                   8129:                             $noprint = 1;
                   8130:                         }
                   8131:                     }
                   8132:                 }
                   8133:             }
                   8134:         }
                   8135:         if ($noprint) {
                   8136:             return <<"ENDSTYLE";
                   8137: <style type="text/css" media="print">
                   8138:     body { display:none }
                   8139: </style>
                   8140: ENDSTYLE
                   8141:         }
                   8142:     }
                   8143:     return;
                   8144: }
                   8145: 
                   8146: =pod
                   8147: 
1.341     albertel 8148: =item * &xml_begin()
                   8149: 
                   8150: Returns the needed doctype and <html>
                   8151: 
                   8152: Inputs: none
                   8153: 
                   8154: =cut
                   8155: 
                   8156: sub xml_begin {
1.1075.2.61  raeburn  8157:     my ($is_frameset) = @_;
1.341     albertel 8158:     my $output='';
                   8159: 
                   8160:     if ($env{'browser.mathml'}) {
                   8161: 	$output='<?xml version="1.0"?>'
                   8162:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8163: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8164:             
                   8165: #	    .'<!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">] >'
                   8166: 	    .'<!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">'
                   8167:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8168: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  8169:     } elsif ($is_frameset) {
                   8170:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8171:                 '<html>'."\n";
1.341     albertel 8172:     } else {
1.1075.2.61  raeburn  8173: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8174:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8175:     }
                   8176:     return $output;
                   8177: }
1.340     albertel 8178: 
                   8179: =pod
                   8180: 
1.306     albertel 8181: =item * &start_page()
                   8182: 
                   8183: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8184: 
1.648     raeburn  8185: Inputs:
                   8186: 
                   8187: =over 4
                   8188: 
                   8189: $title - optional title for the page
                   8190: 
                   8191: $head_extra - optional extra HTML to incude inside the <head>
                   8192: 
                   8193: $args - additional optional args supported are:
                   8194: 
                   8195: =over 8
                   8196: 
                   8197:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8198:                                     arg on
1.814     bisitz   8199:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8200:              add_entries    -> additional attributes to add to the  <body>
                   8201:              domain         -> force to color decorate a page for a 
1.317     albertel 8202:                                     specific domain
1.648     raeburn  8203:              function       -> force usage of a specific rolish color
1.317     albertel 8204:                                     scheme
1.648     raeburn  8205:              redirect       -> see &headtag()
                   8206:              bgcolor        -> override the default page bg color
                   8207:              js_ready       -> return a string ready for being used in 
1.317     albertel 8208:                                     a javascript writeln
1.648     raeburn  8209:              html_encode    -> return a string ready for being used in 
1.320     albertel 8210:                                     a html attribute
1.648     raeburn  8211:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8212:                                     $forcereg arg
1.648     raeburn  8213:              frameset       -> if true will start with a <frameset>
1.330     albertel 8214:                                     rather than <body>
1.648     raeburn  8215:              skip_phases    -> hash ref of 
1.338     albertel 8216:                                     head -> skip the <html><head> generation
                   8217:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8218:              no_inline_link -> if true and in remote mode, don't show the
                   8219:                                     'Switch To Inline Menu' link
1.648     raeburn  8220:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8221:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8222:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  8223:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8224:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  8225:              group          -> includes the current group, if page is for a
                   8226:                                specific group
1.1075.2.133  raeburn  8227:              use_absolute   -> for request for external resource or syllabus, this
                   8228:                                will contain https://<hostname> if server uses
                   8229:                                https (as per hosts.tab), but request is for http
                   8230:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8231: 
1.648     raeburn  8232: =back
1.460     albertel 8233: 
1.648     raeburn  8234: =back
1.562     albertel 8235: 
1.306     albertel 8236: =cut
                   8237: 
                   8238: sub start_page {
1.309     albertel 8239:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8240:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8241: 
1.315     albertel 8242:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  8243:     my ($result,@advtools);
1.964     droeschl 8244: 
1.338     albertel 8245:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8246:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8247:     }
                   8248:     
                   8249:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8250: 	if ($args->{'frameset'}) {
                   8251: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8252: 						$args->{'add_entries'});
                   8253: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8254:         } else {
                   8255:             $result .=
                   8256:                 &bodytag($title, 
                   8257:                          $args->{'function'},       $args->{'add_entries'},
                   8258:                          $args->{'only_body'},      $args->{'domain'},
                   8259:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8260:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  8261:                          $args,                     \@advtools);
1.831     bisitz   8262:         }
1.330     albertel 8263:     }
1.338     albertel 8264: 
1.315     albertel 8265:     if ($args->{'js_ready'}) {
1.713     kaisler  8266: 		$result = &js_ready($result);
1.315     albertel 8267:     }
1.320     albertel 8268:     if ($args->{'html_encode'}) {
1.713     kaisler  8269: 		$result = &html_encode($result);
                   8270:     }
                   8271: 
1.813     bisitz   8272:     # Preparation for new and consistent functionlist at top of screen
                   8273:     # if ($args->{'functionlist'}) {
                   8274:     #            $result .= &build_functionlist();
                   8275:     #}
                   8276: 
1.964     droeschl 8277:     # Don't add anything more if only_body wanted or in const space
                   8278:     return $result if    $args->{'only_body'} 
                   8279:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8280: 
                   8281:     #Breadcrumbs
1.758     kaisler  8282:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8283: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8284: 		#if any br links exists, add them to the breadcrumbs
                   8285: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8286: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8287: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8288: 			}
                   8289: 		}
1.1075.2.19  raeburn  8290:                 # if @advtools array contains items add then to the breadcrumbs
                   8291:                 if (@advtools > 0) {
                   8292:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8293:                 }
1.1075.2.123  raeburn  8294:                 my $menulink;
                   8295:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8296:                 if (exists($args->{'bread_crumbs_nomenu'})) {
                   8297:                     $menulink = 0;
                   8298:                 } else {
                   8299:                     undef($menulink);
                   8300:                 }
1.758     kaisler  8301: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8302: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  8303: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.758     kaisler  8304: 		}else{
1.1075.2.123  raeburn  8305: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8306: 		}
1.1075.2.24  raeburn  8307:     } elsif (($env{'environment.remote'} eq 'on') &&
                   8308:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   8309:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   8310:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  8311:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 8312:     }
1.315     albertel 8313:     return $result;
1.306     albertel 8314: }
                   8315: 
                   8316: sub end_page {
1.315     albertel 8317:     my ($args) = @_;
                   8318:     $env{'internal.end_page'}++;
1.330     albertel 8319:     my $result;
1.335     albertel 8320:     if ($args->{'discussion'}) {
                   8321: 	my ($target,$parser);
                   8322: 	if (ref($args->{'discussion'})) {
                   8323: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8324: 				$args->{'discussion'}{'parser'});
                   8325: 	}
                   8326: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8327:     }
1.330     albertel 8328:     if ($args->{'frameset'}) {
                   8329: 	$result .= '</frameset>';
                   8330:     } else {
1.635     raeburn  8331: 	$result .= &endbodytag($args);
1.330     albertel 8332:     }
1.1075.2.6  raeburn  8333:     unless ($args->{'notbody'}) {
                   8334:         $result .= "\n</html>";
                   8335:     }
1.330     albertel 8336: 
1.315     albertel 8337:     if ($args->{'js_ready'}) {
1.317     albertel 8338: 	$result = &js_ready($result);
1.315     albertel 8339:     }
1.335     albertel 8340: 
1.320     albertel 8341:     if ($args->{'html_encode'}) {
                   8342: 	$result = &html_encode($result);
                   8343:     }
1.335     albertel 8344: 
1.315     albertel 8345:     return $result;
                   8346: }
                   8347: 
1.1034    www      8348: sub wishlist_window {
                   8349:     return(<<'ENDWISHLIST');
1.1046    raeburn  8350: <script type="text/javascript">
1.1034    www      8351: // <![CDATA[
                   8352: // <!-- BEGIN LON-CAPA Internal
                   8353: function set_wishlistlink(title, path) {
                   8354:     if (!title) {
                   8355:         title = document.title;
                   8356:         title = title.replace(/^LON-CAPA /,'');
                   8357:     }
1.1075.2.65  raeburn  8358:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  8359:     title = title.replace("'","\\\'");
1.1034    www      8360:     if (!path) {
                   8361:         path = location.pathname;
                   8362:     }
1.1075.2.65  raeburn  8363:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  8364:     path = path.replace("'","\\\'");
1.1034    www      8365:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8366:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8367: }
                   8368: // END LON-CAPA Internal -->
                   8369: // ]]>
                   8370: </script>
                   8371: ENDWISHLIST
                   8372: }
                   8373: 
1.1030    www      8374: sub modal_window {
                   8375:     return(<<'ENDMODAL');
1.1046    raeburn  8376: <script type="text/javascript">
1.1030    www      8377: // <![CDATA[
                   8378: // <!-- BEGIN LON-CAPA Internal
                   8379: var modalWindow = {
                   8380: 	parent:"body",
                   8381: 	windowId:null,
                   8382: 	content:null,
                   8383: 	width:null,
                   8384: 	height:null,
                   8385: 	close:function()
                   8386: 	{
                   8387: 	        $(".LCmodal-window").remove();
                   8388: 	        $(".LCmodal-overlay").remove();
                   8389: 	},
                   8390: 	open:function()
                   8391: 	{
                   8392: 		var modal = "";
                   8393: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8394: 		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;\">";
                   8395: 		modal += this.content;
                   8396: 		modal += "</div>";	
                   8397: 
                   8398: 		$(this.parent).append(modal);
                   8399: 
                   8400: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8401: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8402: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8403: 	}
                   8404: };
1.1075.2.42  raeburn  8405: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8406: 	{
1.1075.2.119  raeburn  8407:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8408: 		modalWindow.windowId = "myModal";
                   8409: 		modalWindow.width = width;
                   8410: 		modalWindow.height = height;
1.1075.2.80  raeburn  8411: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8412: 		modalWindow.open();
1.1075.2.87  raeburn  8413: 	};
1.1030    www      8414: // END LON-CAPA Internal -->
                   8415: // ]]>
                   8416: </script>
                   8417: ENDMODAL
                   8418: }
                   8419: 
                   8420: sub modal_link {
1.1075.2.42  raeburn  8421:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8422:     unless ($width) { $width=480; }
                   8423:     unless ($height) { $height=400; }
1.1031    www      8424:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  8425:     unless ($transparency) { $transparency='true'; }
                   8426: 
1.1074    raeburn  8427:     my $target_attr;
                   8428:     if (defined($target)) {
                   8429:         $target_attr = 'target="'.$target.'"';
                   8430:     }
                   8431:     return <<"ENDLINK";
1.1075.2.141.  .3(raebu 8432:20): <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  8433: ENDLINK
1.1030    www      8434: }
                   8435: 
1.1032    www      8436: sub modal_adhoc_script {
                   8437:     my ($funcname,$width,$height,$content)=@_;
                   8438:     return (<<ENDADHOC);
1.1046    raeburn  8439: <script type="text/javascript">
1.1032    www      8440: // <![CDATA[
                   8441:         var $funcname = function()
                   8442:         {
                   8443:                 modalWindow.windowId = "myModal";
                   8444:                 modalWindow.width = $width;
                   8445:                 modalWindow.height = $height;
                   8446:                 modalWindow.content = '$content';
                   8447:                 modalWindow.open();
                   8448:         };  
                   8449: // ]]>
                   8450: </script>
                   8451: ENDADHOC
                   8452: }
                   8453: 
1.1041    www      8454: sub modal_adhoc_inner {
                   8455:     my ($funcname,$width,$height,$content)=@_;
                   8456:     my $innerwidth=$width-20;
                   8457:     $content=&js_ready(
1.1042    www      8458:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  8459:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8460:                  $content.
1.1041    www      8461:                  &end_scrollbox().
1.1075.2.42  raeburn  8462:                  &end_page()
1.1041    www      8463:              );
                   8464:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8465: }
                   8466: 
                   8467: sub modal_adhoc_window {
                   8468:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8469:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8470:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8471: }
                   8472: 
                   8473: sub modal_adhoc_launch {
                   8474:     my ($funcname,$width,$height,$content)=@_;
                   8475:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8476: <script type="text/javascript">
                   8477: // <![CDATA[
                   8478: $funcname();
                   8479: // ]]>
                   8480: </script>
                   8481: ENDLAUNCH
                   8482: }
                   8483: 
                   8484: sub modal_adhoc_close {
                   8485:     return (<<ENDCLOSE);
                   8486: <script type="text/javascript">
                   8487: // <![CDATA[
                   8488: modalWindow.close();
                   8489: // ]]>
                   8490: </script>
                   8491: ENDCLOSE
                   8492: }
                   8493: 
1.1038    www      8494: sub togglebox_script {
                   8495:    return(<<ENDTOGGLE);
                   8496: <script type="text/javascript"> 
                   8497: // <![CDATA[
                   8498: function LCtoggleDisplay(id,hidetext,showtext) {
                   8499:    link = document.getElementById(id + "link").childNodes[0];
                   8500:    with (document.getElementById(id).style) {
                   8501:       if (display == "none" ) {
                   8502:           display = "inline";
                   8503:           link.nodeValue = hidetext;
                   8504:         } else {
                   8505:           display = "none";
                   8506:           link.nodeValue = showtext;
                   8507:        }
                   8508:    }
                   8509: }
                   8510: // ]]>
                   8511: </script>
                   8512: ENDTOGGLE
                   8513: }
                   8514: 
1.1039    www      8515: sub start_togglebox {
                   8516:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8517:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8518:     unless ($showtext) { $showtext=&mt('show'); }
                   8519:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8520:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8521:     return &start_data_table().
                   8522:            &start_data_table_header_row().
                   8523:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8524:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8525:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8526:            &end_data_table_header_row().
                   8527:            '<tr id="'.$id.'" style="display:none""><td>';
                   8528: }
                   8529: 
                   8530: sub end_togglebox {
                   8531:     return '</td></tr>'.&end_data_table();
                   8532: }
                   8533: 
1.1041    www      8534: sub LCprogressbar_script {
1.1075.2.130  raeburn  8535:    my ($id,$number_to_do)=@_;
                   8536:    if ($number_to_do) {
                   8537:        return(<<ENDPROGRESS);
1.1041    www      8538: <script type="text/javascript">
                   8539: // <![CDATA[
1.1045    www      8540: \$('#progressbar$id').progressbar({
1.1041    www      8541:   value: 0,
                   8542:   change: function(event, ui) {
                   8543:     var newVal = \$(this).progressbar('option', 'value');
                   8544:     \$('.pblabel', this).text(LCprogressTxt);
                   8545:   }
                   8546: });
                   8547: // ]]>
                   8548: </script>
                   8549: ENDPROGRESS
1.1075.2.130  raeburn  8550:    } else {
                   8551:        return(<<ENDPROGRESS);
                   8552: <script type="text/javascript">
                   8553: // <![CDATA[
                   8554: \$('#progressbar$id').progressbar({
                   8555:   value: false,
                   8556:   create: function(event, ui) {
                   8557:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   8558:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   8559:   }
                   8560: });
                   8561: // ]]>
                   8562: </script>
                   8563: ENDPROGRESS
                   8564:    }
1.1041    www      8565: }
                   8566: 
                   8567: sub LCprogressbarUpdate_script {
                   8568:    return(<<ENDPROGRESSUPDATE);
                   8569: <style type="text/css">
                   8570: .ui-progressbar { position:relative; }
1.1075.2.130  raeburn  8571: .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      8572: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8573: </style>
                   8574: <script type="text/javascript">
                   8575: // <![CDATA[
1.1045    www      8576: var LCprogressTxt='---';
                   8577: 
1.1075.2.130  raeburn  8578: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      8579:    LCprogressTxt=progresstext;
1.1075.2.130  raeburn  8580:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   8581:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   8582:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
                   8583:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   8584:    } else {
                   8585:        \$('#progressbar'+id).progressbar('value',percent);
                   8586:    }
1.1041    www      8587: }
                   8588: // ]]>
                   8589: </script>
                   8590: ENDPROGRESSUPDATE
                   8591: }
                   8592: 
1.1042    www      8593: my $LClastpercent;
1.1045    www      8594: my $LCidcnt;
                   8595: my $LCcurrentid;
1.1042    www      8596: 
1.1041    www      8597: sub LCprogressbar {
1.1075.2.130  raeburn  8598:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      8599:     $LClastpercent=0;
1.1045    www      8600:     $LCidcnt++;
                   8601:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1075.2.130  raeburn  8602:     my ($starting,$content);
                   8603:     if ($number_to_do) {
                   8604:         $starting=&mt('Starting');
                   8605:         $content=(<<ENDPROGBAR);
                   8606: $preamble
1.1045    www      8607:   <div id="progressbar$LCcurrentid">
1.1041    www      8608:     <span class="pblabel">$starting</span>
                   8609:   </div>
                   8610: ENDPROGBAR
1.1075.2.130  raeburn  8611:     } else {
                   8612:         $starting=&mt('Loading...');
                   8613:         $LClastpercent='false';
                   8614:         $content=(<<ENDPROGBAR);
                   8615: $preamble
                   8616:   <div id="progressbar$LCcurrentid">
                   8617:       <div class="progress-label">$starting</div>
                   8618:   </div>
                   8619: ENDPROGBAR
                   8620:     }
                   8621:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      8622: }
                   8623: 
                   8624: sub LCprogressbarUpdate {
1.1075.2.130  raeburn  8625:     my ($r,$val,$text,$number_to_do)=@_;
                   8626:     if ($number_to_do) {
                   8627:         unless ($val) { 
                   8628:             if ($LClastpercent) {
                   8629:                 $val=$LClastpercent;
                   8630:             } else {
                   8631:                 $val=0;
                   8632:             }
                   8633:         }
                   8634:         if ($val<0) { $val=0; }
                   8635:         if ($val>100) { $val=0; }
                   8636:         $LClastpercent=$val;
                   8637:         unless ($text) { $text=$val.'%'; }
                   8638:     } else {
                   8639:         $val = 'false';
1.1042    www      8640:     }
1.1041    www      8641:     $text=&js_ready($text);
1.1044    www      8642:     &r_print($r,<<ENDUPDATE);
1.1041    www      8643: <script type="text/javascript">
                   8644: // <![CDATA[
1.1075.2.130  raeburn  8645: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      8646: // ]]>
                   8647: </script>
                   8648: ENDUPDATE
1.1035    www      8649: }
                   8650: 
1.1042    www      8651: sub LCprogressbarClose {
                   8652:     my ($r)=@_;
                   8653:     $LClastpercent=0;
1.1044    www      8654:     &r_print($r,<<ENDCLOSE);
1.1042    www      8655: <script type="text/javascript">
                   8656: // <![CDATA[
1.1045    www      8657: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8658: // ]]>
                   8659: </script>
                   8660: ENDCLOSE
1.1044    www      8661: }
                   8662: 
                   8663: sub r_print {
                   8664:     my ($r,$to_print)=@_;
                   8665:     if ($r) {
                   8666:       $r->print($to_print);
                   8667:       $r->rflush();
                   8668:     } else {
                   8669:       print($to_print);
                   8670:     }
1.1042    www      8671: }
                   8672: 
1.320     albertel 8673: sub html_encode {
                   8674:     my ($result) = @_;
                   8675: 
1.322     albertel 8676:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8677:     
                   8678:     return $result;
                   8679: }
1.1044    www      8680: 
1.317     albertel 8681: sub js_ready {
                   8682:     my ($result) = @_;
                   8683: 
1.323     albertel 8684:     $result =~ s/[\n\r]/ /xmsg;
                   8685:     $result =~ s/\\/\\\\/xmsg;
                   8686:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8687:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8688:     
                   8689:     return $result;
                   8690: }
                   8691: 
1.315     albertel 8692: sub validate_page {
                   8693:     if (  exists($env{'internal.start_page'})
1.316     albertel 8694: 	  &&     $env{'internal.start_page'} > 1) {
                   8695: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8696: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8697: 				 $ENV{'request.filename'});
1.315     albertel 8698:     }
                   8699:     if (  exists($env{'internal.end_page'})
1.316     albertel 8700: 	  &&     $env{'internal.end_page'} > 1) {
                   8701: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8702: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8703: 				 $env{'request.filename'});
1.315     albertel 8704:     }
                   8705:     if (     exists($env{'internal.start_page'})
                   8706: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8707: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8708: 				 $env{'request.filename'});
1.315     albertel 8709:     }
                   8710:     if (   ! exists($env{'internal.start_page'})
                   8711: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8712: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8713: 				 $env{'request.filename'});
1.315     albertel 8714:     }
1.306     albertel 8715: }
1.315     albertel 8716: 
1.996     www      8717: 
                   8718: sub start_scrollbox {
1.1075.2.56  raeburn  8719:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8720:     unless ($outerwidth) { $outerwidth='520px'; }
                   8721:     unless ($width) { $width='500px'; }
                   8722:     unless ($height) { $height='200px'; }
1.1075    raeburn  8723:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8724:     if ($id ne '') {
1.1075.2.42  raeburn  8725:         $table_id = ' id="table_'.$id.'"';
                   8726:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8727:     }
1.1075    raeburn  8728:     if ($bgcolor ne '') {
                   8729:         $tdcol = "background-color: $bgcolor;";
                   8730:     }
1.1075.2.42  raeburn  8731:     my $nicescroll_js;
                   8732:     if ($env{'browser.mobile'}) {
                   8733:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8734:     }
1.1075    raeburn  8735:     return <<"END";
1.1075.2.42  raeburn  8736: $nicescroll_js
                   8737: 
                   8738: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8739: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8740: END
1.996     www      8741: }
                   8742: 
                   8743: sub end_scrollbox {
1.1036    www      8744:     return '</div></td></tr></table>';
1.996     www      8745: }
                   8746: 
1.1075.2.42  raeburn  8747: sub nicescroll_javascript {
                   8748:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8749:     my %options;
                   8750:     if (ref($cursor) eq 'HASH') {
                   8751:         %options = %{$cursor};
                   8752:     }
                   8753:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8754:         $options{'railalign'} = 'left';
                   8755:     }
                   8756:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8757:         my $function  = &get_users_function();
                   8758:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8759:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8760:             $options{'cursorcolor'} = '#00F';
                   8761:         }
                   8762:     }
                   8763:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8764:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8765:             $options{'cursoropacity'}='1.0';
                   8766:         }
                   8767:     } else {
                   8768:         $options{'cursoropacity'}='1.0';
                   8769:     }
                   8770:     if ($options{'cursorfixedheight'} eq 'none') {
                   8771:         delete($options{'cursorfixedheight'});
                   8772:     } else {
                   8773:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8774:     }
                   8775:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8776:         delete($options{'railoffset'});
                   8777:     }
                   8778:     my @niceoptions;
                   8779:     while (my($key,$value) = each(%options)) {
                   8780:         if ($value =~ /^\{.+\}$/) {
                   8781:             push(@niceoptions,$key.':'.$value);
                   8782:         } else {
                   8783:             push(@niceoptions,$key.':"'.$value.'"');
                   8784:         }
                   8785:     }
                   8786:     my $nicescroll_js = '
                   8787: $(document).ready(
                   8788:       function() {
                   8789:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8790:       }
                   8791: );
                   8792: ';
                   8793:     if ($framecheck) {
                   8794:         $nicescroll_js .= '
                   8795: function expand_div(caller) {
                   8796:     if (top === self) {
                   8797:         document.getElementById("'.$id.'").style.width = "auto";
                   8798:         document.getElementById("'.$id.'").style.height = "auto";
                   8799:     } else {
                   8800:         try {
                   8801:             if (parent.frames) {
                   8802:                 if (parent.frames.length > 1) {
                   8803:                     var framesrc = parent.frames[1].location.href;
                   8804:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8805:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8806:                         document.getElementById("'.$id.'").style.width = "auto";
                   8807:                         document.getElementById("'.$id.'").style.height = "auto";
                   8808:                     }
                   8809:                 }
                   8810:             }
                   8811:         } catch (e) {
                   8812:             return;
                   8813:         }
                   8814:     }
                   8815:     return;
                   8816: }
                   8817: ';
                   8818:     }
                   8819:     if ($needjsready) {
                   8820:         $nicescroll_js = '
                   8821: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8822:     } else {
                   8823:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8824:     }
                   8825:     return $nicescroll_js;
                   8826: }
                   8827: 
1.318     albertel 8828: sub simple_error_page {
1.1075.2.49  raeburn  8829:     my ($r,$title,$msg,$args) = @_;
                   8830:     if (ref($args) eq 'HASH') {
                   8831:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8832:     } else {
                   8833:         $msg = &mt($msg);
                   8834:     }
                   8835: 
1.318     albertel 8836:     my $page =
                   8837: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8838: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8839: 	&Apache::loncommon::end_page();
                   8840:     if (ref($r)) {
                   8841: 	$r->print($page);
1.327     albertel 8842: 	return;
1.318     albertel 8843:     }
                   8844:     return $page;
                   8845: }
1.347     albertel 8846: 
                   8847: {
1.610     albertel 8848:     my @row_count;
1.961     onken    8849: 
                   8850:     sub start_data_table_count {
                   8851:         unshift(@row_count, 0);
                   8852:         return;
                   8853:     }
                   8854: 
                   8855:     sub end_data_table_count {
                   8856:         shift(@row_count);
                   8857:         return;
                   8858:     }
                   8859: 
1.347     albertel 8860:     sub start_data_table {
1.1018    raeburn  8861: 	my ($add_class,$id) = @_;
1.422     albertel 8862: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8863:         my $table_id;
                   8864:         if (defined($id)) {
                   8865:             $table_id = ' id="'.$id.'"';
                   8866:         }
1.961     onken    8867: 	&start_data_table_count();
1.1018    raeburn  8868: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8869:     }
                   8870: 
                   8871:     sub end_data_table {
1.961     onken    8872: 	&end_data_table_count();
1.389     albertel 8873: 	return '</table>'."\n";;
1.347     albertel 8874:     }
                   8875: 
                   8876:     sub start_data_table_row {
1.974     wenzelju 8877: 	my ($add_class, $id) = @_;
1.610     albertel 8878: 	$row_count[0]++;
                   8879: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8880: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8881:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8882:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8883:     }
1.471     banghart 8884:     
                   8885:     sub continue_data_table_row {
1.974     wenzelju 8886: 	my ($add_class, $id) = @_;
1.610     albertel 8887: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8888: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8889:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8890:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8891:     }
1.347     albertel 8892: 
                   8893:     sub end_data_table_row {
1.389     albertel 8894: 	return '</tr>'."\n";;
1.347     albertel 8895:     }
1.367     www      8896: 
1.421     albertel 8897:     sub start_data_table_empty_row {
1.707     bisitz   8898: #	$row_count[0]++;
1.421     albertel 8899: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8900:     }
                   8901: 
                   8902:     sub end_data_table_empty_row {
                   8903: 	return '</tr>'."\n";;
                   8904:     }
                   8905: 
1.367     www      8906:     sub start_data_table_header_row {
1.389     albertel 8907: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8908:     }
                   8909: 
                   8910:     sub end_data_table_header_row {
1.389     albertel 8911: 	return '</tr>'."\n";;
1.367     www      8912:     }
1.890     droeschl 8913: 
                   8914:     sub data_table_caption {
                   8915:         my $caption = shift;
                   8916:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8917:     }
1.347     albertel 8918: }
                   8919: 
1.548     albertel 8920: =pod
                   8921: 
                   8922: =item * &inhibit_menu_check($arg)
                   8923: 
                   8924: Checks for a inhibitmenu state and generates output to preserve it
                   8925: 
                   8926: Inputs:         $arg - can be any of
                   8927:                      - undef - in which case the return value is a string 
                   8928:                                to add  into arguments list of a uri
                   8929:                      - 'input' - in which case the return value is a HTML
                   8930:                                  <form> <input> field of type hidden to
                   8931:                                  preserve the value
                   8932:                      - a url - in which case the return value is the url with
                   8933:                                the neccesary cgi args added to preserve the
                   8934:                                inhibitmenu state
                   8935:                      - a ref to a url - no return value, but the string is
                   8936:                                         updated to include the neccessary cgi
                   8937:                                         args to preserve the inhibitmenu state
                   8938: 
                   8939: =cut
                   8940: 
                   8941: sub inhibit_menu_check {
                   8942:     my ($arg) = @_;
                   8943:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8944:     if ($arg eq 'input') {
                   8945: 	if ($env{'form.inhibitmenu'}) {
                   8946: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8947: 	} else {
                   8948: 	    return
                   8949: 	}
                   8950:     }
                   8951:     if ($env{'form.inhibitmenu'}) {
                   8952: 	if (ref($arg)) {
                   8953: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8954: 	} elsif ($arg eq '') {
                   8955: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8956: 	} else {
                   8957: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8958: 	}
                   8959:     }
                   8960:     if (!ref($arg)) {
                   8961: 	return $arg;
                   8962:     }
                   8963: }
                   8964: 
1.251     albertel 8965: ###############################################
1.182     matthew  8966: 
                   8967: =pod
                   8968: 
1.549     albertel 8969: =back
                   8970: 
                   8971: =head1 User Information Routines
                   8972: 
                   8973: =over 4
                   8974: 
1.405     albertel 8975: =item * &get_users_function()
1.182     matthew  8976: 
                   8977: Used by &bodytag to determine the current users primary role.
                   8978: Returns either 'student','coordinator','admin', or 'author'.
                   8979: 
                   8980: =cut
                   8981: 
                   8982: ###############################################
                   8983: sub get_users_function {
1.815     tempelho 8984:     my $function = 'norole';
1.818     tempelho 8985:     if ($env{'request.role'}=~/^(st)/) {
                   8986:         $function='student';
                   8987:     }
1.907     raeburn  8988:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8989:         $function='coordinator';
                   8990:     }
1.258     albertel 8991:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8992:         $function='admin';
                   8993:     }
1.826     bisitz   8994:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8995:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8996:         $function='author';
                   8997:     }
                   8998:     return $function;
1.54      www      8999: }
1.99      www      9000: 
                   9001: ###############################################
                   9002: 
1.233     raeburn  9003: =pod
                   9004: 
1.821     raeburn  9005: =item * &show_course()
                   9006: 
                   9007: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9008: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9009: 
                   9010: Inputs:
                   9011: None
                   9012: 
                   9013: Outputs:
                   9014: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9015: 
                   9016: =cut
                   9017: 
                   9018: ###############################################
                   9019: sub show_course {
                   9020:     my $course = !$env{'user.adv'};
                   9021:     if (!$env{'user.adv'}) {
                   9022:         foreach my $env (keys(%env)) {
                   9023:             next if ($env !~ m/^user\.priv\./);
                   9024:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9025:                 $course = 0;
                   9026:                 last;
                   9027:             }
                   9028:         }
                   9029:     }
                   9030:     return $course;
                   9031: }
                   9032: 
                   9033: ###############################################
                   9034: 
                   9035: =pod
                   9036: 
1.542     raeburn  9037: =item * &check_user_status()
1.274     raeburn  9038: 
                   9039: Determines current status of supplied role for a
                   9040: specific user. Roles can be active, previous or future.
                   9041: 
                   9042: Inputs: 
                   9043: user's domain, user's username, course's domain,
1.375     raeburn  9044: course's number, optional section ID.
1.274     raeburn  9045: 
                   9046: Outputs:
                   9047: role status: active, previous or future. 
                   9048: 
                   9049: =cut
                   9050: 
                   9051: sub check_user_status {
1.412     raeburn  9052:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9053:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  9054:     my @uroles = keys(%userinfo);
1.274     raeburn  9055:     my $srchstr;
                   9056:     my $active_chk = 'none';
1.412     raeburn  9057:     my $now = time;
1.274     raeburn  9058:     if (@uroles > 0) {
1.908     raeburn  9059:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9060:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9061:         } else {
1.412     raeburn  9062:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9063:         }
                   9064:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9065:             my $role_end = 0;
                   9066:             my $role_start = 0;
                   9067:             $active_chk = 'active';
1.412     raeburn  9068:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9069:                 $role_end = $1;
                   9070:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9071:                     $role_start = $1;
1.274     raeburn  9072:                 }
                   9073:             }
                   9074:             if ($role_start > 0) {
1.412     raeburn  9075:                 if ($now < $role_start) {
1.274     raeburn  9076:                     $active_chk = 'future';
                   9077:                 }
                   9078:             }
                   9079:             if ($role_end > 0) {
1.412     raeburn  9080:                 if ($now > $role_end) {
1.274     raeburn  9081:                     $active_chk = 'previous';
                   9082:                 }
                   9083:             }
                   9084:         }
                   9085:     }
                   9086:     return $active_chk;
                   9087: }
                   9088: 
                   9089: ###############################################
                   9090: 
                   9091: =pod
                   9092: 
1.405     albertel 9093: =item * &get_sections()
1.233     raeburn  9094: 
                   9095: Determines all the sections for a course including
                   9096: sections with students and sections containing other roles.
1.419     raeburn  9097: Incoming parameters: 
                   9098: 
                   9099: 1. domain
                   9100: 2. course number 
                   9101: 3. reference to array containing roles for which sections should 
                   9102: be gathered (optional).
                   9103: 4. reference to array containing status types for which sections 
                   9104: should be gathered (optional).
                   9105: 
                   9106: If the third argument is undefined, sections are gathered for any role. 
                   9107: If the fourth argument is undefined, sections are gathered for any status.
                   9108: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9109:  
1.374     raeburn  9110: Returns section hash (keys are section IDs, values are
                   9111: number of users in each section), subject to the
1.419     raeburn  9112: optional roles filter, optional status filter 
1.233     raeburn  9113: 
                   9114: =cut
                   9115: 
                   9116: ###############################################
                   9117: sub get_sections {
1.419     raeburn  9118:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9119:     if (!defined($cdom) || !defined($cnum)) {
                   9120:         my $cid =  $env{'request.course.id'};
                   9121: 
                   9122: 	return if (!defined($cid));
                   9123: 
                   9124:         $cdom = $env{'course.'.$cid.'.domain'};
                   9125:         $cnum = $env{'course.'.$cid.'.num'};
                   9126:     }
                   9127: 
                   9128:     my %sectioncount;
1.419     raeburn  9129:     my $now = time;
1.240     albertel 9130: 
1.1075.2.33  raeburn  9131:     my $check_students = 1;
                   9132:     my $only_students = 0;
                   9133:     if (ref($possible_roles) eq 'ARRAY') {
                   9134:         if (grep(/^st$/,@{$possible_roles})) {
                   9135:             if (@{$possible_roles} == 1) {
                   9136:                 $only_students = 1;
                   9137:             }
                   9138:         } else {
                   9139:             $check_students = 0;
                   9140:         }
                   9141:     }
                   9142: 
                   9143:     if ($check_students) {
1.276     albertel 9144: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9145: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9146: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9147:         my $start_index = &Apache::loncoursedata::CL_START();
                   9148:         my $end_index = &Apache::loncoursedata::CL_END();
                   9149:         my $status;
1.366     albertel 9150: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9151: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9152: 				                     $data->[$status_index],
                   9153:                                                      $data->[$start_index],
                   9154:                                                      $data->[$end_index]);
                   9155:             if ($stu_status eq 'Active') {
                   9156:                 $status = 'active';
                   9157:             } elsif ($end < $now) {
                   9158:                 $status = 'previous';
                   9159:             } elsif ($start > $now) {
                   9160:                 $status = 'future';
                   9161:             } 
                   9162: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9163:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9164:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9165: 		    $sectioncount{$section}++;
                   9166:                 }
1.240     albertel 9167: 	    }
                   9168: 	}
                   9169:     }
1.1075.2.33  raeburn  9170:     if ($only_students) {
                   9171:         return %sectioncount;
                   9172:     }
1.240     albertel 9173:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9174:     foreach my $user (sort(keys(%courseroles))) {
                   9175: 	if ($user !~ /^(\w{2})/) { next; }
                   9176: 	my ($role) = ($user =~ /^(\w{2})/);
                   9177: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9178: 	my ($section,$status);
1.240     albertel 9179: 	if ($role eq 'cr' &&
                   9180: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9181: 	    $section=$1;
                   9182: 	}
                   9183: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9184: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9185:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9186:         if ($end == -1 && $start == -1) {
                   9187:             next; #deleted role
                   9188:         }
                   9189:         if (!defined($possible_status)) { 
                   9190:             $sectioncount{$section}++;
                   9191:         } else {
                   9192:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9193:                 $status = 'active';
                   9194:             } elsif ($end < $now) {
                   9195:                 $status = 'future';
                   9196:             } elsif ($start > $now) {
                   9197:                 $status = 'previous';
                   9198:             }
                   9199:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9200:                 $sectioncount{$section}++;
                   9201:             }
                   9202:         }
1.233     raeburn  9203:     }
1.366     albertel 9204:     return %sectioncount;
1.233     raeburn  9205: }
                   9206: 
1.274     raeburn  9207: ###############################################
1.294     raeburn  9208: 
                   9209: =pod
1.405     albertel 9210: 
                   9211: =item * &get_course_users()
                   9212: 
1.275     raeburn  9213: Retrieves usernames:domains for users in the specified course
                   9214: with specific role(s), and access status. 
                   9215: 
                   9216: Incoming parameters:
1.277     albertel 9217: 1. course domain
                   9218: 2. course number
                   9219: 3. access status: users must have - either active, 
1.275     raeburn  9220: previous, future, or all.
1.277     albertel 9221: 4. reference to array of permissible roles
1.288     raeburn  9222: 5. reference to array of section restrictions (optional)
                   9223: 6. reference to results object (hash of hashes).
                   9224: 7. reference to optional userdata hash
1.609     raeburn  9225: 8. reference to optional statushash
1.630     raeburn  9226: 9. flag if privileged users (except those set to unhide in
                   9227:    course settings) should be excluded    
1.609     raeburn  9228: Keys of top level results hash are roles.
1.275     raeburn  9229: Keys of inner hashes are username:domain, with 
                   9230: values set to access type.
1.288     raeburn  9231: Optional userdata hash returns an array with arguments in the 
                   9232: same order as loncoursedata::get_classlist() for student data.
                   9233: 
1.609     raeburn  9234: Optional statushash returns
                   9235: 
1.288     raeburn  9236: Entries for end, start, section and status are blank because
                   9237: of the possibility of multiple values for non-student roles.
                   9238: 
1.275     raeburn  9239: =cut
1.405     albertel 9240: 
1.275     raeburn  9241: ###############################################
1.405     albertel 9242: 
1.275     raeburn  9243: sub get_course_users {
1.630     raeburn  9244:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9245:     my %idx = ();
1.419     raeburn  9246:     my %seclists;
1.288     raeburn  9247: 
                   9248:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9249:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9250:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9251:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9252:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9253:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9254:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9255:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9256: 
1.290     albertel 9257:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9258:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9259:         my $now = time;
1.277     albertel 9260:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9261:             my $match = 0;
1.412     raeburn  9262:             my $secmatch = 0;
1.419     raeburn  9263:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9264:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9265:             if ($section eq '') {
                   9266:                 $section = 'none';
                   9267:             }
1.291     albertel 9268:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9269:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9270:                     $secmatch = 1;
                   9271:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9272:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9273:                         $secmatch = 1;
                   9274:                     }
                   9275:                 } else {  
1.419     raeburn  9276: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9277: 		        $secmatch = 1;
                   9278:                     }
1.290     albertel 9279: 		}
1.412     raeburn  9280:                 if (!$secmatch) {
                   9281:                     next;
                   9282:                 }
1.419     raeburn  9283:             }
1.275     raeburn  9284:             if (defined($$types{'active'})) {
1.288     raeburn  9285:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9286:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9287:                     $match = 1;
1.275     raeburn  9288:                 }
                   9289:             }
                   9290:             if (defined($$types{'previous'})) {
1.609     raeburn  9291:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9292:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9293:                     $match = 1;
1.275     raeburn  9294:                 }
                   9295:             }
                   9296:             if (defined($$types{'future'})) {
1.609     raeburn  9297:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9298:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9299:                     $match = 1;
1.275     raeburn  9300:                 }
                   9301:             }
1.609     raeburn  9302:             if ($match) {
                   9303:                 push(@{$seclists{$student}},$section);
                   9304:                 if (ref($userdata) eq 'HASH') {
                   9305:                     $$userdata{$student} = $$classlist{$student};
                   9306:                 }
                   9307:                 if (ref($statushash) eq 'HASH') {
                   9308:                     $statushash->{$student}{'st'}{$section} = $status;
                   9309:                 }
1.288     raeburn  9310:             }
1.275     raeburn  9311:         }
                   9312:     }
1.412     raeburn  9313:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9314:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9315:         my $now = time;
1.609     raeburn  9316:         my %displaystatus = ( previous => 'Expired',
                   9317:                               active   => 'Active',
                   9318:                               future   => 'Future',
                   9319:                             );
1.1075.2.36  raeburn  9320:         my (%nothide,@possdoms);
1.630     raeburn  9321:         if ($hidepriv) {
                   9322:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9323:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9324:                 if ($user !~ /:/) {
                   9325:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9326:                 } else {
                   9327:                     $nothide{$user} = 1;
                   9328:                 }
                   9329:             }
1.1075.2.36  raeburn  9330:             my @possdoms = ($cdom);
                   9331:             if ($coursehash{'checkforpriv'}) {
                   9332:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9333:             }
1.630     raeburn  9334:         }
1.439     raeburn  9335:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9336:             my $match = 0;
1.412     raeburn  9337:             my $secmatch = 0;
1.439     raeburn  9338:             my $status;
1.412     raeburn  9339:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9340:             $user =~ s/:$//;
1.439     raeburn  9341:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9342:             if ($end == -1 || $start == -1) {
                   9343:                 next;
                   9344:             }
                   9345:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9346:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9347:                 my ($uname,$udom) = split(/:/,$user);
                   9348:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9349:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9350:                         $secmatch = 1;
                   9351:                     } elsif ($usec eq '') {
1.420     albertel 9352:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9353:                             $secmatch = 1;
                   9354:                         }
                   9355:                     } else {
                   9356:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9357:                             $secmatch = 1;
                   9358:                         }
                   9359:                     }
                   9360:                     if (!$secmatch) {
                   9361:                         next;
                   9362:                     }
1.288     raeburn  9363:                 }
1.419     raeburn  9364:                 if ($usec eq '') {
                   9365:                     $usec = 'none';
                   9366:                 }
1.275     raeburn  9367:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9368:                     if ($hidepriv) {
1.1075.2.36  raeburn  9369:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9370:                             (!$nothide{$uname.':'.$udom})) {
                   9371:                             next;
                   9372:                         }
                   9373:                     }
1.503     raeburn  9374:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9375:                         $status = 'previous';
                   9376:                     } elsif ($start > $now) {
                   9377:                         $status = 'future';
                   9378:                     } else {
                   9379:                         $status = 'active';
                   9380:                     }
1.277     albertel 9381:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9382:                         if ($status eq $type) {
1.420     albertel 9383:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9384:                                 push(@{$$users{$role}{$user}},$type);
                   9385:                             }
1.288     raeburn  9386:                             $match = 1;
                   9387:                         }
                   9388:                     }
1.419     raeburn  9389:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9390:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9391: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9392:                         }
1.420     albertel 9393:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9394:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9395:                         }
1.609     raeburn  9396:                         if (ref($statushash) eq 'HASH') {
                   9397:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9398:                         }
1.275     raeburn  9399:                     }
                   9400:                 }
                   9401:             }
                   9402:         }
1.290     albertel 9403:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9404:             if ((defined($cdom)) && (defined($cnum))) {
                   9405:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9406:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9407:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9408:                     next if ($owner eq '');
                   9409:                     my ($ownername,$ownerdom);
                   9410:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9411:                         $ownername = $1;
                   9412:                         $ownerdom = $2;
                   9413:                     } else {
                   9414:                         $ownername = $owner;
                   9415:                         $ownerdom = $cdom;
                   9416:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9417:                     }
                   9418:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9419:                     if (defined($userdata) && 
1.609     raeburn  9420: 			!exists($$userdata{$owner})) {
                   9421: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9422:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9423:                             push(@{$seclists{$owner}},'none');
                   9424:                         }
                   9425:                         if (ref($statushash) eq 'HASH') {
                   9426:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9427:                         }
1.290     albertel 9428: 		    }
1.279     raeburn  9429:                 }
                   9430:             }
                   9431:         }
1.419     raeburn  9432:         foreach my $user (keys(%seclists)) {
                   9433:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9434:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9435:         }
1.275     raeburn  9436:     }
                   9437:     return;
                   9438: }
                   9439: 
1.288     raeburn  9440: sub get_user_info {
                   9441:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9442:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9443: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9444:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9445:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9446:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9447:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9448:     return;
                   9449: }
1.275     raeburn  9450: 
1.472     raeburn  9451: ###############################################
                   9452: 
                   9453: =pod
                   9454: 
                   9455: =item * &get_user_quota()
                   9456: 
1.1075.2.41  raeburn  9457: Retrieves quota assigned for storage of user files.
                   9458: Default is to report quota for portfolio files.
1.472     raeburn  9459: 
                   9460: Incoming parameters:
                   9461: 1. user's username
                   9462: 2. user's domain
1.1075.2.41  raeburn  9463: 3. quota name - portfolio, author, or course
                   9464:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  9465: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  9466:    course
1.472     raeburn  9467: 
                   9468: Returns:
1.1075.2.58  raeburn  9469: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9470: 2. (Optional) Type of setting: custom or default
                   9471:    (individually assigned or default for user's 
                   9472:    institutional status).
                   9473: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9474:    or student - types as defined in localenroll::inst_usertypes 
                   9475:    for user's domain, which determines default quota for user.
                   9476: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9477: 
                   9478: If a value has been stored in the user's environment, 
1.536     raeburn  9479: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  9480: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9481: 
                   9482: =cut
                   9483: 
                   9484: ###############################################
                   9485: 
                   9486: 
                   9487: sub get_user_quota {
1.1075.2.42  raeburn  9488:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9489:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9490:     if (!defined($udom)) {
                   9491:         $udom = $env{'user.domain'};
                   9492:     }
                   9493:     if (!defined($uname)) {
                   9494:         $uname = $env{'user.name'};
                   9495:     }
                   9496:     if (($udom eq '' || $uname eq '') ||
                   9497:         ($udom eq 'public') && ($uname eq 'public')) {
                   9498:         $quota = 0;
1.536     raeburn  9499:         $quotatype = 'default';
                   9500:         $defquota = 0; 
1.472     raeburn  9501:     } else {
1.536     raeburn  9502:         my $inststatus;
1.1075.2.41  raeburn  9503:         if ($quotaname eq 'course') {
                   9504:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9505:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9506:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9507:             } else {
                   9508:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9509:                 $quota = $cenv{'internal.uploadquota'};
                   9510:             }
1.536     raeburn  9511:         } else {
1.1075.2.41  raeburn  9512:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9513:                 if ($quotaname eq 'author') {
                   9514:                     $quota = $env{'environment.authorquota'};
                   9515:                 } else {
                   9516:                     $quota = $env{'environment.portfolioquota'};
                   9517:                 }
                   9518:                 $inststatus = $env{'environment.inststatus'};
                   9519:             } else {
                   9520:                 my %userenv = 
                   9521:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9522:                                          'authorquota','inststatus'],$udom,$uname);
                   9523:                 my ($tmp) = keys(%userenv);
                   9524:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9525:                     if ($quotaname eq 'author') {
                   9526:                         $quota = $userenv{'authorquota'};
                   9527:                     } else {
                   9528:                         $quota = $userenv{'portfolioquota'};
                   9529:                     }
                   9530:                     $inststatus = $userenv{'inststatus'};
                   9531:                 } else {
                   9532:                     undef(%userenv);
                   9533:                 }
                   9534:             }
                   9535:         }
                   9536:         if ($quota eq '' || wantarray) {
                   9537:             if ($quotaname eq 'course') {
                   9538:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  9539:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   9540:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  9541:                     $defquota = $domdefs{$crstype.'quota'};
                   9542:                 }
                   9543:                 if ($defquota eq '') {
                   9544:                     $defquota = 500;
                   9545:                 }
1.1075.2.41  raeburn  9546:             } else {
                   9547:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9548:             }
                   9549:             if ($quota eq '') {
                   9550:                 $quota = $defquota;
                   9551:                 $quotatype = 'default';
                   9552:             } else {
                   9553:                 $quotatype = 'custom';
                   9554:             }
1.472     raeburn  9555:         }
                   9556:     }
1.536     raeburn  9557:     if (wantarray) {
                   9558:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9559:     } else {
                   9560:         return $quota;
                   9561:     }
1.472     raeburn  9562: }
                   9563: 
                   9564: ###############################################
                   9565: 
                   9566: =pod
                   9567: 
                   9568: =item * &default_quota()
                   9569: 
1.536     raeburn  9570: Retrieves default quota assigned for storage of user portfolio files,
                   9571: given an (optional) user's institutional status.
1.472     raeburn  9572: 
                   9573: Incoming parameters:
1.1075.2.42  raeburn  9574: 
1.472     raeburn  9575: 1. domain
1.536     raeburn  9576: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9577:    status types (e.g., faculty, staff, student etc.)
                   9578:    which apply to the user for whom the default is being retrieved.
                   9579:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9580:    default quota will be returned.
                   9581: 3.  quota name - portfolio, author, or course
                   9582:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9583: 
                   9584: Returns:
1.1075.2.42  raeburn  9585: 
1.1075.2.58  raeburn  9586: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9587: 2. (Optional) institutional type which determined the value of the
                   9588:    default quota.
1.472     raeburn  9589: 
                   9590: If a value has been stored in the domain's configuration db,
                   9591: it will return that, otherwise it returns 20 (for backwards 
                   9592: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9593: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9594: 
1.536     raeburn  9595: If the user's status includes multiple types (e.g., staff and student),
                   9596: the largest default quota which applies to the user determines the
                   9597: default quota returned.
                   9598: 
1.472     raeburn  9599: =cut
                   9600: 
                   9601: ###############################################
                   9602: 
                   9603: 
                   9604: sub default_quota {
1.1075.2.41  raeburn  9605:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9606:     my ($defquota,$settingstatus);
                   9607:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9608:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9609:     my $key = 'defaultquota';
                   9610:     if ($quotaname eq 'author') {
                   9611:         $key = 'authorquota';
                   9612:     }
1.622     raeburn  9613:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9614:         if ($inststatus ne '') {
1.765     raeburn  9615:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9616:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9617:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9618:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9619:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9620:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9621:                             $settingstatus = $item;
1.1075.2.41  raeburn  9622:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9623:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9624:                             $settingstatus = $item;
                   9625:                         }
                   9626:                     }
1.1075.2.41  raeburn  9627:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9628:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9629:                         if ($defquota eq '') {
                   9630:                             $defquota = $quotahash{'quotas'}{$item};
                   9631:                             $settingstatus = $item;
                   9632:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9633:                             $defquota = $quotahash{'quotas'}{$item};
                   9634:                             $settingstatus = $item;
                   9635:                         }
1.536     raeburn  9636:                     }
                   9637:                 }
                   9638:             }
                   9639:         }
                   9640:         if ($defquota eq '') {
1.1075.2.41  raeburn  9641:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9642:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9643:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9644:                 $defquota = $quotahash{'quotas'}{'default'};
                   9645:             }
1.536     raeburn  9646:             $settingstatus = 'default';
1.1075.2.42  raeburn  9647:             if ($defquota eq '') {
                   9648:                 if ($quotaname eq 'author') {
                   9649:                     $defquota = 500;
                   9650:                 }
                   9651:             }
1.536     raeburn  9652:         }
                   9653:     } else {
                   9654:         $settingstatus = 'default';
1.1075.2.41  raeburn  9655:         if ($quotaname eq 'author') {
                   9656:             $defquota = 500;
                   9657:         } else {
                   9658:             $defquota = 20;
                   9659:         }
1.536     raeburn  9660:     }
                   9661:     if (wantarray) {
                   9662:         return ($defquota,$settingstatus);
1.472     raeburn  9663:     } else {
1.536     raeburn  9664:         return $defquota;
1.472     raeburn  9665:     }
                   9666: }
                   9667: 
1.1075.2.41  raeburn  9668: ###############################################
                   9669: 
                   9670: =pod
                   9671: 
1.1075.2.42  raeburn  9672: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9673: 
                   9674: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9675: of existing file within authoring space will cause quota for the authoring
                   9676: space to be exceeded.
                   9677: 
                   9678: Same, if upload of a file directly to a course/community via Course Editor
                   9679: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9680: 
1.1075.2.61  raeburn  9681: Inputs: 7 
1.1075.2.42  raeburn  9682: 1. username or coursenum
1.1075.2.41  raeburn  9683: 2. domain
1.1075.2.42  raeburn  9684: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9685: 4. filename of file for which action is being requested
                   9686: 5. filesize (kB) of file
                   9687: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9688: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9689: 
                   9690: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9691:          otherwise return null.
                   9692: 
1.1075.2.42  raeburn  9693: =back
                   9694: 
1.1075.2.41  raeburn  9695: =cut
                   9696: 
1.1075.2.42  raeburn  9697: sub excess_filesize_warning {
1.1075.2.59  raeburn  9698:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9699:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9700:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9701:     if ($context eq 'author') {
                   9702:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9703:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9704:     } else {
                   9705:         foreach my $subdir ('docs','supplemental') {
                   9706:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9707:         }
                   9708:     }
1.1075.2.41  raeburn  9709:     $disk_quota = int($disk_quota * 1000);
                   9710:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9711:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9712:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9713:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9714:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9715:                             $disk_quota,$current_disk_usage).
                   9716:                '</p>';
                   9717:     }
                   9718:     return;
                   9719: }
                   9720: 
                   9721: ###############################################
                   9722: 
                   9723: 
1.384     raeburn  9724: sub get_secgrprole_info {
                   9725:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9726:     my %sections_count = &get_sections($cdom,$cnum);
                   9727:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9728:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9729:     my @groups = sort(keys(%curr_groups));
                   9730:     my $allroles = [];
                   9731:     my $rolehash;
                   9732:     my $accesshash = {
                   9733:                      active => 'Currently has access',
                   9734:                      future => 'Will have future access',
                   9735:                      previous => 'Previously had access',
                   9736:                   };
                   9737:     if ($needroles) {
                   9738:         $rolehash = {'all' => 'all'};
1.385     albertel 9739:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9740: 	if (&Apache::lonnet::error(%user_roles)) {
                   9741: 	    undef(%user_roles);
                   9742: 	}
                   9743:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9744:             my ($role)=split(/\:/,$item,2);
                   9745:             if ($role eq 'cr') { next; }
                   9746:             if ($role =~ /^cr/) {
                   9747:                 $$rolehash{$role} = (split('/',$role))[3];
                   9748:             } else {
                   9749:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9750:             }
                   9751:         }
                   9752:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9753:             push(@{$allroles},$key);
                   9754:         }
                   9755:         push (@{$allroles},'st');
                   9756:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9757:     }
                   9758:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9759: }
                   9760: 
1.555     raeburn  9761: sub user_picker {
1.1075.2.127  raeburn  9762:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  9763:     my $currdom = $dom;
1.1075.2.114  raeburn  9764:     my @alldoms = &Apache::lonnet::all_domains();
                   9765:     if (@alldoms == 1) {
                   9766:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   9767:                                                ['directorysrch'],$alldoms[0]);
                   9768:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   9769:         my $showdom = $domdesc;
                   9770:         if ($showdom eq '') {
                   9771:             $showdom = $dom;
                   9772:         }
                   9773:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   9774:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   9775:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   9776:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   9777:             }
                   9778:         }
                   9779:     }
1.555     raeburn  9780:     my %curr_selected = (
                   9781:                         srchin => 'dom',
1.580     raeburn  9782:                         srchby => 'lastname',
1.555     raeburn  9783:                       );
                   9784:     my $srchterm;
1.625     raeburn  9785:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9786:         if ($srch->{'srchby'} ne '') {
                   9787:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9788:         }
                   9789:         if ($srch->{'srchin'} ne '') {
                   9790:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9791:         }
                   9792:         if ($srch->{'srchtype'} ne '') {
                   9793:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9794:         }
                   9795:         if ($srch->{'srchdomain'} ne '') {
                   9796:             $currdom = $srch->{'srchdomain'};
                   9797:         }
                   9798:         $srchterm = $srch->{'srchterm'};
                   9799:     }
1.1075.2.98  raeburn  9800:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9801:                     'usr'       => 'Search criteria',
1.563     raeburn  9802:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9803:                     'uname'     => 'username',
                   9804:                     'lastname'  => 'last name',
1.555     raeburn  9805:                     'lastfirst' => 'last name, first name',
1.558     albertel 9806:                     'crs'       => 'in this course',
1.576     raeburn  9807:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9808:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9809:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9810:                     'exact'     => 'is',
                   9811:                     'contains'  => 'contains',
1.569     raeburn  9812:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  9813:                                        );
                   9814:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9815:                     'youm'      => "You must include some text to search for.",
                   9816:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9817:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9818:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9819:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9820:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9821:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9822:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9823:                                        );
1.1075.2.98  raeburn  9824:     &html_escape(\%html_lt);
                   9825:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  9826:     my $domform;
1.1075.2.126  raeburn  9827:     my $allow_blank = 1;
1.1075.2.115  raeburn  9828:     if ($fixeddom) {
1.1075.2.126  raeburn  9829:         $allow_blank = 0;
                   9830:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  9831:     } else {
1.1075.2.126  raeburn  9832:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  9833:     }
1.563     raeburn  9834:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9835: 
                   9836:     my @srchins = ('crs','dom','alc','instd');
                   9837: 
                   9838:     foreach my $option (@srchins) {
                   9839:         # FIXME 'alc' option unavailable until 
                   9840:         #       loncreateuser::print_user_query_page()
                   9841:         #       has been completed.
                   9842:         next if ($option eq 'alc');
1.880     raeburn  9843:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9844:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  9845:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  9846:         if ($curr_selected{'srchin'} eq $option) {
                   9847:             $srchinsel .= ' 
1.1075.2.98  raeburn  9848:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9849:         } else {
                   9850:             $srchinsel .= '
1.1075.2.98  raeburn  9851:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9852:         }
1.555     raeburn  9853:     }
1.563     raeburn  9854:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9855: 
                   9856:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9857:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9858:         if ($curr_selected{'srchby'} eq $option) {
                   9859:             $srchbysel .= '
1.1075.2.98  raeburn  9860:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9861:         } else {
                   9862:             $srchbysel .= '
1.1075.2.98  raeburn  9863:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9864:          }
                   9865:     }
                   9866:     $srchbysel .= "\n  </select>\n";
                   9867: 
                   9868:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9869:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9870:         if ($curr_selected{'srchtype'} eq $option) {
                   9871:             $srchtypesel .= '
1.1075.2.98  raeburn  9872:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9873:         } else {
                   9874:             $srchtypesel .= '
1.1075.2.98  raeburn  9875:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9876:         }
                   9877:     }
                   9878:     $srchtypesel .= "\n  </select>\n";
                   9879: 
1.558     albertel 9880:     my ($newuserscript,$new_user_create);
1.994     raeburn  9881:     my $context_dom = $env{'request.role.domain'};
                   9882:     if ($context eq 'requestcrs') {
                   9883:         if ($env{'form.coursedom'} ne '') { 
                   9884:             $context_dom = $env{'form.coursedom'};
                   9885:         }
                   9886:     }
1.556     raeburn  9887:     if ($forcenewuser) {
1.576     raeburn  9888:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9889:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9890:                 if ($cancreate) {
                   9891:                     $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>';
                   9892:                 } else {
1.799     bisitz   9893:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9894:                     my %usertypetext = (
                   9895:                         official   => 'institutional',
                   9896:                         unofficial => 'non-institutional',
                   9897:                     );
1.799     bisitz   9898:                     $new_user_create = '<p class="LC_warning">'
                   9899:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9900:                                       .' '
                   9901:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9902:                                           ,'<a href="'.$helplink.'">','</a>')
                   9903:                                       .'</p><br />';
1.627     raeburn  9904:                 }
1.576     raeburn  9905:             }
                   9906:         }
                   9907: 
1.556     raeburn  9908:         $newuserscript = <<"ENDSCRIPT";
                   9909: 
1.570     raeburn  9910: function setSearch(createnew,callingForm) {
1.556     raeburn  9911:     if (createnew == 1) {
1.570     raeburn  9912:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9913:             if (callingForm.srchby.options[i].value == 'uname') {
                   9914:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9915:             }
                   9916:         }
1.570     raeburn  9917:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9918:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9919: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9920:             }
                   9921:         }
1.570     raeburn  9922:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9923:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9924:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9925:             }
                   9926:         }
1.570     raeburn  9927:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9928:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9929:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9930:             }
                   9931:         }
                   9932:     }
                   9933: }
                   9934: ENDSCRIPT
1.558     albertel 9935: 
1.556     raeburn  9936:     }
                   9937: 
1.555     raeburn  9938:     my $output = <<"END_BLOCK";
1.556     raeburn  9939: <script type="text/javascript">
1.824     bisitz   9940: // <![CDATA[
1.570     raeburn  9941: function validateEntry(callingForm) {
1.558     albertel 9942: 
1.556     raeburn  9943:     var checkok = 1;
1.558     albertel 9944:     var srchin;
1.570     raeburn  9945:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9946: 	if ( callingForm.srchin[i].checked ) {
                   9947: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9948: 	}
                   9949:     }
                   9950: 
1.570     raeburn  9951:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9952:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9953:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9954:     var srchterm =  callingForm.srchterm.value;
                   9955:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9956:     var msg = "";
                   9957: 
                   9958:     if (srchterm == "") {
                   9959:         checkok = 0;
1.1075.2.98  raeburn  9960:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  9961:     }
                   9962: 
1.569     raeburn  9963:     if (srchtype== 'begins') {
                   9964:         if (srchterm.length < 2) {
                   9965:             checkok = 0;
1.1075.2.98  raeburn  9966:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  9967:         }
                   9968:     }
                   9969: 
1.556     raeburn  9970:     if (srchtype== 'contains') {
                   9971:         if (srchterm.length < 3) {
                   9972:             checkok = 0;
1.1075.2.98  raeburn  9973:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  9974:         }
                   9975:     }
                   9976:     if (srchin == 'instd') {
                   9977:         if (srchdomain == '') {
                   9978:             checkok = 0;
1.1075.2.98  raeburn  9979:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  9980:         }
                   9981:     }
                   9982:     if (srchin == 'dom') {
                   9983:         if (srchdomain == '') {
                   9984:             checkok = 0;
1.1075.2.98  raeburn  9985:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  9986:         }
                   9987:     }
                   9988:     if (srchby == 'lastfirst') {
                   9989:         if (srchterm.indexOf(",") == -1) {
                   9990:             checkok = 0;
1.1075.2.98  raeburn  9991:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  9992:         }
                   9993:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9994:             checkok = 0;
1.1075.2.98  raeburn  9995:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  9996:         }
                   9997:     }
                   9998:     if (checkok == 0) {
1.1075.2.98  raeburn  9999:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10000:         return;
                   10001:     }
                   10002:     if (checkok == 1) {
1.570     raeburn  10003:         callingForm.submit();
1.556     raeburn  10004:     }
                   10005: }
                   10006: 
                   10007: $newuserscript
                   10008: 
1.824     bisitz   10009: // ]]>
1.556     raeburn  10010: </script>
1.558     albertel 10011: 
                   10012: $new_user_create
                   10013: 
1.555     raeburn  10014: END_BLOCK
1.558     albertel 10015: 
1.876     raeburn  10016:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  10017:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10018:                $domform.
                   10019:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  10020:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10021:                $srchbysel.
                   10022:                $srchtypesel. 
                   10023:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10024:                $srchinsel.
                   10025:                &Apache::lonhtmlcommon::row_closure(1). 
                   10026:                &Apache::lonhtmlcommon::end_pick_box().
                   10027:                '<br />';
1.1075.2.114  raeburn  10028:     return ($output,1);
1.555     raeburn  10029: }
                   10030: 
1.612     raeburn  10031: sub user_rule_check {
1.615     raeburn  10032:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  10033:     my ($response,%inst_response);
1.612     raeburn  10034:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  10035:         if (keys(%{$usershash}) > 1) {
                   10036:             my (%by_username,%by_id,%userdoms);
                   10037:             my $checkid;
1.612     raeburn  10038:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  10039:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10040:                     $checkid = 1;
                   10041:                 }
                   10042:             }
                   10043:             foreach my $user (keys(%{$usershash})) {
                   10044:                 my ($uname,$udom) = split(/:/,$user);
                   10045:                 if ($checkid) {
                   10046:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10047:                         if ($usershash->{$user}->{'id'} ne '') {
                   10048:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   10049:                             $userdoms{$udom} = 1;
                   10050:                             if (ref($inst_results) eq 'HASH') {
                   10051:                                 $inst_results->{$uname.':'.$udom} = {};
                   10052:                             }
                   10053:                         }
                   10054:                     }
                   10055:                 } else {
                   10056:                     $by_username{$udom}{$uname} = 1;
                   10057:                     $userdoms{$udom} = 1;
                   10058:                     if (ref($inst_results) eq 'HASH') {
                   10059:                         $inst_results->{$uname.':'.$udom} = {};
                   10060:                     }
                   10061:                 }
                   10062:             }
                   10063:             foreach my $udom (keys(%userdoms)) {
                   10064:                 if (!$got_rules->{$udom}) {
                   10065:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10066:                                                              ['usercreation'],$udom);
                   10067:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10068:                         foreach my $item ('username','id') {
                   10069:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10070:                                 $$curr_rules{$udom}{$item} =
                   10071:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   10072:                             }
                   10073:                         }
                   10074:                     }
                   10075:                     $got_rules->{$udom} = 1;
                   10076:                 }
                   10077:             }
                   10078:             if ($checkid) {
                   10079:                 foreach my $udom (keys(%by_id)) {
                   10080:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10081:                     if ($outcome eq 'ok') {
                   10082:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10083:                             my $uname = $by_id{$udom}{$id};
                   10084:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10085:                         }
                   10086:                         if (ref($results) eq 'HASH') {
                   10087:                             foreach my $uname (keys(%{$results})) {
                   10088:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10089:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10090:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10091:                                 }
                   10092:                             }
                   10093:                         }
                   10094:                     }
1.612     raeburn  10095:                 }
1.615     raeburn  10096:             } else {
1.1075.2.99  raeburn  10097:                 foreach my $udom (keys(%by_username)) {
                   10098:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10099:                     if ($outcome eq 'ok') {
                   10100:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10101:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10102:                         }
                   10103:                         if (ref($results) eq 'HASH') {
                   10104:                             foreach my $uname (keys(%{$results})) {
                   10105:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10106:                             }
                   10107:                         }
                   10108:                     }
                   10109:                 }
1.612     raeburn  10110:             }
1.1075.2.99  raeburn  10111:         } elsif (keys(%{$usershash}) == 1) {
                   10112:             my $user = (keys(%{$usershash}))[0];
                   10113:             my ($uname,$udom) = split(/:/,$user);
                   10114:             if (($udom ne '') && ($uname ne '')) {
                   10115:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10116:                     if (ref($checks) eq 'HASH') {
                   10117:                         if (defined($checks->{'username'})) {
                   10118:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   10119:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10120:                         } elsif (defined($checks->{'id'})) {
                   10121:                             if ($usershash->{$user}->{'id'} ne '') {
                   10122:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10123:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10124:                                                                   $usershash->{$user}->{'id'});
                   10125:                             } else {
                   10126:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10127:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10128:                             }
                   10129:                         }
                   10130:                     } else {
                   10131:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10132:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10133:                        return;
                   10134:                     }
                   10135:                     if (!$got_rules->{$udom}) {
                   10136:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10137:                                                                  ['usercreation'],$udom);
                   10138:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10139:                             foreach my $item ('username','id') {
                   10140:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10141:                                    $$curr_rules{$udom}{$item} =
                   10142:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10143:                                 }
                   10144:                             }
1.585     raeburn  10145:                         }
1.1075.2.99  raeburn  10146:                         $got_rules->{$udom} = 1;
1.585     raeburn  10147:                     }
                   10148:                 }
1.1075.2.99  raeburn  10149:             } else {
                   10150:                 return;
                   10151:             }
                   10152:         } else {
                   10153:             return;
                   10154:         }
                   10155:         foreach my $user (keys(%{$usershash})) {
                   10156:             my ($uname,$udom) = split(/:/,$user);
                   10157:             next if (($udom eq '') || ($uname eq ''));
                   10158:             my $id;
                   10159:             if (ref($inst_results) eq 'HASH') {
                   10160:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10161:                     $id = $inst_results->{$user}->{'id'};
                   10162:                 }
                   10163:             }
                   10164:             if ($id eq '') {
                   10165:                 if (ref($usershash->{$user})) {
                   10166:                     $id = $usershash->{$user}->{'id'};
                   10167:                 }
1.585     raeburn  10168:             }
1.612     raeburn  10169:             foreach my $item (keys(%{$checks})) {
                   10170:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10171:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10172:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  10173:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10174:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10175:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10176:                                 if ($rule_check{$rule}) {
                   10177:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  10178:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10179:                                         if (ref($inst_results) eq 'HASH') {
                   10180:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10181:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10182:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  10183:                                                 } elsif ($item eq 'id') {
                   10184:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10185:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10186:                                                     }
1.615     raeburn  10187:                                                 }
1.612     raeburn  10188:                                             }
                   10189:                                         }
1.615     raeburn  10190:                                     }
                   10191:                                     last;
1.585     raeburn  10192:                                 }
                   10193:                             }
                   10194:                         }
                   10195:                     }
                   10196:                 }
                   10197:             }
                   10198:         }
                   10199:     }
1.612     raeburn  10200:     return;
                   10201: }
                   10202: 
                   10203: sub user_rule_formats {
                   10204:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10205:     my %text = ( 
                   10206:                  'username' => 'Usernames',
                   10207:                  'id'       => 'IDs',
                   10208:                );
                   10209:     my $output;
                   10210:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10211:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10212:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  10213:             $output = '<br />'.
                   10214:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10215:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10216:                       ' <ul>';
1.612     raeburn  10217:             foreach my $rule (@{$ruleorder}) {
                   10218:                 if (ref($curr_rules) eq 'ARRAY') {
                   10219:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10220:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10221:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10222:                                         $rules->{$rule}{'desc'}.'</li>';
                   10223:                         }
                   10224:                     }
                   10225:                 }
                   10226:             }
                   10227:             $output .= '</ul>';
                   10228:         }
                   10229:     }
                   10230:     return $output;
                   10231: }
                   10232: 
                   10233: sub instrule_disallow_msg {
1.615     raeburn  10234:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10235:     my $response;
                   10236:     my %text = (
                   10237:                   item   => 'username',
                   10238:                   items  => 'usernames',
                   10239:                   match  => 'matches',
                   10240:                   do     => 'does',
                   10241:                   action => 'a username',
                   10242:                   one    => 'one',
                   10243:                );
                   10244:     if ($count > 1) {
                   10245:         $text{'item'} = 'usernames';
                   10246:         $text{'match'} ='match';
                   10247:         $text{'do'} = 'do';
                   10248:         $text{'action'} = 'usernames',
                   10249:         $text{'one'} = 'ones';
                   10250:     }
                   10251:     if ($checkitem eq 'id') {
                   10252:         $text{'items'} = 'IDs';
                   10253:         $text{'item'} = 'ID';
                   10254:         $text{'action'} = 'an ID';
1.615     raeburn  10255:         if ($count > 1) {
                   10256:             $text{'item'} = 'IDs';
                   10257:             $text{'action'} = 'IDs';
                   10258:         }
1.612     raeburn  10259:     }
1.674     bisitz   10260:     $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  10261:     if ($mode eq 'upload') {
                   10262:         if ($checkitem eq 'username') {
                   10263:             $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'}.");
                   10264:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10265:             $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  10266:         }
1.669     raeburn  10267:     } elsif ($mode eq 'selfcreate') {
                   10268:         if ($checkitem eq 'id') {
                   10269:             $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.");
                   10270:         }
1.615     raeburn  10271:     } else {
                   10272:         if ($checkitem eq 'username') {
                   10273:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10274:         } elsif ($checkitem eq 'id') {
                   10275:             $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.");
                   10276:         }
1.612     raeburn  10277:     }
                   10278:     return $response;
1.585     raeburn  10279: }
                   10280: 
1.624     raeburn  10281: sub personal_data_fieldtitles {
                   10282:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10283:                         id => 'Student/Employee ID',
                   10284:                         permanentemail => 'E-mail address',
                   10285:                         lastname => 'Last Name',
                   10286:                         firstname => 'First Name',
                   10287:                         middlename => 'Middle Name',
                   10288:                         generation => 'Generation',
                   10289:                         gen => 'Generation',
1.765     raeburn  10290:                         inststatus => 'Affiliation',
1.624     raeburn  10291:                    );
                   10292:     return %fieldtitles;
                   10293: }
                   10294: 
1.642     raeburn  10295: sub sorted_inst_types {
                   10296:     my ($dom) = @_;
1.1075.2.70  raeburn  10297:     my ($usertypes,$order);
                   10298:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10299:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10300:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10301:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10302:     } else {
                   10303:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10304:     }
1.642     raeburn  10305:     my $othertitle = &mt('All users');
                   10306:     if ($env{'request.course.id'}) {
1.668     raeburn  10307:         $othertitle  = &mt('Any users');
1.642     raeburn  10308:     }
                   10309:     my @types;
                   10310:     if (ref($order) eq 'ARRAY') {
                   10311:         @types = @{$order};
                   10312:     }
                   10313:     if (@types == 0) {
                   10314:         if (ref($usertypes) eq 'HASH') {
                   10315:             @types = sort(keys(%{$usertypes}));
                   10316:         }
                   10317:     }
                   10318:     if (keys(%{$usertypes}) > 0) {
                   10319:         $othertitle = &mt('Other users');
                   10320:     }
                   10321:     return ($othertitle,$usertypes,\@types);
                   10322: }
                   10323: 
1.645     raeburn  10324: sub get_institutional_codes {
                   10325:     my ($settings,$allcourses,$LC_code) = @_;
                   10326: # Get complete list of course sections to update
                   10327:     my @currsections = ();
                   10328:     my @currxlists = ();
                   10329:     my $coursecode = $$settings{'internal.coursecode'};
                   10330: 
                   10331:     if ($$settings{'internal.sectionnums'} ne '') {
                   10332:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10333:     }
                   10334: 
                   10335:     if ($$settings{'internal.crosslistings'} ne '') {
                   10336:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10337:     }
                   10338: 
                   10339:     if (@currxlists > 0) {
                   10340:         foreach (@currxlists) {
                   10341:             if (m/^([^:]+):(\w*)$/) {
                   10342:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  10343:                     push(@{$allcourses},$1);
1.645     raeburn  10344:                     $$LC_code{$1} = $2;
                   10345:                 }
                   10346:             }
                   10347:         }
                   10348:     }
                   10349:  
                   10350:     if (@currsections > 0) {
                   10351:         foreach (@currsections) {
                   10352:             if (m/^(\w+):(\w*)$/) {
                   10353:                 my $sec = $coursecode.$1;
                   10354:                 my $lc_sec = $2;
                   10355:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1075.2.119  raeburn  10356:                     push(@{$allcourses},$sec);
1.645     raeburn  10357:                     $$LC_code{$sec} = $lc_sec;
                   10358:                 }
                   10359:             }
                   10360:         }
                   10361:     }
                   10362:     return;
                   10363: }
                   10364: 
1.971     raeburn  10365: sub get_standard_codeitems {
                   10366:     return ('Year','Semester','Department','Number','Section');
                   10367: }
                   10368: 
1.112     bowersj2 10369: =pod
                   10370: 
1.780     raeburn  10371: =head1 Slot Helpers
                   10372: 
                   10373: =over 4
                   10374: 
                   10375: =item * sorted_slots()
                   10376: 
1.1040    raeburn  10377: Sorts an array of slot names in order of an optional sort key,
                   10378: default sort is by slot start time (earliest first). 
1.780     raeburn  10379: 
                   10380: Inputs:
                   10381: 
                   10382: =over 4
                   10383: 
                   10384: slotsarr  - Reference to array of unsorted slot names.
                   10385: 
                   10386: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10387: 
1.1040    raeburn  10388: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10389: 
1.549     albertel 10390: =back
                   10391: 
1.780     raeburn  10392: Returns:
                   10393: 
                   10394: =over 4
                   10395: 
1.1040    raeburn  10396: sorted   - An array of slot names sorted by a specified sort key 
                   10397:            (default sort key is start time of the slot).
1.780     raeburn  10398: 
                   10399: =back
                   10400: 
                   10401: =cut
                   10402: 
                   10403: 
                   10404: sub sorted_slots {
1.1040    raeburn  10405:     my ($slotsarr,$slots,$sortkey) = @_;
                   10406:     if ($sortkey eq '') {
                   10407:         $sortkey = 'starttime';
                   10408:     }
1.780     raeburn  10409:     my @sorted;
                   10410:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10411:         @sorted =
                   10412:             sort {
                   10413:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10414:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10415:                      }
                   10416:                      if (ref($slots->{$a})) { return -1;}
                   10417:                      if (ref($slots->{$b})) { return 1;}
                   10418:                      return 0;
                   10419:                  } @{$slotsarr};
                   10420:     }
                   10421:     return @sorted;
                   10422: }
                   10423: 
1.1040    raeburn  10424: =pod
                   10425: 
                   10426: =item * get_future_slots()
                   10427: 
                   10428: Inputs:
                   10429: 
                   10430: =over 4
                   10431: 
                   10432: cnum - course number
                   10433: 
                   10434: cdom - course domain
                   10435: 
                   10436: now - current UNIX time
                   10437: 
                   10438: symb - optional symb
                   10439: 
                   10440: =back
                   10441: 
                   10442: Returns:
                   10443: 
                   10444: =over 4
                   10445: 
                   10446: sorted_reservable - ref to array of student_schedulable slots currently 
                   10447:                     reservable, ordered by end date of reservation period.
                   10448: 
                   10449: reservable_now - ref to hash of student_schedulable slots currently
                   10450:                  reservable.
                   10451: 
                   10452:     Keys in inner hash are:
                   10453:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  10454:     (b) endreserve: end date of reservation period.
                   10455:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10456:         selected.
1.1040    raeburn  10457: 
                   10458: sorted_future - ref to array of student_schedulable slots reservable in
                   10459:                 the future, ordered by start date of reservation period.
                   10460: 
                   10461: future_reservable - ref to hash of student_schedulable slots reservable
                   10462:                     in the future.
                   10463: 
                   10464:     Keys in inner hash are:
                   10465:     (a) symb: either blank or symb to which slot use is restricted.
                   10466:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  10467:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10468:         selected.
1.1040    raeburn  10469: 
                   10470: =back
                   10471: 
                   10472: =cut
                   10473: 
                   10474: sub get_future_slots {
                   10475:     my ($cnum,$cdom,$now,$symb) = @_;
                   10476:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10477:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10478:     foreach my $slot (keys(%slots)) {
                   10479:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10480:         if ($symb) {
                   10481:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10482:                      ($slots{$slot}->{'symb'} ne $symb));
                   10483:         }
                   10484:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10485:             ($slots{$slot}->{'endtime'} > $now)) {
                   10486:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10487:                 my $userallowed = 0;
                   10488:                 if ($slots{$slot}->{'allowedsections'}) {
                   10489:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10490:                     if (!defined($env{'request.role.sec'})
                   10491:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10492:                         $userallowed=1;
                   10493:                     } else {
                   10494:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10495:                             $userallowed=1;
                   10496:                         }
                   10497:                     }
                   10498:                     unless ($userallowed) {
                   10499:                         if (defined($env{'request.course.groups'})) {
                   10500:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10501:                             foreach my $group (@groups) {
                   10502:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10503:                                     $userallowed=1;
                   10504:                                     last;
                   10505:                                 }
                   10506:                             }
                   10507:                         }
                   10508:                     }
                   10509:                 }
                   10510:                 if ($slots{$slot}->{'allowedusers'}) {
                   10511:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10512:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10513:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10514:                         $userallowed = 1;
                   10515:                     }
                   10516:                 }
                   10517:                 next unless($userallowed);
                   10518:             }
                   10519:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10520:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10521:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  10522:             my $uniqueperiod;
                   10523:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10524:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10525:             }
1.1040    raeburn  10526:             if (($startreserve < $now) &&
                   10527:                 (!$endreserve || $endreserve > $now)) {
                   10528:                 my $lastres = $endreserve;
                   10529:                 if (!$lastres) {
                   10530:                     $lastres = $slots{$slot}->{'starttime'};
                   10531:                 }
                   10532:                 $reservable_now{$slot} = {
                   10533:                                            symb       => $symb,
1.1075.2.104  raeburn  10534:                                            endreserve => $lastres,
                   10535:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  10536:                                          };
                   10537:             } elsif (($startreserve > $now) &&
                   10538:                      (!$endreserve || $endreserve > $startreserve)) {
                   10539:                 $future_reservable{$slot} = {
                   10540:                                               symb         => $symb,
1.1075.2.104  raeburn  10541:                                               startreserve => $startreserve,
                   10542:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10543:                                             };
                   10544:             }
                   10545:         }
                   10546:     }
                   10547:     my @unsorted_reservable = keys(%reservable_now);
                   10548:     if (@unsorted_reservable > 0) {
                   10549:         @sorted_reservable = 
                   10550:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10551:     }
                   10552:     my @unsorted_future = keys(%future_reservable);
                   10553:     if (@unsorted_future > 0) {
                   10554:         @sorted_future =
                   10555:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10556:     }
                   10557:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10558: }
1.780     raeburn  10559: 
                   10560: =pod
                   10561: 
1.1057    foxr     10562: =back
                   10563: 
1.549     albertel 10564: =head1 HTTP Helpers
                   10565: 
                   10566: =over 4
                   10567: 
1.648     raeburn  10568: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10569: 
1.258     albertel 10570: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10571: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10572: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10573: 
                   10574: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10575: $possible_names is an ref to an array of form element names.  As an example:
                   10576: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10577: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10578: 
                   10579: =cut
1.1       albertel 10580: 
1.6       albertel 10581: sub get_unprocessed_cgi {
1.25      albertel 10582:   my ($query,$possible_names)= @_;
1.26      matthew  10583:   # $Apache::lonxml::debug=1;
1.356     albertel 10584:   foreach my $pair (split(/&/,$query)) {
                   10585:     my ($name, $value) = split(/=/,$pair);
1.369     www      10586:     $name = &unescape($name);
1.25      albertel 10587:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10588:       $value =~ tr/+/ /;
                   10589:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10590:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10591:     }
1.16      harris41 10592:   }
1.6       albertel 10593: }
                   10594: 
1.112     bowersj2 10595: =pod
                   10596: 
1.648     raeburn  10597: =item * &cacheheader() 
1.112     bowersj2 10598: 
                   10599: returns cache-controlling header code
                   10600: 
                   10601: =cut
                   10602: 
1.7       albertel 10603: sub cacheheader {
1.258     albertel 10604:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10605:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10606:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10607:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10608:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10609:     return $output;
1.7       albertel 10610: }
                   10611: 
1.112     bowersj2 10612: =pod
                   10613: 
1.648     raeburn  10614: =item * &no_cache($r) 
1.112     bowersj2 10615: 
                   10616: specifies header code to not have cache
                   10617: 
                   10618: =cut
                   10619: 
1.9       albertel 10620: sub no_cache {
1.216     albertel 10621:     my ($r) = @_;
                   10622:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10623: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10624:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10625:     $r->no_cache(1);
                   10626:     $r->header_out("Expires" => $date);
                   10627:     $r->header_out("Pragma" => "no-cache");
1.123     www      10628: }
                   10629: 
                   10630: sub content_type {
1.181     albertel 10631:     my ($r,$type,$charset) = @_;
1.299     foxr     10632:     if ($r) {
                   10633: 	#  Note that printout.pl calls this with undef for $r.
                   10634: 	&no_cache($r);
                   10635:     }
1.258     albertel 10636:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10637:     unless ($charset) {
                   10638: 	$charset=&Apache::lonlocal::current_encoding;
                   10639:     }
                   10640:     if ($charset) { $type.='; charset='.$charset; }
                   10641:     if ($r) {
                   10642: 	$r->content_type($type);
                   10643:     } else {
                   10644: 	print("Content-type: $type\n\n");
                   10645:     }
1.9       albertel 10646: }
1.25      albertel 10647: 
1.112     bowersj2 10648: =pod
                   10649: 
1.648     raeburn  10650: =item * &add_to_env($name,$value) 
1.112     bowersj2 10651: 
1.258     albertel 10652: adds $name to the %env hash with value
1.112     bowersj2 10653: $value, if $name already exists, the entry is converted to an array
                   10654: reference and $value is added to the array.
                   10655: 
                   10656: =cut
                   10657: 
1.25      albertel 10658: sub add_to_env {
                   10659:   my ($name,$value)=@_;
1.258     albertel 10660:   if (defined($env{$name})) {
                   10661:     if (ref($env{$name})) {
1.25      albertel 10662:       #already have multiple values
1.258     albertel 10663:       push(@{ $env{$name} },$value);
1.25      albertel 10664:     } else {
                   10665:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10666:       my $first=$env{$name};
                   10667:       undef($env{$name});
                   10668:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10669:     }
                   10670:   } else {
1.258     albertel 10671:     $env{$name}=$value;
1.25      albertel 10672:   }
1.31      albertel 10673: }
1.149     albertel 10674: 
                   10675: =pod
                   10676: 
1.648     raeburn  10677: =item * &get_env_multiple($name) 
1.149     albertel 10678: 
1.258     albertel 10679: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10680: values may be defined and end up as an array ref.
                   10681: 
                   10682: returns an array of values
                   10683: 
                   10684: =cut
                   10685: 
                   10686: sub get_env_multiple {
                   10687:     my ($name) = @_;
                   10688:     my @values;
1.258     albertel 10689:     if (defined($env{$name})) {
1.149     albertel 10690:         # exists is it an array
1.258     albertel 10691:         if (ref($env{$name})) {
                   10692:             @values=@{ $env{$name} };
1.149     albertel 10693:         } else {
1.258     albertel 10694:             $values[0]=$env{$name};
1.149     albertel 10695:         }
                   10696:     }
                   10697:     return(@values);
                   10698: }
                   10699: 
1.660     raeburn  10700: sub ask_for_embedded_content {
                   10701:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10702:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  10703:         %currsubfile,%unused,$rem);
1.1071    raeburn  10704:     my $counter = 0;
                   10705:     my $numnew = 0;
1.987     raeburn  10706:     my $numremref = 0;
                   10707:     my $numinvalid = 0;
                   10708:     my $numpathchg = 0;
                   10709:     my $numexisting = 0;
1.1071    raeburn  10710:     my $numunused = 0;
                   10711:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10712:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10713:     my $heading = &mt('Upload embedded files');
                   10714:     my $buttontext = &mt('Upload');
                   10715: 
1.1075.2.11  raeburn  10716:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10717:         if ($actionurl eq '/adm/dependencies') {
                   10718:             $navmap = Apache::lonnavmaps::navmap->new();
                   10719:         }
                   10720:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10721:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10722:     }
1.1075.2.35  raeburn  10723:     if (($actionurl eq '/adm/portfolio') ||
                   10724:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10725:         my $current_path='/';
                   10726:         if ($env{'form.currentpath'}) {
                   10727:             $current_path = $env{'form.currentpath'};
                   10728:         }
                   10729:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10730:             $udom = $cdom;
                   10731:             $uname = $cnum;
1.984     raeburn  10732:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10733:         } else {
                   10734:             $udom = $env{'user.domain'};
                   10735:             $uname = $env{'user.name'};
                   10736:             $url = '/userfiles/portfolio';
                   10737:         }
1.987     raeburn  10738:         $toplevel = $url.'/';
1.984     raeburn  10739:         $url .= $current_path;
                   10740:         $getpropath = 1;
1.987     raeburn  10741:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10742:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10743:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10744:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10745:         $toplevel = $url;
1.984     raeburn  10746:         if ($rest ne '') {
1.987     raeburn  10747:             $url .= $rest;
                   10748:         }
                   10749:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10750:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10751:             $url = $args->{'docs_url'};
                   10752:             $toplevel = $url;
1.1075.2.11  raeburn  10753:             if ($args->{'context'} eq 'paste') {
                   10754:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10755:                 ($path) =
                   10756:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10757:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10758:                 $fileloc =~ s{^/}{};
                   10759:             }
1.1071    raeburn  10760:         }
                   10761:     } elsif ($actionurl eq '/adm/dependencies') {
                   10762:         if ($env{'request.course.id'} ne '') {
                   10763:             if (ref($args) eq 'HASH') {
                   10764:                 $url = $args->{'docs_url'};
                   10765:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  10766:                 $toplevel = $url;
                   10767:                 unless ($toplevel =~ m{^/}) {
                   10768:                     $toplevel = "/$url";
                   10769:                 }
1.1075.2.11  raeburn  10770:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  10771:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10772:                     $path = $1;
                   10773:                 } else {
                   10774:                     ($path) =
                   10775:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10776:                 }
1.1075.2.79  raeburn  10777:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10778:                     $fileloc = $toplevel;
                   10779:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10780:                     my ($udom,$uname,$fname) =
                   10781:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10782:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10783:                 } else {
                   10784:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10785:                 }
1.1071    raeburn  10786:                 $fileloc =~ s{^/}{};
                   10787:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10788:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10789:             }
1.987     raeburn  10790:         }
1.1075.2.35  raeburn  10791:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10792:         $udom = $cdom;
                   10793:         $uname = $cnum;
                   10794:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10795:         $toplevel = $url;
                   10796:         $path = $url;
                   10797:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10798:         $fileloc =~ s{^/}{};
                   10799:     }
                   10800:     foreach my $file (keys(%{$allfiles})) {
                   10801:         my $embed_file;
                   10802:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10803:             $embed_file = $1;
                   10804:         } else {
                   10805:             $embed_file = $file;
                   10806:         }
1.1075.2.55  raeburn  10807:         my ($absolutepath,$cleaned_file);
                   10808:         if ($embed_file =~ m{^\w+://}) {
                   10809:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  10810:             $newfiles{$cleaned_file} = 1;
                   10811:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10812:         } else {
1.1075.2.55  raeburn  10813:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10814:             if ($embed_file =~ m{^/}) {
                   10815:                 $absolutepath = $embed_file;
                   10816:             }
1.1075.2.47  raeburn  10817:             if ($cleaned_file =~ m{/}) {
                   10818:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10819:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10820:                 my $item = $fname;
                   10821:                 if ($path ne '') {
                   10822:                     $item = $path.'/'.$fname;
                   10823:                     $subdependencies{$path}{$fname} = 1;
                   10824:                 } else {
                   10825:                     $dependencies{$item} = 1;
                   10826:                 }
                   10827:                 if ($absolutepath) {
                   10828:                     $mapping{$item} = $absolutepath;
                   10829:                 } else {
                   10830:                     $mapping{$item} = $embed_file;
                   10831:                 }
                   10832:             } else {
                   10833:                 $dependencies{$embed_file} = 1;
                   10834:                 if ($absolutepath) {
1.1075.2.47  raeburn  10835:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10836:                 } else {
1.1075.2.47  raeburn  10837:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10838:                 }
                   10839:             }
1.984     raeburn  10840:         }
                   10841:     }
1.1071    raeburn  10842:     my $dirptr = 16384;
1.984     raeburn  10843:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10844:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  10845:         if (($actionurl eq '/adm/portfolio') ||
                   10846:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  10847:             my ($sublistref,$listerror) =
                   10848:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10849:             if (ref($sublistref) eq 'ARRAY') {
                   10850:                 foreach my $line (@{$sublistref}) {
                   10851:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10852:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10853:                 }
1.984     raeburn  10854:             }
1.987     raeburn  10855:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10856:             if (opendir(my $dir,$url.'/'.$path)) {
                   10857:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10858:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10859:             }
1.1075.2.11  raeburn  10860:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10861:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10862:                   ($args->{'context'} eq 'paste')) ||
                   10863:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10864:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  10865:                 my $dir;
                   10866:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10867:                     $dir = $fileloc;
                   10868:                 } else {
                   10869:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10870:                 }
1.1071    raeburn  10871:                 if ($dir ne '') {
                   10872:                     my ($sublistref,$listerror) =
                   10873:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10874:                     if (ref($sublistref) eq 'ARRAY') {
                   10875:                         foreach my $line (@{$sublistref}) {
                   10876:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10877:                                 undef,$mtime)=split(/\&/,$line,12);
                   10878:                             unless (($testdir&$dirptr) ||
                   10879:                                     ($file_name =~ /^\.\.?$/)) {
                   10880:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10881:                             }
                   10882:                         }
                   10883:                     }
                   10884:                 }
1.984     raeburn  10885:             }
                   10886:         }
                   10887:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10888:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10889:                 my $item = $path.'/'.$file;
                   10890:                 unless ($mapping{$item} eq $item) {
                   10891:                     $pathchanges{$item} = 1;
                   10892:                 }
                   10893:                 $existing{$item} = 1;
                   10894:                 $numexisting ++;
                   10895:             } else {
                   10896:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10897:             }
                   10898:         }
1.1071    raeburn  10899:         if ($actionurl eq '/adm/dependencies') {
                   10900:             foreach my $path (keys(%currsubfile)) {
                   10901:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10902:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10903:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  10904:                              next if (($rem ne '') &&
                   10905:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10906:                                        (ref($navmap) &&
                   10907:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10908:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10909:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10910:                              $unused{$path.'/'.$file} = 1; 
                   10911:                          }
                   10912:                     }
                   10913:                 }
                   10914:             }
                   10915:         }
1.984     raeburn  10916:     }
1.987     raeburn  10917:     my %currfile;
1.1075.2.35  raeburn  10918:     if (($actionurl eq '/adm/portfolio') ||
                   10919:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10920:         my ($dirlistref,$listerror) =
                   10921:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10922:         if (ref($dirlistref) eq 'ARRAY') {
                   10923:             foreach my $line (@{$dirlistref}) {
                   10924:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10925:                 $currfile{$file_name} = 1;
                   10926:             }
1.984     raeburn  10927:         }
1.987     raeburn  10928:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10929:         if (opendir(my $dir,$url)) {
1.987     raeburn  10930:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10931:             map {$currfile{$_} = 1;} @dir_list;
                   10932:         }
1.1075.2.11  raeburn  10933:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10934:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10935:               ($args->{'context'} eq 'paste')) ||
                   10936:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10937:         if ($env{'request.course.id'} ne '') {
                   10938:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10939:             if ($dir ne '') {
                   10940:                 my ($dirlistref,$listerror) =
                   10941:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10942:                 if (ref($dirlistref) eq 'ARRAY') {
                   10943:                     foreach my $line (@{$dirlistref}) {
                   10944:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10945:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10946:                         unless (($testdir&$dirptr) ||
                   10947:                                 ($file_name =~ /^\.\.?$/)) {
                   10948:                             $currfile{$file_name} = [$size,$mtime];
                   10949:                         }
                   10950:                     }
                   10951:                 }
                   10952:             }
                   10953:         }
1.984     raeburn  10954:     }
                   10955:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10956:         if (exists($currfile{$file})) {
1.987     raeburn  10957:             unless ($mapping{$file} eq $file) {
                   10958:                 $pathchanges{$file} = 1;
                   10959:             }
                   10960:             $existing{$file} = 1;
                   10961:             $numexisting ++;
                   10962:         } else {
1.984     raeburn  10963:             $newfiles{$file} = 1;
                   10964:         }
                   10965:     }
1.1071    raeburn  10966:     foreach my $file (keys(%currfile)) {
                   10967:         unless (($file eq $filename) ||
                   10968:                 ($file eq $filename.'.bak') ||
                   10969:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  10970:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  10971:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10972:                     next if (($rem ne '') &&
                   10973:                              (($env{"httpref.$rem".$file} ne '') ||
                   10974:                               (ref($navmap) &&
                   10975:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10976:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10977:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10978:                 }
1.1075.2.11  raeburn  10979:             }
1.1071    raeburn  10980:             $unused{$file} = 1;
                   10981:         }
                   10982:     }
1.1075.2.11  raeburn  10983:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10984:         ($args->{'context'} eq 'paste')) {
                   10985:         $counter = scalar(keys(%existing));
                   10986:         $numpathchg = scalar(keys(%pathchanges));
                   10987:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  10988:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   10989:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10990:         $counter = scalar(keys(%existing));
                   10991:         $numpathchg = scalar(keys(%pathchanges));
                   10992:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  10993:     }
1.984     raeburn  10994:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10995:         if ($actionurl eq '/adm/dependencies') {
                   10996:             next if ($embed_file =~ m{^\w+://});
                   10997:         }
1.660     raeburn  10998:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10999:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11000:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11001:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  11002:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11003:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11004:         }
1.1075.2.35  raeburn  11005:         $upload_output .= '</td>';
1.1071    raeburn  11006:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  11007:             $upload_output.='<td align="right">'.
                   11008:                             '<span class="LC_info LC_fontsize_medium">'.
                   11009:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11010:             $numremref++;
1.660     raeburn  11011:         } elsif ($args->{'error_on_invalid_names'}
                   11012:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  11013:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11014:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11015:             $numinvalid++;
1.660     raeburn  11016:         } else {
1.1075.2.35  raeburn  11017:             $upload_output .= '<td>'.
                   11018:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11019:                                                      $embed_file,\%mapping,
1.1071    raeburn  11020:                                                      $allfiles,$codebase,'upload');
                   11021:             $counter ++;
                   11022:             $numnew ++;
1.987     raeburn  11023:         }
                   11024:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11025:     }
                   11026:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11027:         if ($actionurl eq '/adm/dependencies') {
                   11028:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11029:             $modify_output .= &start_data_table_row().
                   11030:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11031:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11032:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11033:                               '<td>'.$size.'</td>'.
                   11034:                               '<td>'.$mtime.'</td>'.
                   11035:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11036:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11037:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11038:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11039:                               &embedded_file_element('upload_embedded',$counter,
                   11040:                                                      $embed_file,\%mapping,
                   11041:                                                      $allfiles,$codebase,'modify').
                   11042:                               '</div></td>'.
                   11043:                               &end_data_table_row()."\n";
                   11044:             $counter ++;
                   11045:         } else {
                   11046:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11047:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11048:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11049:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11050:                               &Apache::loncommon::end_data_table_row()."\n";
                   11051:         }
                   11052:     }
                   11053:     my $delidx = $counter;
                   11054:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11055:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11056:         $delete_output .= &start_data_table_row().
                   11057:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11058:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11059:                           '<td>'.$size.'</td>'.
                   11060:                           '<td>'.$mtime.'</td>'.
                   11061:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11062:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11063:                           &embedded_file_element('upload_embedded',$delidx,
                   11064:                                                  $oldfile,\%mapping,$allfiles,
                   11065:                                                  $codebase,'delete').'</td>'.
                   11066:                           &end_data_table_row()."\n"; 
                   11067:         $numunused ++;
                   11068:         $delidx ++;
1.987     raeburn  11069:     }
                   11070:     if ($upload_output) {
                   11071:         $upload_output = &start_data_table().
                   11072:                          $upload_output.
                   11073:                          &end_data_table()."\n";
                   11074:     }
1.1071    raeburn  11075:     if ($modify_output) {
                   11076:         $modify_output = &start_data_table().
                   11077:                          &start_data_table_header_row().
                   11078:                          '<th>'.&mt('File').'</th>'.
                   11079:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11080:                          '<th>'.&mt('Modified').'</th>'.
                   11081:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11082:                          &end_data_table_header_row().
                   11083:                          $modify_output.
                   11084:                          &end_data_table()."\n";
                   11085:     }
                   11086:     if ($delete_output) {
                   11087:         $delete_output = &start_data_table().
                   11088:                          &start_data_table_header_row().
                   11089:                          '<th>'.&mt('File').'</th>'.
                   11090:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11091:                          '<th>'.&mt('Modified').'</th>'.
                   11092:                          '<th>'.&mt('Delete?').'</th>'.
                   11093:                          &end_data_table_header_row().
                   11094:                          $delete_output.
                   11095:                          &end_data_table()."\n";
                   11096:     }
1.987     raeburn  11097:     my $applies = 0;
                   11098:     if ($numremref) {
                   11099:         $applies ++;
                   11100:     }
                   11101:     if ($numinvalid) {
                   11102:         $applies ++;
                   11103:     }
                   11104:     if ($numexisting) {
                   11105:         $applies ++;
                   11106:     }
1.1071    raeburn  11107:     if ($counter || $numunused) {
1.987     raeburn  11108:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11109:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11110:                   $state.'<h3>'.$heading.'</h3>'; 
                   11111:         if ($actionurl eq '/adm/dependencies') {
                   11112:             if ($numnew) {
                   11113:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11114:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11115:                            $upload_output.'<br />'."\n";
                   11116:             }
                   11117:             if ($numexisting) {
                   11118:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11119:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11120:                            $modify_output.'<br />'."\n";
                   11121:                            $buttontext = &mt('Save changes');
                   11122:             }
                   11123:             if ($numunused) {
                   11124:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11125:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11126:                            $delete_output.'<br />'."\n";
                   11127:                            $buttontext = &mt('Save changes');
                   11128:             }
                   11129:         } else {
                   11130:             $output .= $upload_output.'<br />'."\n";
                   11131:         }
                   11132:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11133:                    $counter.'" />'."\n";
                   11134:         if ($actionurl eq '/adm/dependencies') { 
                   11135:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11136:                        $numnew.'" />'."\n";
                   11137:         } elsif ($actionurl eq '') {
1.987     raeburn  11138:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11139:         }
                   11140:     } elsif ($applies) {
                   11141:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11142:         if ($applies > 1) {
                   11143:             $output .=  
1.1075.2.35  raeburn  11144:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11145:             if ($numremref) {
                   11146:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11147:             }
                   11148:             if ($numinvalid) {
                   11149:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11150:             }
                   11151:             if ($numexisting) {
                   11152:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11153:             }
                   11154:             $output .= '</ul><br />';
                   11155:         } elsif ($numremref) {
                   11156:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11157:         } elsif ($numinvalid) {
                   11158:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11159:         } elsif ($numexisting) {
                   11160:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11161:         }
                   11162:         $output .= $upload_output.'<br />';
                   11163:     }
                   11164:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11165:     $chgcount = $counter;
1.987     raeburn  11166:     if (keys(%pathchanges) > 0) {
                   11167:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11168:             if ($counter) {
1.987     raeburn  11169:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11170:                                                   $embed_file,\%mapping,
1.1071    raeburn  11171:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11172:             } else {
                   11173:                 $pathchange_output .= 
                   11174:                     &start_data_table_row().
                   11175:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11176:                     $chgcount.'" checked="checked" /></td>'.
                   11177:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11178:                     '<td>'.$embed_file.
                   11179:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11180:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11181:                     '</td>'.&end_data_table_row();
1.660     raeburn  11182:             }
1.987     raeburn  11183:             $numpathchg ++;
                   11184:             $chgcount ++;
1.660     raeburn  11185:         }
                   11186:     }
1.1075.2.35  raeburn  11187:     if (($counter) || ($numunused)) {
1.987     raeburn  11188:         if ($numpathchg) {
                   11189:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11190:                        $numpathchg.'" />'."\n";
                   11191:         }
                   11192:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11193:             ($actionurl eq '/adm/imsimport')) {
                   11194:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11195:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11196:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11197:         } elsif ($actionurl eq '/adm/dependencies') {
                   11198:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11199:         }
1.1075.2.35  raeburn  11200:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11201:     } elsif ($numpathchg) {
                   11202:         my %pathchange = ();
                   11203:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11204:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11205:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  11206:         }
1.987     raeburn  11207:     }
1.1071    raeburn  11208:     return ($output,$counter,$numpathchg);
1.987     raeburn  11209: }
                   11210: 
1.1075.2.47  raeburn  11211: =pod
                   11212: 
                   11213: =item * clean_path($name)
                   11214: 
                   11215: Performs clean-up of directories, subdirectories and filename in an
                   11216: embedded object, referenced in an HTML file which is being uploaded
                   11217: to a course or portfolio, where
                   11218: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11219: checked.
                   11220: 
                   11221: Clean-up is similar to replacements in lonnet::clean_filename()
                   11222: except each / between sub-directory and next level is preserved.
                   11223: 
                   11224: =cut
                   11225: 
                   11226: sub clean_path {
                   11227:     my ($embed_file) = @_;
                   11228:     $embed_file =~s{^/+}{};
                   11229:     my @contents;
                   11230:     if ($embed_file =~ m{/}) {
                   11231:         @contents = split(/\//,$embed_file);
                   11232:     } else {
                   11233:         @contents = ($embed_file);
                   11234:     }
                   11235:     my $lastidx = scalar(@contents)-1;
                   11236:     for (my $i=0; $i<=$lastidx; $i++) {
                   11237:         $contents[$i]=~s{\\}{/}g;
                   11238:         $contents[$i]=~s/\s+/\_/g;
                   11239:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11240:         if ($i == $lastidx) {
                   11241:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11242:         }
                   11243:     }
                   11244:     if ($lastidx > 0) {
                   11245:         return join('/',@contents);
                   11246:     } else {
                   11247:         return $contents[0];
                   11248:     }
                   11249: }
                   11250: 
1.987     raeburn  11251: sub embedded_file_element {
1.1071    raeburn  11252:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11253:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11254:                    (ref($codebase) eq 'HASH'));
                   11255:     my $output;
1.1071    raeburn  11256:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11257:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11258:     }
                   11259:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11260:                &escape($embed_file).'" />';
                   11261:     unless (($context eq 'upload_embedded') && 
                   11262:             ($mapping->{$embed_file} eq $embed_file)) {
                   11263:         $output .='
                   11264:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11265:     }
                   11266:     my $attrib;
                   11267:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11268:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11269:     }
                   11270:     $output .=
                   11271:         "\n\t\t".
                   11272:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11273:         $attrib.'" />';
                   11274:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11275:         $output .=
                   11276:             "\n\t\t".
                   11277:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11278:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11279:     }
1.987     raeburn  11280:     return $output;
1.660     raeburn  11281: }
                   11282: 
1.1071    raeburn  11283: sub get_dependency_details {
                   11284:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11285:     my ($size,$mtime,$showsize,$showmtime);
                   11286:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11287:         if ($embed_file =~ m{/}) {
                   11288:             my ($path,$fname) = split(/\//,$embed_file);
                   11289:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11290:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11291:             }
                   11292:         } else {
                   11293:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11294:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11295:             }
                   11296:         }
                   11297:         $showsize = $size/1024.0;
                   11298:         $showsize = sprintf("%.1f",$showsize);
                   11299:         if ($mtime > 0) {
                   11300:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11301:         }
                   11302:     }
                   11303:     return ($showsize,$showmtime);
                   11304: }
                   11305: 
                   11306: sub ask_embedded_js {
                   11307:     return <<"END";
                   11308: <script type="text/javascript"">
                   11309: // <![CDATA[
                   11310: function toggleBrowse(counter) {
                   11311:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11312:     var fileid = document.getElementById('embedded_item_'+counter);
                   11313:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11314:     if (chkboxid.checked == true) {
                   11315:         uploaddivid.style.display='block';
                   11316:     } else {
                   11317:         uploaddivid.style.display='none';
                   11318:         fileid.value = '';
                   11319:     }
                   11320: }
                   11321: // ]]>
                   11322: </script>
                   11323: 
                   11324: END
                   11325: }
                   11326: 
1.661     raeburn  11327: sub upload_embedded {
                   11328:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11329:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11330:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11331:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11332:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11333:         my $orig_uploaded_filename =
                   11334:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11335:         foreach my $type ('orig','ref','attrib','codebase') {
                   11336:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11337:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11338:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11339:             }
                   11340:         }
1.661     raeburn  11341:         my ($path,$fname) =
                   11342:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11343:         # no path, whole string is fname
                   11344:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11345:         $fname = &Apache::lonnet::clean_filename($fname);
                   11346:         # See if there is anything left
                   11347:         next if ($fname eq '');
                   11348: 
                   11349:         # Check if file already exists as a file or directory.
                   11350:         my ($state,$msg);
                   11351:         if ($context eq 'portfolio') {
                   11352:             my $port_path = $dirpath;
                   11353:             if ($group ne '') {
                   11354:                 $port_path = "groups/$group/$port_path";
                   11355:             }
1.987     raeburn  11356:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11357:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11358:                                               $dir_root,$port_path,$disk_quota,
                   11359:                                               $current_disk_usage,$uname,$udom);
                   11360:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11361:                 || $state eq 'file_locked') {
1.661     raeburn  11362:                 $output .= $msg;
                   11363:                 next;
                   11364:             }
                   11365:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11366:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11367:             if ($state eq 'exists') {
                   11368:                 $output .= $msg;
                   11369:                 next;
                   11370:             }
                   11371:         }
                   11372:         # Check if extension is valid
                   11373:         if (($fname =~ /\.(\w+)$/) &&
                   11374:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  11375:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11376:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11377:             next;
                   11378:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11379:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11380:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11381:             next;
                   11382:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  11383:             $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  11384:             next;
                   11385:         }
                   11386:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  11387:         my $subdir = $path;
                   11388:         $subdir =~ s{/+$}{};
1.661     raeburn  11389:         if ($context eq 'portfolio') {
1.984     raeburn  11390:             my $result;
                   11391:             if ($state eq 'existingfile') {
                   11392:                 $result=
                   11393:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  11394:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11395:             } else {
1.984     raeburn  11396:                 $result=
                   11397:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11398:                                                     $dirpath.
1.1075.2.35  raeburn  11399:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11400:                 if ($result !~ m|^/uploaded/|) {
                   11401:                     $output .= '<span class="LC_error">'
                   11402:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11403:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11404:                                .'</span><br />';
                   11405:                     next;
                   11406:                 } else {
1.987     raeburn  11407:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11408:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11409:                 }
1.661     raeburn  11410:             }
1.1075.2.35  raeburn  11411:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   11412:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11413:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11414:             my $result =
1.1075.2.35  raeburn  11415:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11416:             if ($result !~ m|^/uploaded/|) {
                   11417:                 $output .= '<span class="LC_error">'
                   11418:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11419:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11420:                            .'</span><br />';
                   11421:                     next;
                   11422:             } else {
                   11423:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11424:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  11425:                 if ($context eq 'syllabus') {
                   11426:                     &Apache::lonnet::make_public_indefinitely($result);
                   11427:                 }
1.987     raeburn  11428:             }
1.661     raeburn  11429:         } else {
                   11430: # Save the file
                   11431:             my $target = $env{'form.embedded_item_'.$i};
                   11432:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11433:             my $dest = $fullpath.$fname;
                   11434:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11435:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11436:             my $count;
                   11437:             my $filepath = $dir_root;
1.1027    raeburn  11438:             foreach my $subdir (@parts) {
                   11439:                 $filepath .= "/$subdir";
                   11440:                 if (!-e $filepath) {
1.661     raeburn  11441:                     mkdir($filepath,0770);
                   11442:                 }
                   11443:             }
                   11444:             my $fh;
                   11445:             if (!open($fh,'>'.$dest)) {
                   11446:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11447:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11448:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11449:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11450:                            '</span><br />';
                   11451:             } else {
                   11452:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11453:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11454:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11455:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11456:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11457:                               '</span><br />';
                   11458:                 } else {
1.987     raeburn  11459:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11460:                                $url.'</span>').'<br />';
                   11461:                     unless ($context eq 'testbank') {
                   11462:                         $footer .= &mt('View embedded file: [_1]',
                   11463:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11464:                     }
                   11465:                 }
                   11466:                 close($fh);
                   11467:             }
                   11468:         }
                   11469:         if ($env{'form.embedded_ref_'.$i}) {
                   11470:             $pathchange{$i} = 1;
                   11471:         }
                   11472:     }
                   11473:     if ($output) {
                   11474:         $output = '<p>'.$output.'</p>';
                   11475:     }
                   11476:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11477:     $returnflag = 'ok';
1.1071    raeburn  11478:     my $numpathchgs = scalar(keys(%pathchange));
                   11479:     if ($numpathchgs > 0) {
1.987     raeburn  11480:         if ($context eq 'portfolio') {
                   11481:             $output .= '<p>'.&mt('or').'</p>';
                   11482:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11483:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11484:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11485:             $returnflag = 'modify_orightml';
                   11486:         }
                   11487:     }
1.1071    raeburn  11488:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11489: }
                   11490: 
                   11491: sub modify_html_form {
                   11492:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11493:     my $end = 0;
                   11494:     my $modifyform;
                   11495:     if ($context eq 'upload_embedded') {
                   11496:         return unless (ref($pathchange) eq 'HASH');
                   11497:         if ($env{'form.number_embedded_items'}) {
                   11498:             $end += $env{'form.number_embedded_items'};
                   11499:         }
                   11500:         if ($env{'form.number_pathchange_items'}) {
                   11501:             $end += $env{'form.number_pathchange_items'};
                   11502:         }
                   11503:         if ($end) {
                   11504:             for (my $i=0; $i<$end; $i++) {
                   11505:                 if ($i < $env{'form.number_embedded_items'}) {
                   11506:                     next unless($pathchange->{$i});
                   11507:                 }
                   11508:                 $modifyform .=
                   11509:                     &start_data_table_row().
                   11510:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11511:                     'checked="checked" /></td>'.
                   11512:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11513:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11514:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11515:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11516:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11517:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11518:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11519:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11520:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11521:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11522:                     &end_data_table_row();
1.1071    raeburn  11523:             }
1.987     raeburn  11524:         }
                   11525:     } else {
                   11526:         $modifyform = $pathchgtable;
                   11527:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11528:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11529:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11530:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11531:         }
                   11532:     }
                   11533:     if ($modifyform) {
1.1071    raeburn  11534:         if ($actionurl eq '/adm/dependencies') {
                   11535:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11536:         }
1.987     raeburn  11537:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11538:                '<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".
                   11539:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11540:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11541:                '</ol></p>'."\n".'<p>'.
                   11542:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11543:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11544:                &start_data_table()."\n".
                   11545:                &start_data_table_header_row().
                   11546:                '<th>'.&mt('Change?').'</th>'.
                   11547:                '<th>'.&mt('Current reference').'</th>'.
                   11548:                '<th>'.&mt('Required reference').'</th>'.
                   11549:                &end_data_table_header_row()."\n".
                   11550:                $modifyform.
                   11551:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11552:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11553:                '</form>'."\n";
                   11554:     }
                   11555:     return;
                   11556: }
                   11557: 
                   11558: sub modify_html_refs {
1.1075.2.35  raeburn  11559:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11560:     my $container;
                   11561:     if ($context eq 'portfolio') {
                   11562:         $container = $env{'form.container'};
                   11563:     } elsif ($context eq 'coursedoc') {
                   11564:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11565:     } elsif ($context eq 'manage_dependencies') {
                   11566:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11567:         $container = "/$container";
1.1075.2.35  raeburn  11568:     } elsif ($context eq 'syllabus') {
                   11569:         $container = $url;
1.987     raeburn  11570:     } else {
1.1027    raeburn  11571:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11572:     }
                   11573:     my (%allfiles,%codebase,$output,$content);
                   11574:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  11575:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  11576:         if (wantarray) {
                   11577:             return ('',0,0); 
                   11578:         } else {
                   11579:             return;
                   11580:         }
                   11581:     }
                   11582:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11583:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11584:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11585:             if (wantarray) {
                   11586:                 return ('',0,0);
                   11587:             } else {
                   11588:                 return;
                   11589:             }
                   11590:         } 
1.987     raeburn  11591:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11592:         if ($content eq '-1') {
                   11593:             if (wantarray) {
                   11594:                 return ('',0,0);
                   11595:             } else {
                   11596:                 return;
                   11597:             }
                   11598:         }
1.987     raeburn  11599:     } else {
1.1071    raeburn  11600:         unless ($container =~ /^\Q$dir_root\E/) {
                   11601:             if (wantarray) {
                   11602:                 return ('',0,0);
                   11603:             } else {
                   11604:                 return;
                   11605:             }
                   11606:         } 
1.1075.2.128  raeburn  11607:         if (open(my $fh,'<',$container)) {
1.987     raeburn  11608:             $content = join('', <$fh>);
                   11609:             close($fh);
                   11610:         } else {
1.1071    raeburn  11611:             if (wantarray) {
                   11612:                 return ('',0,0);
                   11613:             } else {
                   11614:                 return;
                   11615:             }
1.987     raeburn  11616:         }
                   11617:     }
                   11618:     my ($count,$codebasecount) = (0,0);
                   11619:     my $mm = new File::MMagic;
                   11620:     my $mime_type = $mm->checktype_contents($content);
                   11621:     if ($mime_type eq 'text/html') {
                   11622:         my $parse_result = 
                   11623:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11624:                                                     \%codebase,\$content);
                   11625:         if ($parse_result eq 'ok') {
                   11626:             foreach my $i (@changes) {
                   11627:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11628:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11629:                 if ($allfiles{$ref}) {
                   11630:                     my $newname =  $orig;
                   11631:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11632:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11633:                     if ($attrib_regexp =~ /:/) {
                   11634:                         $attrib_regexp =~ s/\:/|/g;
                   11635:                     }
                   11636:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11637:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11638:                         $count += $numchg;
1.1075.2.35  raeburn  11639:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  11640:                         delete($allfiles{$ref});
1.987     raeburn  11641:                     }
                   11642:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11643:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11644:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11645:                         $codebasecount ++;
                   11646:                     }
                   11647:                 }
                   11648:             }
1.1075.2.35  raeburn  11649:             my $skiprewrites;
1.987     raeburn  11650:             if ($count || $codebasecount) {
                   11651:                 my $saveresult;
1.1071    raeburn  11652:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11653:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11654:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11655:                     if ($url eq $container) {
                   11656:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11657:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11658:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11659:                                             $fname.'</span>').'</p>';
1.987     raeburn  11660:                     } else {
                   11661:                          $output = '<p class="LC_error">'.
                   11662:                                    &mt('Error: update failed for: [_1].',
                   11663:                                    '<span class="LC_filename">'.
                   11664:                                    $container.'</span>').'</p>';
                   11665:                     }
1.1075.2.35  raeburn  11666:                     if ($context eq 'syllabus') {
                   11667:                         unless ($saveresult eq 'ok') {
                   11668:                             $skiprewrites = 1;
                   11669:                         }
                   11670:                     }
1.987     raeburn  11671:                 } else {
1.1075.2.128  raeburn  11672:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  11673:                         print $fh $content;
                   11674:                         close($fh);
                   11675:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11676:                                   $count,'<span class="LC_filename">'.
                   11677:                                   $container.'</span>').'</p>';
1.661     raeburn  11678:                     } else {
1.987     raeburn  11679:                          $output = '<p class="LC_error">'.
                   11680:                                    &mt('Error: could not update [_1].',
                   11681:                                    '<span class="LC_filename">'.
                   11682:                                    $container.'</span>').'</p>';
1.661     raeburn  11683:                     }
                   11684:                 }
                   11685:             }
1.1075.2.35  raeburn  11686:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11687:                 my ($actionurl,$state);
                   11688:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11689:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11690:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11691:                                               \%codebase,
                   11692:                                               {'context' => 'rewrites',
                   11693:                                                'ignore_remote_references' => 1,});
                   11694:                 if (ref($mapping) eq 'HASH') {
                   11695:                     my $rewrites = 0;
                   11696:                     foreach my $key (keys(%{$mapping})) {
                   11697:                         next if ($key =~ m{^https?://});
                   11698:                         my $ref = $mapping->{$key};
                   11699:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11700:                         my $attrib;
                   11701:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11702:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11703:                         }
                   11704:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11705:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11706:                             $rewrites += $numchg;
                   11707:                         }
                   11708:                     }
                   11709:                     if ($rewrites) {
                   11710:                         my $saveresult;
                   11711:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11712:                         if ($url eq $container) {
                   11713:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11714:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11715:                                             $count,'<span class="LC_filename">'.
                   11716:                                             $fname.'</span>').'</p>';
                   11717:                         } else {
                   11718:                             $output .= '<p class="LC_error">'.
                   11719:                                        &mt('Error: could not update links in [_1].',
                   11720:                                        '<span class="LC_filename">'.
                   11721:                                        $container.'</span>').'</p>';
                   11722: 
                   11723:                         }
                   11724:                     }
                   11725:                 }
                   11726:             }
1.987     raeburn  11727:         } else {
                   11728:             &logthis('Failed to parse '.$container.
                   11729:                      ' to modify references: '.$parse_result);
1.661     raeburn  11730:         }
                   11731:     }
1.1071    raeburn  11732:     if (wantarray) {
                   11733:         return ($output,$count,$codebasecount);
                   11734:     } else {
                   11735:         return $output;
                   11736:     }
1.661     raeburn  11737: }
                   11738: 
                   11739: sub check_for_existing {
                   11740:     my ($path,$fname,$element) = @_;
                   11741:     my ($state,$msg);
                   11742:     if (-d $path.'/'.$fname) {
                   11743:         $state = 'exists';
                   11744:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11745:     } elsif (-e $path.'/'.$fname) {
                   11746:         $state = 'exists';
                   11747:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11748:     }
                   11749:     if ($state eq 'exists') {
                   11750:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11751:     }
                   11752:     return ($state,$msg);
                   11753: }
                   11754: 
                   11755: sub check_for_upload {
                   11756:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11757:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11758:     my $filesize = length($env{'form.'.$element});
                   11759:     if (!$filesize) {
                   11760:         my $msg = '<span class="LC_error">'.
                   11761:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11762:                       '<span class="LC_filename">'.$fname.'</span>',
                   11763:                       $filesize).'<br />'.
1.1007    raeburn  11764:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11765:                   '</span>';
                   11766:         return ('zero_bytes',$msg);
                   11767:     }
                   11768:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11769:     my $getpropath = 1;
1.1021    raeburn  11770:     my ($dirlistref,$listerror) =
                   11771:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11772:     my $found_file = 0;
                   11773:     my $locked_file = 0;
1.991     raeburn  11774:     my @lockers;
                   11775:     my $navmap;
                   11776:     if ($env{'request.course.id'}) {
                   11777:         $navmap = Apache::lonnavmaps::navmap->new();
                   11778:     }
1.1021    raeburn  11779:     if (ref($dirlistref) eq 'ARRAY') {
                   11780:         foreach my $line (@{$dirlistref}) {
                   11781:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11782:             if ($file_name eq $fname){
                   11783:                 $file_name = $path.$file_name;
                   11784:                 if ($group ne '') {
                   11785:                     $file_name = $group.$file_name;
                   11786:                 }
                   11787:                 $found_file = 1;
                   11788:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11789:                     foreach my $lock (@lockers) {
                   11790:                         if (ref($lock) eq 'ARRAY') {
                   11791:                             my ($symb,$crsid) = @{$lock};
                   11792:                             if ($crsid eq $env{'request.course.id'}) {
                   11793:                                 if (ref($navmap)) {
                   11794:                                     my $res = $navmap->getBySymb($symb);
                   11795:                                     foreach my $part (@{$res->parts()}) { 
                   11796:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11797:                                         unless (($slot_status == $res->RESERVED) ||
                   11798:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11799:                                             $locked_file = 1;
                   11800:                                         }
1.991     raeburn  11801:                                     }
1.1021    raeburn  11802:                                 } else {
                   11803:                                     $locked_file = 1;
1.991     raeburn  11804:                                 }
                   11805:                             } else {
                   11806:                                 $locked_file = 1;
                   11807:                             }
                   11808:                         }
1.1021    raeburn  11809:                    }
                   11810:                 } else {
                   11811:                     my @info = split(/\&/,$rest);
                   11812:                     my $currsize = $info[6]/1000;
                   11813:                     if ($currsize < $filesize) {
                   11814:                         my $extra = $filesize - $currsize;
                   11815:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  11816:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11817:                                       &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  11818:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11819:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11820:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11821:                             return ('will_exceed_quota',$msg);
                   11822:                         }
1.984     raeburn  11823:                     }
                   11824:                 }
1.661     raeburn  11825:             }
                   11826:         }
                   11827:     }
                   11828:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  11829:         my $msg = '<p class="LC_warning">'.
                   11830:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   11831:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11832:         return ('will_exceed_quota',$msg);
                   11833:     } elsif ($found_file) {
                   11834:         if ($locked_file) {
1.1075.2.69  raeburn  11835:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11836:             $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  11837:             $msg .= '</p>';
1.661     raeburn  11838:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11839:             return ('file_locked',$msg);
                   11840:         } else {
1.1075.2.69  raeburn  11841:             my $msg = '<p class="LC_error">';
1.984     raeburn  11842:             $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  11843:             $msg .= '</p>';
1.984     raeburn  11844:             return ('existingfile',$msg);
1.661     raeburn  11845:         }
                   11846:     }
                   11847: }
                   11848: 
1.987     raeburn  11849: sub check_for_traversal {
                   11850:     my ($path,$url,$toplevel) = @_;
                   11851:     my @parts=split(/\//,$path);
                   11852:     my $cleanpath;
                   11853:     my $fullpath = $url;
                   11854:     for (my $i=0;$i<@parts;$i++) {
                   11855:         next if ($parts[$i] eq '.');
                   11856:         if ($parts[$i] eq '..') {
                   11857:             $fullpath =~ s{([^/]+/)$}{};
                   11858:         } else {
                   11859:             $fullpath .= $parts[$i].'/';
                   11860:         }
                   11861:     }
                   11862:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11863:         $cleanpath = $1;
                   11864:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11865:         my $curr_toprel = $1;
                   11866:         my @parts = split(/\//,$curr_toprel);
                   11867:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11868:         my @urlparts = split(/\//,$url_toprel);
                   11869:         my $doubledots;
                   11870:         my $startdiff = -1;
                   11871:         for (my $i=0; $i<@urlparts; $i++) {
                   11872:             if ($startdiff == -1) {
                   11873:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11874:                     $startdiff = $i;
                   11875:                     $doubledots .= '../';
                   11876:                 }
                   11877:             } else {
                   11878:                 $doubledots .= '../';
                   11879:             }
                   11880:         }
                   11881:         if ($startdiff > -1) {
                   11882:             $cleanpath = $doubledots;
                   11883:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11884:                 $cleanpath .= $parts[$i].'/';
                   11885:             }
                   11886:         }
                   11887:     }
                   11888:     $cleanpath =~ s{(/)$}{};
                   11889:     return $cleanpath;
                   11890: }
1.31      albertel 11891: 
1.1053    raeburn  11892: sub is_archive_file {
                   11893:     my ($mimetype) = @_;
                   11894:     if (($mimetype eq 'application/octet-stream') ||
                   11895:         ($mimetype eq 'application/x-stuffit') ||
                   11896:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11897:         return 1;
                   11898:     }
                   11899:     return;
                   11900: }
                   11901: 
                   11902: sub decompress_form {
1.1065    raeburn  11903:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11904:     my %lt = &Apache::lonlocal::texthash (
                   11905:         this => 'This file is an archive file.',
1.1067    raeburn  11906:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11907:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11908:         youm => 'You may wish to extract its contents.',
                   11909:         extr => 'Extract contents',
1.1067    raeburn  11910:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11911:         proa => 'Process automatically?',
1.1053    raeburn  11912:         yes  => 'Yes',
                   11913:         no   => 'No',
1.1067    raeburn  11914:         fold => 'Title for folder containing movie',
                   11915:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11916:     );
1.1065    raeburn  11917:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11918:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11919:     my $info = &list_archive_contents($fileloc,\@paths);
                   11920:     if (@paths) {
                   11921:         foreach my $path (@paths) {
                   11922:             $path =~ s{^/}{};
1.1067    raeburn  11923:             if ($path =~ m{^([^/]+)/$}) {
                   11924:                 $topdir = $1;
                   11925:             }
1.1065    raeburn  11926:             if ($path =~ m{^([^/]+)/}) {
                   11927:                 $toplevel{$1} = $path;
                   11928:             } else {
                   11929:                 $toplevel{$path} = $path;
                   11930:             }
                   11931:         }
                   11932:     }
1.1067    raeburn  11933:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  11934:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11935:                         "$topdir/media/",
                   11936:                         "$topdir/media/$topdir.mp4",
                   11937:                         "$topdir/media/FirstFrame.png",
                   11938:                         "$topdir/media/player.swf",
                   11939:                         "$topdir/media/swfobject.js",
                   11940:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  11941:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  11942:                          "$topdir/$topdir.mp4",
                   11943:                          "$topdir/$topdir\_config.xml",
                   11944:                          "$topdir/$topdir\_controller.swf",
                   11945:                          "$topdir/$topdir\_embed.css",
                   11946:                          "$topdir/$topdir\_First_Frame.png",
                   11947:                          "$topdir/$topdir\_player.html",
                   11948:                          "$topdir/$topdir\_Thumbnails.png",
                   11949:                          "$topdir/playerProductInstall.swf",
                   11950:                          "$topdir/scripts/",
                   11951:                          "$topdir/scripts/config_xml.js",
                   11952:                          "$topdir/scripts/handlebars.js",
                   11953:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11954:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11955:                          "$topdir/scripts/modernizr.js",
                   11956:                          "$topdir/scripts/player-min.js",
                   11957:                          "$topdir/scripts/swfobject.js",
                   11958:                          "$topdir/skins/",
                   11959:                          "$topdir/skins/configuration_express.xml",
                   11960:                          "$topdir/skins/express_show/",
                   11961:                          "$topdir/skins/express_show/player-min.css",
                   11962:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  11963:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11964:                          "$topdir/$topdir.mp4",
                   11965:                          "$topdir/$topdir\_config.xml",
                   11966:                          "$topdir/$topdir\_controller.swf",
                   11967:                          "$topdir/$topdir\_embed.css",
                   11968:                          "$topdir/$topdir\_First_Frame.png",
                   11969:                          "$topdir/$topdir\_player.html",
                   11970:                          "$topdir/$topdir\_Thumbnails.png",
                   11971:                          "$topdir/playerProductInstall.swf",
                   11972:                          "$topdir/scripts/",
                   11973:                          "$topdir/scripts/config_xml.js",
                   11974:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11975:                          "$topdir/skins/",
                   11976:                          "$topdir/skins/configuration_express.xml",
                   11977:                          "$topdir/skins/express_show/",
                   11978:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11979:                          "$topdir/skins/express_show/spritesheet.png",
                   11980:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  11981:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11982:         if (@diffs == 0) {
1.1075.2.59  raeburn  11983:             $is_camtasia = 6;
                   11984:         } else {
1.1075.2.81  raeburn  11985:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  11986:             if (@diffs == 0) {
                   11987:                 $is_camtasia = 8;
1.1075.2.81  raeburn  11988:             } else {
                   11989:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11990:                 if (@diffs == 0) {
                   11991:                     $is_camtasia = 8;
                   11992:                 }
1.1075.2.59  raeburn  11993:             }
1.1067    raeburn  11994:         }
                   11995:     }
                   11996:     my $output;
                   11997:     if ($is_camtasia) {
                   11998:         $output = <<"ENDCAM";
                   11999: <script type="text/javascript" language="Javascript">
                   12000: // <![CDATA[
                   12001: 
                   12002: function camtasiaToggle() {
                   12003:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12004:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  12005:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12006:                 document.getElementById('camtasia_titles').style.display='block';
                   12007:             } else {
                   12008:                 document.getElementById('camtasia_titles').style.display='none';
                   12009:             }
                   12010:         }
                   12011:     }
                   12012:     return;
                   12013: }
                   12014: 
                   12015: // ]]>
                   12016: </script>
                   12017: <p>$lt{'camt'}</p>
                   12018: ENDCAM
1.1065    raeburn  12019:     } else {
1.1067    raeburn  12020:         $output = '<p>'.$lt{'this'};
                   12021:         if ($info eq '') {
                   12022:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12023:         } else {
                   12024:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12025:                        '<div><pre>'.$info.'</pre></div>';
                   12026:         }
1.1065    raeburn  12027:     }
1.1067    raeburn  12028:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12029:     my $duplicates;
                   12030:     my $num = 0;
                   12031:     if (ref($dirlist) eq 'ARRAY') {
                   12032:         foreach my $item (@{$dirlist}) {
                   12033:             if (ref($item) eq 'ARRAY') {
                   12034:                 if (exists($toplevel{$item->[0]})) {
                   12035:                     $duplicates .= 
                   12036:                         &start_data_table_row().
                   12037:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12038:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12039:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12040:                         'value="1" />'.&mt('Yes').'</label>'.
                   12041:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12042:                         '<td>'.$item->[0].'</td>';
                   12043:                     if ($item->[2]) {
                   12044:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12045:                     } else {
                   12046:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12047:                     }
                   12048:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12049:                                    '<td>'.
                   12050:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12051:                                    '</td>'.
                   12052:                                    &end_data_table_row();
                   12053:                     $num ++;
                   12054:                 }
                   12055:             }
                   12056:         }
                   12057:     }
                   12058:     my $itemcount;
                   12059:     if (@paths > 0) {
                   12060:         $itemcount = scalar(@paths);
                   12061:     } else {
                   12062:         $itemcount = 1;
                   12063:     }
1.1067    raeburn  12064:     if ($is_camtasia) {
                   12065:         $output .= $lt{'auto'}.'<br />'.
                   12066:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  12067:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12068:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12069:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12070:                    $lt{'no'}.'</label></span><br />'.
                   12071:                    '<div id="camtasia_titles" style="display:block">'.
                   12072:                    &Apache::lonhtmlcommon::start_pick_box().
                   12073:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12074:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12075:                    &Apache::lonhtmlcommon::row_closure().
                   12076:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12077:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12078:                    &Apache::lonhtmlcommon::row_closure(1).
                   12079:                    &Apache::lonhtmlcommon::end_pick_box().
                   12080:                    '</div>';
                   12081:     }
1.1065    raeburn  12082:     $output .= 
                   12083:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12084:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12085:         "\n";
1.1065    raeburn  12086:     if ($duplicates ne '') {
                   12087:         $output .= '<p><span class="LC_warning">'.
                   12088:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12089:                    &start_data_table().
                   12090:                    &start_data_table_header_row().
                   12091:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12092:                    '<th>'.&mt('Name').'</th>'.
                   12093:                    '<th>'.&mt('Type').'</th>'.
                   12094:                    '<th>'.&mt('Size').'</th>'.
                   12095:                    '<th>'.&mt('Last modified').'</th>'.
                   12096:                    &end_data_table_header_row().
                   12097:                    $duplicates.
                   12098:                    &end_data_table().
                   12099:                    '</p>';
                   12100:     }
1.1067    raeburn  12101:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12102:     if (ref($hiddenelements) eq 'HASH') {
                   12103:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12104:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12105:         }
                   12106:     }
                   12107:     $output .= <<"END";
1.1067    raeburn  12108: <br />
1.1053    raeburn  12109: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12110: </form>
                   12111: $noextract
                   12112: END
                   12113:     return $output;
                   12114: }
                   12115: 
1.1065    raeburn  12116: sub decompression_utility {
                   12117:     my ($program) = @_;
                   12118:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12119:     my $location;
                   12120:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12121:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12122:                          '/usr/sbin/') {
                   12123:             if (-x $dir.$program) {
                   12124:                 $location = $dir.$program;
                   12125:                 last;
                   12126:             }
                   12127:         }
                   12128:     }
                   12129:     return $location;
                   12130: }
                   12131: 
                   12132: sub list_archive_contents {
                   12133:     my ($file,$pathsref) = @_;
                   12134:     my (@cmd,$output);
                   12135:     my $needsregexp;
                   12136:     if ($file =~ /\.zip$/) {
                   12137:         @cmd = (&decompression_utility('unzip'),"-l");
                   12138:         $needsregexp = 1;
                   12139:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12140:              ($file =~ /\.tgz$/)) {
                   12141:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12142:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12143:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12144:     } elsif ($file =~ m|\.tar$|) {
                   12145:         @cmd = (&decompression_utility('tar'),"-tf");
                   12146:     }
                   12147:     if (@cmd) {
                   12148:         undef($!);
                   12149:         undef($@);
                   12150:         if (open(my $fh,"-|", @cmd, $file)) {
                   12151:             while (my $line = <$fh>) {
                   12152:                 $output .= $line;
                   12153:                 chomp($line);
                   12154:                 my $item;
                   12155:                 if ($needsregexp) {
                   12156:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12157:                 } else {
                   12158:                     $item = $line;
                   12159:                 }
                   12160:                 if ($item ne '') {
                   12161:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12162:                         push(@{$pathsref},$item);
                   12163:                     } 
                   12164:                 }
                   12165:             }
                   12166:             close($fh);
                   12167:         }
                   12168:     }
                   12169:     return $output;
                   12170: }
                   12171: 
1.1053    raeburn  12172: sub decompress_uploaded_file {
                   12173:     my ($file,$dir) = @_;
                   12174:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12175:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12176:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12177:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12178:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12179:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12180:     my $decompressed = $env{'cgi.decompressed'};
                   12181:     &Apache::lonnet::delenv('cgi.file');
                   12182:     &Apache::lonnet::delenv('cgi.dir');
                   12183:     &Apache::lonnet::delenv('cgi.decompressed');
                   12184:     return ($decompressed,$result);
                   12185: }
                   12186: 
1.1055    raeburn  12187: sub process_decompression {
                   12188:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1075.2.128  raeburn  12189:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12190:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12191:                &mt('Unexpected file path.').'</p>'."\n";
                   12192:     }
                   12193:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12194:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12195:                &mt('Unexpected course context.').'</p>'."\n";
                   12196:     }
                   12197:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
                   12198:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12199:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12200:     }
1.1055    raeburn  12201:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  12202:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  12203:         $error = &mt('Filename not a supported archive file type.').
                   12204:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12205:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12206:     } else {
                   12207:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12208:         if ($docuhome eq 'no_host') {
                   12209:             $error = &mt('Could not determine home server for course.');
                   12210:         } else {
                   12211:             my @ids=&Apache::lonnet::current_machine_ids();
                   12212:             my $currdir = "$dir_root/$destination";
                   12213:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12214:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12215:                        "$dir_root/$destination";
                   12216:             } else {
                   12217:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12218:                        "$dir_root/$docudom/$docuname/$destination";
                   12219:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12220:                     $error = &mt('Archive file not found.');
                   12221:                 }
                   12222:             }
1.1065    raeburn  12223:             my (@to_overwrite,@to_skip);
                   12224:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12225:                 my $total = $env{'form.archive_overwrite_total'};
                   12226:                 for (my $i=0; $i<$total; $i++) {
                   12227:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12228:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12229:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12230:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12231:                     }
                   12232:                 }
                   12233:             }
                   12234:             my $numskip = scalar(@to_skip);
1.1075.2.128  raeburn  12235:             my $numoverwrite = scalar(@to_overwrite);
                   12236:             if (($numskip) && (!$numoverwrite)) {
1.1065    raeburn  12237:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12238:             } elsif ($dir eq '') {
1.1055    raeburn  12239:                 $error = &mt('Directory containing archive file unavailable.');
                   12240:             } elsif (!$error) {
1.1065    raeburn  12241:                 my ($decompressed,$display);
1.1075.2.128  raeburn  12242:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12243:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12244:                     mkdir("$dir/$tempdir",0755);
1.1075.2.128  raeburn  12245:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   12246:                         ($decompressed,$display) =
                   12247:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   12248:                         foreach my $item (@to_skip) {
                   12249:                             if (($item ne '') && ($item !~ /\.\./)) {
                   12250:                                 if (-f "$dir/$tempdir/$item") {
                   12251:                                     unlink("$dir/$tempdir/$item");
                   12252:                                 } elsif (-d "$dir/$tempdir/$item") {
                   12253:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
                   12254:                                 }
                   12255:                             }
                   12256:                         }
                   12257:                         foreach my $item (@to_overwrite) {
                   12258:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   12259:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   12260:                                     if (-f "$dir/$item") {
                   12261:                                         unlink("$dir/$item");
                   12262:                                     } elsif (-d "$dir/$item") {
                   12263:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
                   12264:                                     }
                   12265:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   12266:                                 }
1.1065    raeburn  12267:                             }
                   12268:                         }
1.1075.2.128  raeburn  12269:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
                   12270:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
                   12271:                         }
1.1065    raeburn  12272:                     }
                   12273:                 } else {
                   12274:                     ($decompressed,$display) = 
                   12275:                         &decompress_uploaded_file($file,$dir);
                   12276:                 }
1.1055    raeburn  12277:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12278:                     $output = '<p class="LC_info">'.
                   12279:                               &mt('Files extracted successfully from archive.').
                   12280:                               '</p>'."\n";
1.1055    raeburn  12281:                     my ($warning,$result,@contents);
                   12282:                     my ($newdirlistref,$newlisterror) =
                   12283:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12284:                                                  $docuname,1);
                   12285:                     my (%is_dir,%changes,@newitems);
                   12286:                     my $dirptr = 16384;
1.1065    raeburn  12287:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12288:                         foreach my $dir_line (@{$newdirlistref}) {
                   12289:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1075.2.128  raeburn  12290:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
1.1055    raeburn  12291:                                 push(@newitems,$item);
                   12292:                                 if ($dirptr&$testdir) {
                   12293:                                     $is_dir{$item} = 1;
                   12294:                                 }
                   12295:                                 $changes{$item} = 1;
                   12296:                             }
                   12297:                         }
                   12298:                     }
                   12299:                     if (keys(%changes) > 0) {
                   12300:                         foreach my $item (sort(@newitems)) {
                   12301:                             if ($changes{$item}) {
                   12302:                                 push(@contents,$item);
                   12303:                             }
                   12304:                         }
                   12305:                     }
                   12306:                     if (@contents > 0) {
1.1067    raeburn  12307:                         my $wantform;
                   12308:                         unless ($env{'form.autoextract_camtasia'}) {
                   12309:                             $wantform = 1;
                   12310:                         }
1.1056    raeburn  12311:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12312:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12313:                                                                 $currdir,\%is_dir,
                   12314:                                                                 \%children,\%parent,
1.1056    raeburn  12315:                                                                 \@contents,\%dirorder,
                   12316:                                                                 \%titles,$wantform);
1.1055    raeburn  12317:                         if ($datatable ne '') {
                   12318:                             $output .= &archive_options_form('decompressed',$datatable,
                   12319:                                                              $count,$hiddenelem);
1.1065    raeburn  12320:                             my $startcount = 6;
1.1055    raeburn  12321:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12322:                                                            \%titles,\%children);
1.1055    raeburn  12323:                         }
1.1067    raeburn  12324:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  12325:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12326:                             my %displayed;
                   12327:                             my $total = 1;
                   12328:                             $env{'form.archive_directory'} = [];
                   12329:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12330:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12331:                                 $path =~ s{/$}{};
                   12332:                                 my $item;
                   12333:                                 if ($path ne '') {
                   12334:                                     $item = "$path/$titles{$i}";
                   12335:                                 } else {
                   12336:                                     $item = $titles{$i};
                   12337:                                 }
                   12338:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12339:                                 if ($item eq $contents[0]) {
                   12340:                                     push(@{$env{'form.archive_directory'}},$i);
                   12341:                                     $env{'form.archive_'.$i} = 'display';
                   12342:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12343:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  12344:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12345:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  12346:                                     $env{'form.archive_'.$i} = 'display';
                   12347:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12348:                                     $displayed{'web'} = $i;
                   12349:                                 } else {
1.1075.2.59  raeburn  12350:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12351:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12352:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12353:                                         push(@{$env{'form.archive_directory'}},$i);
                   12354:                                     }
                   12355:                                     $env{'form.archive_'.$i} = 'dependency';
                   12356:                                 }
                   12357:                                 $total ++;
                   12358:                             }
                   12359:                             for (my $i=1; $i<$total; $i++) {
                   12360:                                 next if ($i == $displayed{'web'});
                   12361:                                 next if ($i == $displayed{'folder'});
                   12362:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12363:                             }
                   12364:                             $env{'form.phase'} = 'decompress_cleanup';
                   12365:                             $env{'form.archivedelete'} = 1;
                   12366:                             $env{'form.archive_count'} = $total-1;
                   12367:                             $output .=
                   12368:                                 &process_extracted_files('coursedocs',$docudom,
                   12369:                                                          $docuname,$destination,
                   12370:                                                          $dir_root,$hiddenelem);
                   12371:                         }
1.1055    raeburn  12372:                     } else {
                   12373:                         $warning = &mt('No new items extracted from archive file.');
                   12374:                     }
                   12375:                 } else {
                   12376:                     $output = $display;
                   12377:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12378:                 }
                   12379:             }
                   12380:         }
                   12381:     }
                   12382:     if ($error) {
                   12383:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12384:                    $error.'</p>'."\n";
                   12385:     }
                   12386:     if ($warning) {
                   12387:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12388:     }
                   12389:     return $output;
                   12390: }
                   12391: 
                   12392: sub get_extracted {
1.1056    raeburn  12393:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12394:         $titles,$wantform) = @_;
1.1055    raeburn  12395:     my $count = 0;
                   12396:     my $depth = 0;
                   12397:     my $datatable;
1.1056    raeburn  12398:     my @hierarchy;
1.1055    raeburn  12399:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12400:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12401:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12402:     foreach my $item (@{$contents}) {
                   12403:         $count ++;
1.1056    raeburn  12404:         @{$dirorder->{$count}} = @hierarchy;
                   12405:         $titles->{$count} = $item;
1.1055    raeburn  12406:         &archive_hierarchy($depth,$count,$parent,$children);
                   12407:         if ($wantform) {
                   12408:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12409:                                        $currdir,$depth,$count);
                   12410:         }
                   12411:         if ($is_dir->{$item}) {
                   12412:             $depth ++;
1.1056    raeburn  12413:             push(@hierarchy,$count);
                   12414:             $parent->{$depth} = $count;
1.1055    raeburn  12415:             $datatable .=
                   12416:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12417:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12418:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12419:             $depth --;
1.1056    raeburn  12420:             pop(@hierarchy);
1.1055    raeburn  12421:         }
                   12422:     }
                   12423:     return ($count,$datatable);
                   12424: }
                   12425: 
                   12426: sub recurse_extracted_archive {
1.1056    raeburn  12427:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12428:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12429:     my $result='';
1.1056    raeburn  12430:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12431:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12432:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12433:         return $result;
                   12434:     }
                   12435:     my $dirptr = 16384;
                   12436:     my ($newdirlistref,$newlisterror) =
                   12437:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12438:     if (ref($newdirlistref) eq 'ARRAY') {
                   12439:         foreach my $dir_line (@{$newdirlistref}) {
                   12440:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12441:             unless ($item =~ /^\.+$/) {
                   12442:                 $$count ++;
1.1056    raeburn  12443:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12444:                 $titles->{$$count} = $item;
1.1055    raeburn  12445:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12446: 
1.1055    raeburn  12447:                 my $is_dir;
                   12448:                 if ($dirptr&$testdir) {
                   12449:                     $is_dir = 1;
                   12450:                 }
                   12451:                 if ($wantform) {
                   12452:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12453:                 }
                   12454:                 if ($is_dir) {
                   12455:                     $$depth ++;
1.1056    raeburn  12456:                     push(@{$hierarchy},$$count);
                   12457:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12458:                     $result .=
                   12459:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12460:                                                    $docuname,$depth,$count,
1.1056    raeburn  12461:                                                    $hierarchy,$dirorder,$children,
                   12462:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12463:                     $$depth --;
1.1056    raeburn  12464:                     pop(@{$hierarchy});
1.1055    raeburn  12465:                 }
                   12466:             }
                   12467:         }
                   12468:     }
                   12469:     return $result;
                   12470: }
                   12471: 
                   12472: sub archive_hierarchy {
                   12473:     my ($depth,$count,$parent,$children) =@_;
                   12474:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12475:         if (exists($parent->{$depth})) {
                   12476:              $children->{$parent->{$depth}} .= $count.':';
                   12477:         }
                   12478:     }
                   12479:     return;
                   12480: }
                   12481: 
                   12482: sub archive_row {
                   12483:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12484:     my ($name) = ($item =~ m{([^/]+)$});
                   12485:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12486:                                        'display'    => 'Add as file',
1.1055    raeburn  12487:                                        'dependency' => 'Include as dependency',
                   12488:                                        'discard'    => 'Discard',
                   12489:                                       );
                   12490:     if ($is_dir) {
1.1059    raeburn  12491:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12492:     }
1.1056    raeburn  12493:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12494:     my $offset = 0;
1.1055    raeburn  12495:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12496:         $offset ++;
1.1065    raeburn  12497:         if ($action ne 'display') {
                   12498:             $offset ++;
                   12499:         }  
1.1055    raeburn  12500:         $output .= '<td><span class="LC_nobreak">'.
                   12501:                    '<label><input type="radio" name="archive_'.$count.
                   12502:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12503:         my $text = $choices{$action};
                   12504:         if ($is_dir) {
                   12505:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12506:             if ($action eq 'display') {
1.1059    raeburn  12507:                 $text = &mt('Add as folder');
1.1055    raeburn  12508:             }
1.1056    raeburn  12509:         } else {
                   12510:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12511: 
                   12512:         }
                   12513:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12514:         if ($action eq 'dependency') {
                   12515:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12516:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12517:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12518:                        '<option value=""></option>'."\n".
                   12519:                        '</select>'."\n".
                   12520:                        '</div>';
1.1059    raeburn  12521:         } elsif ($action eq 'display') {
                   12522:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12523:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12524:                        '</div>';
1.1055    raeburn  12525:         }
1.1056    raeburn  12526:         $output .= '</td>';
1.1055    raeburn  12527:     }
                   12528:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12529:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12530:     for (my $i=0; $i<$depth; $i++) {
                   12531:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12532:     }
                   12533:     if ($is_dir) {
                   12534:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12535:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12536:     } else {
                   12537:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12538:     }
                   12539:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12540:                &end_data_table_row();
                   12541:     return $output;
                   12542: }
                   12543: 
                   12544: sub archive_options_form {
1.1065    raeburn  12545:     my ($form,$display,$count,$hiddenelem) = @_;
                   12546:     my %lt = &Apache::lonlocal::texthash(
                   12547:                perm => 'Permanently remove archive file?',
                   12548:                hows => 'How should each extracted item be incorporated in the course?',
                   12549:                cont => 'Content actions for all',
                   12550:                addf => 'Add as folder/file',
                   12551:                incd => 'Include as dependency for a displayed file',
                   12552:                disc => 'Discard',
                   12553:                no   => 'No',
                   12554:                yes  => 'Yes',
                   12555:                save => 'Save',
                   12556:     );
                   12557:     my $output = <<"END";
                   12558: <form name="$form" method="post" action="">
                   12559: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12560: <label>
                   12561:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12562: </label>
                   12563: &nbsp;
                   12564: <label>
                   12565:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12566: </span>
                   12567: </p>
                   12568: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12569: <br />$lt{'hows'}
                   12570: <div class="LC_columnSection">
                   12571:   <fieldset>
                   12572:     <legend>$lt{'cont'}</legend>
                   12573:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12574:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12575:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12576:   </fieldset>
                   12577: </div>
                   12578: END
                   12579:     return $output.
1.1055    raeburn  12580:            &start_data_table()."\n".
1.1065    raeburn  12581:            $display."\n".
1.1055    raeburn  12582:            &end_data_table()."\n".
                   12583:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12584:            $hiddenelem.
1.1065    raeburn  12585:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12586:            '</form>';
                   12587: }
                   12588: 
                   12589: sub archive_javascript {
1.1056    raeburn  12590:     my ($startcount,$numitems,$titles,$children) = @_;
                   12591:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12592:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12593:     my $scripttag = <<START;
                   12594: <script type="text/javascript">
                   12595: // <![CDATA[
                   12596: 
                   12597: function checkAll(form,prefix) {
                   12598:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12599:     for (var i=0; i < form.elements.length; i++) {
                   12600:         var id = form.elements[i].id;
                   12601:         if ((id != '') && (id != undefined)) {
                   12602:             if (idstr.test(id)) {
                   12603:                 if (form.elements[i].type == 'radio') {
                   12604:                     form.elements[i].checked = true;
1.1056    raeburn  12605:                     var nostart = i-$startcount;
1.1059    raeburn  12606:                     var offset = nostart%7;
                   12607:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12608:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12609:                 }
                   12610:             }
                   12611:         }
                   12612:     }
                   12613: }
                   12614: 
                   12615: function propagateCheck(form,count) {
                   12616:     if (count > 0) {
1.1059    raeburn  12617:         var startelement = $startcount + ((count-1) * 7);
                   12618:         for (var j=1; j<6; j++) {
                   12619:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12620:                 var item = startelement + j; 
                   12621:                 if (form.elements[item].type == 'radio') {
                   12622:                     if (form.elements[item].checked) {
                   12623:                         containerCheck(form,count,j);
                   12624:                         break;
                   12625:                     }
1.1055    raeburn  12626:                 }
                   12627:             }
                   12628:         }
                   12629:     }
                   12630: }
                   12631: 
                   12632: numitems = $numitems
1.1056    raeburn  12633: var titles = new Array(numitems);
                   12634: var parents = new Array(numitems);
1.1055    raeburn  12635: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12636:     parents[i] = new Array;
1.1055    raeburn  12637: }
1.1059    raeburn  12638: var maintitle = '$maintitle';
1.1055    raeburn  12639: 
                   12640: START
                   12641: 
1.1056    raeburn  12642:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12643:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12644:         for (my $i=0; $i<@contents; $i ++) {
                   12645:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12646:         }
                   12647:     }
                   12648: 
1.1056    raeburn  12649:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12650:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12651:     }
                   12652: 
1.1055    raeburn  12653:     $scripttag .= <<END;
                   12654: 
                   12655: function containerCheck(form,count,offset) {
                   12656:     if (count > 0) {
1.1056    raeburn  12657:         dependencyCheck(form,count,offset);
1.1059    raeburn  12658:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12659:         form.elements[item].checked = true;
                   12660:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12661:             if (parents[count].length > 0) {
                   12662:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12663:                     containerCheck(form,parents[count][j],offset);
                   12664:                 }
                   12665:             }
                   12666:         }
                   12667:     }
                   12668: }
                   12669: 
                   12670: function dependencyCheck(form,count,offset) {
                   12671:     if (count > 0) {
1.1059    raeburn  12672:         var chosen = (offset+$startcount)+7*(count-1);
                   12673:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12674:         var currtype = form.elements[depitem].type;
                   12675:         if (form.elements[chosen].value == 'dependency') {
                   12676:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12677:             form.elements[depitem].options.length = 0;
                   12678:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  12679:             for (var i=1; i<=numitems; i++) {
                   12680:                 if (i == count) {
                   12681:                     continue;
                   12682:                 }
1.1059    raeburn  12683:                 var startelement = $startcount + (i-1) * 7;
                   12684:                 for (var j=1; j<6; j++) {
                   12685:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12686:                         var item = startelement + j;
                   12687:                         if (form.elements[item].type == 'radio') {
                   12688:                             if (form.elements[item].checked) {
                   12689:                                 if (form.elements[item].value == 'display') {
                   12690:                                     var n = form.elements[depitem].options.length;
                   12691:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12692:                                 }
                   12693:                             }
                   12694:                         }
                   12695:                     }
                   12696:                 }
                   12697:             }
                   12698:         } else {
                   12699:             document.getElementById('arc_depon_'+count).style.display='none';
                   12700:             form.elements[depitem].options.length = 0;
                   12701:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12702:         }
1.1059    raeburn  12703:         titleCheck(form,count,offset);
1.1056    raeburn  12704:     }
                   12705: }
                   12706: 
                   12707: function propagateSelect(form,count,offset) {
                   12708:     if (count > 0) {
1.1065    raeburn  12709:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12710:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12711:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12712:             if (parents[count].length > 0) {
                   12713:                 for (var j=0; j<parents[count].length; j++) {
                   12714:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12715:                 }
                   12716:             }
                   12717:         }
                   12718:     }
                   12719: }
1.1056    raeburn  12720: 
                   12721: function containerSelect(form,count,offset,picked) {
                   12722:     if (count > 0) {
1.1065    raeburn  12723:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12724:         if (form.elements[item].type == 'radio') {
                   12725:             if (form.elements[item].value == 'dependency') {
                   12726:                 if (form.elements[item+1].type == 'select-one') {
                   12727:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12728:                         if (form.elements[item+1].options[i].value == picked) {
                   12729:                             form.elements[item+1].selectedIndex = i;
                   12730:                             break;
                   12731:                         }
                   12732:                     }
                   12733:                 }
                   12734:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12735:                     if (parents[count].length > 0) {
                   12736:                         for (var j=0; j<parents[count].length; j++) {
                   12737:                             containerSelect(form,parents[count][j],offset,picked);
                   12738:                         }
                   12739:                     }
                   12740:                 }
                   12741:             }
                   12742:         }
                   12743:     }
                   12744: }
                   12745: 
1.1059    raeburn  12746: function titleCheck(form,count,offset) {
                   12747:     if (count > 0) {
                   12748:         var chosen = (offset+$startcount)+7*(count-1);
                   12749:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12750:         var currtype = form.elements[depitem].type;
                   12751:         if (form.elements[chosen].value == 'display') {
                   12752:             document.getElementById('arc_title_'+count).style.display='block';
                   12753:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12754:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12755:             }
                   12756:         } else {
                   12757:             document.getElementById('arc_title_'+count).style.display='none';
                   12758:             if (currtype == 'text') { 
                   12759:                 document.getElementById('archive_title_'+count).value='';
                   12760:             }
                   12761:         }
                   12762:     }
                   12763:     return;
                   12764: }
                   12765: 
1.1055    raeburn  12766: // ]]>
                   12767: </script>
                   12768: END
                   12769:     return $scripttag;
                   12770: }
                   12771: 
                   12772: sub process_extracted_files {
1.1067    raeburn  12773:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12774:     my $numitems = $env{'form.archive_count'};
1.1075.2.128  raeburn  12775:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  12776:     my @ids=&Apache::lonnet::current_machine_ids();
                   12777:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12778:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12779:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12780:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12781:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12782:         $pathtocheck = "$dir_root/$destination";
                   12783:         $dir = $dir_root;
                   12784:         $ishome = 1;
                   12785:     } else {
                   12786:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12787:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1075.2.128  raeburn  12788:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  12789:     }
                   12790:     my $currdir = "$dir_root/$destination";
                   12791:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12792:     if ($env{'form.folderpath'}) {
                   12793:         my @items = split('&',$env{'form.folderpath'});
                   12794:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  12795:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12796:             $containers{'0'}='page';
                   12797:         } else {
                   12798:             $containers{'0'}='sequence';
                   12799:         }
1.1055    raeburn  12800:     }
                   12801:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12802:     if ($numitems) {
                   12803:         for (my $i=1; $i<=$numitems; $i++) {
                   12804:             my $path = $env{'form.archive_content_'.$i};
                   12805:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12806:                 my $item = $1;
                   12807:                 $toplevelitems{$item} = $i;
                   12808:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12809:                     $is_dir{$item} = 1;
                   12810:                 }
                   12811:             }
                   12812:         }
                   12813:     }
1.1067    raeburn  12814:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12815:     if (keys(%toplevelitems) > 0) {
                   12816:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12817:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12818:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12819:     }
1.1066    raeburn  12820:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12821:     if ($numitems) {
                   12822:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  12823:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12824:             my $path = $env{'form.archive_content_'.$i};
                   12825:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12826:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12827:                     if ($prefix ne '' && $path ne '') {
                   12828:                         if (-e $prefix.$path) {
1.1066    raeburn  12829:                             if ((@archdirs > 0) && 
                   12830:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12831:                                 $todeletedir{$prefix.$path} = 1;
                   12832:                             } else {
                   12833:                                 $todelete{$prefix.$path} = 1;
                   12834:                             }
1.1055    raeburn  12835:                         }
                   12836:                     }
                   12837:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12838:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12839:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12840:                     $docstitle = $env{'form.archive_title_'.$i};
                   12841:                     if ($docstitle eq '') {
                   12842:                         $docstitle = $title;
                   12843:                     }
1.1055    raeburn  12844:                     $outer = 0;
1.1056    raeburn  12845:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12846:                         if (@{$dirorder{$i}} > 0) {
                   12847:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12848:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12849:                                     $outer = $item;
                   12850:                                     last;
                   12851:                                 }
                   12852:                             }
                   12853:                         }
                   12854:                     }
                   12855:                     my ($errtext,$fatal) = 
                   12856:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12857:                                                '/'.$folders{$outer}.'.'.
                   12858:                                                $containers{$outer});
                   12859:                     next if ($fatal);
                   12860:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12861:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12862:                             $mapinner{$i} = time;
1.1055    raeburn  12863:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12864:                             $containers{$i} = 'sequence';
                   12865:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12866:                                       $folders{$i}.'.'.$containers{$i};
                   12867:                             my $newidx = &LONCAPA::map::getresidx();
                   12868:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12869:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12870:                             push(@LONCAPA::map::order,$newidx);
                   12871:                             my ($outtext,$errtext) =
                   12872:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12873:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12874:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12875:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12876:                             unless ($errtext) {
1.1075.2.128  raeburn  12877:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   12878:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
                   12879:                                             '</li>'."\n";
1.1067    raeburn  12880:                             }
1.1055    raeburn  12881:                         }
                   12882:                     } else {
                   12883:                         if ($context eq 'coursedocs') {
                   12884:                             my $newidx=&LONCAPA::map::getresidx();
                   12885:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12886:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12887:                                       $title;
1.1075.2.128  raeburn  12888:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   12889:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12890:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
1.1067    raeburn  12891:                                 }
1.1075.2.128  raeburn  12892:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12893:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12894:                                 }
                   12895:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12896:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   12897:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   12898:                                         unless ($ishome) {
                   12899:                                             my $fetch = "$newdest{$i}/$title";
                   12900:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   12901:                                             $prompttofetch{$fetch} = 1;
                   12902:                                         }
                   12903:                                    }
                   12904:                                 }
                   12905:                                 $LONCAPA::map::resources[$newidx]=
                   12906:                                     $docstitle.':'.$url.':false:normal:res';
                   12907:                                 push(@LONCAPA::map::order, $newidx);
                   12908:                                 my ($outtext,$errtext)=
                   12909:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12910:                                                             $docuname.'/'.$folders{$outer}.
                   12911:                                                             '.'.$containers{$outer},1,1);
                   12912:                                 unless ($errtext) {
                   12913:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12914:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   12915:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   12916:                                                    '</li>'."\n";
                   12917:                                     }
1.1067    raeburn  12918:                                 }
1.1075.2.128  raeburn  12919:                             } else {
                   12920:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   12921:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1067    raeburn  12922:                             }
1.1055    raeburn  12923:                         }
                   12924:                     }
1.1075.2.11  raeburn  12925:                 }
                   12926:             } else {
1.1075.2.128  raeburn  12927:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   12928:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1075.2.11  raeburn  12929:             }
                   12930:         }
                   12931:         for (my $i=1; $i<=$numitems; $i++) {
                   12932:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12933:             my $path = $env{'form.archive_content_'.$i};
                   12934:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12935:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12936:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12937:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12938:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12939:                         my ($itemidx,$fullpath,$relpath);
                   12940:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12941:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12942:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  12943:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12944:                                     $itemidx = $j;
1.1056    raeburn  12945:                                 }
                   12946:                             }
1.1075.2.11  raeburn  12947:                         }
                   12948:                         if ($itemidx eq '') {
                   12949:                             $itemidx =  0;
                   12950:                         }
                   12951:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12952:                             if ($mapinner{$referrer{$i}}) {
                   12953:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12954:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12955:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12956:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12957:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12958:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12959:                                             if (!-e $fullpath) {
                   12960:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12961:                                             }
                   12962:                                         }
1.1075.2.11  raeburn  12963:                                     } else {
                   12964:                                         last;
1.1056    raeburn  12965:                                     }
1.1075.2.11  raeburn  12966:                                 }
                   12967:                             }
                   12968:                         } elsif ($newdest{$referrer{$i}}) {
                   12969:                             $fullpath = $newdest{$referrer{$i}};
                   12970:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12971:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12972:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12973:                                     last;
                   12974:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12975:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12976:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12977:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12978:                                         if (!-e $fullpath) {
                   12979:                                             mkdir($fullpath,0755);
1.1056    raeburn  12980:                                         }
                   12981:                                     }
1.1075.2.11  raeburn  12982:                                 } else {
                   12983:                                     last;
1.1056    raeburn  12984:                                 }
1.1075.2.11  raeburn  12985:                             }
                   12986:                         }
                   12987:                         if ($fullpath ne '') {
                   12988:                             if (-e "$prefix$path") {
1.1075.2.128  raeburn  12989:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   12990:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   12991:                                 }
1.1075.2.11  raeburn  12992:                             }
                   12993:                             if (-e "$fullpath/$title") {
                   12994:                                 my $showpath;
                   12995:                                 if ($relpath ne '') {
                   12996:                                     $showpath = "$relpath/$title";
                   12997:                                 } else {
                   12998:                                     $showpath = "/$title";
1.1056    raeburn  12999:                                 }
1.1075.2.128  raeburn  13000:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13001:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13002:                                            '</li>'."\n";
                   13003:                                 unless ($ishome) {
                   13004:                                     my $fetch = "$fullpath/$title";
                   13005:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13006:                                     $prompttofetch{$fetch} = 1;
                   13007:                                 }
1.1055    raeburn  13008:                             }
                   13009:                         }
                   13010:                     }
1.1075.2.11  raeburn  13011:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13012:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1075.2.128  raeburn  13013:                                     &HTML::Entities::encode($path,'<>&"'),
                   13014:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13015:                                 '<br />';
1.1055    raeburn  13016:                 }
                   13017:             } else {
1.1075.2.128  raeburn  13018:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13019:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13020:             }
                   13021:         }
                   13022:         if (keys(%todelete)) {
                   13023:             foreach my $key (keys(%todelete)) {
                   13024:                 unlink($key);
1.1066    raeburn  13025:             }
                   13026:         }
                   13027:         if (keys(%todeletedir)) {
                   13028:             foreach my $key (keys(%todeletedir)) {
                   13029:                 rmdir($key);
                   13030:             }
                   13031:         }
                   13032:         foreach my $dir (sort(keys(%is_dir))) {
                   13033:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13034:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13035:             }
                   13036:         }
1.1067    raeburn  13037:         if ($result ne '') {
                   13038:             $output .= '<ul>'."\n".
                   13039:                        $result."\n".
                   13040:                        '</ul>';
                   13041:         }
                   13042:         unless ($ishome) {
                   13043:             my $replicationfail;
                   13044:             foreach my $item (keys(%prompttofetch)) {
                   13045:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13046:                 unless ($fetchresult eq 'ok') {
                   13047:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13048:                 }
                   13049:             }
                   13050:             if ($replicationfail) {
                   13051:                 $output .= '<p class="LC_error">'.
                   13052:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13053:                            $replicationfail.
                   13054:                            '</ul></p>';
                   13055:             }
                   13056:         }
1.1055    raeburn  13057:     } else {
                   13058:         $warning = &mt('No items found in archive.');
                   13059:     }
                   13060:     if ($error) {
                   13061:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13062:                    $error.'</p>'."\n";
                   13063:     }
                   13064:     if ($warning) {
                   13065:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13066:     }
                   13067:     return $output;
                   13068: }
                   13069: 
1.1066    raeburn  13070: sub cleanup_empty_dirs {
                   13071:     my ($path) = @_;
                   13072:     if (($path ne '') && (-d $path)) {
                   13073:         if (opendir(my $dirh,$path)) {
                   13074:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13075:             my $numitems = 0;
                   13076:             foreach my $item (@dircontents) {
                   13077:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  13078:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13079:                     if (-e "$path/$item") {
                   13080:                         $numitems ++;
                   13081:                     }
                   13082:                 } else {
                   13083:                     $numitems ++;
                   13084:                 }
                   13085:             }
                   13086:             if ($numitems == 0) {
                   13087:                 rmdir($path);
                   13088:             }
                   13089:             closedir($dirh);
                   13090:         }
                   13091:     }
                   13092:     return;
                   13093: }
                   13094: 
1.41      ng       13095: =pod
1.45      matthew  13096: 
1.1075.2.56  raeburn  13097: =item * &get_folder_hierarchy()
1.1068    raeburn  13098: 
                   13099: Provides hierarchy of names of folders/sub-folders containing the current
                   13100: item,
                   13101: 
                   13102: Inputs: 3
                   13103:      - $navmap - navmaps object
                   13104: 
                   13105:      - $map - url for map (either the trigger itself, or map containing
                   13106:                            the resource, which is the trigger).
                   13107: 
                   13108:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13109: 
                   13110: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13111: 
                   13112: =cut
                   13113: 
                   13114: sub get_folder_hierarchy {
                   13115:     my ($navmap,$map,$showitem) = @_;
                   13116:     my @pathitems;
                   13117:     if (ref($navmap)) {
                   13118:         my $mapres = $navmap->getResourceByUrl($map);
                   13119:         if (ref($mapres)) {
                   13120:             my $pcslist = $mapres->map_hierarchy();
                   13121:             if ($pcslist ne '') {
                   13122:                 my @pcs = split(/,/,$pcslist);
                   13123:                 foreach my $pc (@pcs) {
                   13124:                     if ($pc == 1) {
1.1075.2.38  raeburn  13125:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13126:                     } else {
                   13127:                         my $res = $navmap->getByMapPc($pc);
                   13128:                         if (ref($res)) {
                   13129:                             my $title = $res->compTitle();
                   13130:                             $title =~ s/\W+/_/g;
                   13131:                             if ($title ne '') {
                   13132:                                 push(@pathitems,$title);
                   13133:                             }
                   13134:                         }
                   13135:                     }
                   13136:                 }
                   13137:             }
1.1071    raeburn  13138:             if ($showitem) {
                   13139:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  13140:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13141:                 } else {
                   13142:                     my $maptitle = $mapres->compTitle();
                   13143:                     $maptitle =~ s/\W+/_/g;
                   13144:                     if ($maptitle ne '') {
                   13145:                         push(@pathitems,$maptitle);
                   13146:                     }
1.1068    raeburn  13147:                 }
                   13148:             }
                   13149:         }
                   13150:     }
                   13151:     return @pathitems;
                   13152: }
                   13153: 
                   13154: =pod
                   13155: 
1.1015    raeburn  13156: =item * &get_turnedin_filepath()
                   13157: 
                   13158: Determines path in a user's portfolio file for storage of files uploaded
                   13159: to a specific essayresponse or dropbox item.
                   13160: 
                   13161: Inputs: 3 required + 1 optional.
                   13162: $symb is symb for resource, $uname and $udom are for current user (required).
                   13163: $caller is optional (can be "submission", if routine is called when storing
                   13164: an upoaded file when "Submit Answer" button was pressed).
                   13165: 
                   13166: Returns array containing $path and $multiresp. 
                   13167: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13168: than one file upload item.  Callers of routine should append partid as a 
                   13169: subdirectory to $path in cases where $multiresp is 1.
                   13170: 
                   13171: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13172: 
                   13173: =cut
                   13174: 
                   13175: sub get_turnedin_filepath {
                   13176:     my ($symb,$uname,$udom,$caller) = @_;
                   13177:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13178:     my $turnindir;
                   13179:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13180:     $turnindir = $userhash{'turnindir'};
                   13181:     my ($path,$multiresp);
                   13182:     if ($turnindir eq '') {
                   13183:         if ($caller eq 'submission') {
                   13184:             $turnindir = &mt('turned in');
                   13185:             $turnindir =~ s/\W+/_/g;
                   13186:             my %newhash = (
                   13187:                             'turnindir' => $turnindir,
                   13188:                           );
                   13189:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13190:         }
                   13191:     }
                   13192:     if ($turnindir ne '') {
                   13193:         $path = '/'.$turnindir.'/';
                   13194:         my ($multipart,$turnin,@pathitems);
                   13195:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13196:         if (defined($navmap)) {
                   13197:             my $mapres = $navmap->getResourceByUrl($map);
                   13198:             if (ref($mapres)) {
                   13199:                 my $pcslist = $mapres->map_hierarchy();
                   13200:                 if ($pcslist ne '') {
                   13201:                     foreach my $pc (split(/,/,$pcslist)) {
                   13202:                         my $res = $navmap->getByMapPc($pc);
                   13203:                         if (ref($res)) {
                   13204:                             my $title = $res->compTitle();
                   13205:                             $title =~ s/\W+/_/g;
                   13206:                             if ($title ne '') {
1.1075.2.48  raeburn  13207:                                 if (($pc > 1) && (length($title) > 12)) {
                   13208:                                     $title = substr($title,0,12);
                   13209:                                 }
1.1015    raeburn  13210:                                 push(@pathitems,$title);
                   13211:                             }
                   13212:                         }
                   13213:                     }
                   13214:                 }
                   13215:                 my $maptitle = $mapres->compTitle();
                   13216:                 $maptitle =~ s/\W+/_/g;
                   13217:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  13218:                     if (length($maptitle) > 12) {
                   13219:                         $maptitle = substr($maptitle,0,12);
                   13220:                     }
1.1015    raeburn  13221:                     push(@pathitems,$maptitle);
                   13222:                 }
                   13223:                 unless ($env{'request.state'} eq 'construct') {
                   13224:                     my $res = $navmap->getBySymb($symb);
                   13225:                     if (ref($res)) {
                   13226:                         my $partlist = $res->parts();
                   13227:                         my $totaluploads = 0;
                   13228:                         if (ref($partlist) eq 'ARRAY') {
                   13229:                             foreach my $part (@{$partlist}) {
                   13230:                                 my @types = $res->responseType($part);
                   13231:                                 my @ids = $res->responseIds($part);
                   13232:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13233:                                     if ($types[$i] eq 'essay') {
                   13234:                                         my $partid = $part.'_'.$ids[$i];
                   13235:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13236:                                             $totaluploads ++;
                   13237:                                         }
                   13238:                                     }
                   13239:                                 }
                   13240:                             }
                   13241:                             if ($totaluploads > 1) {
                   13242:                                 $multiresp = 1;
                   13243:                             }
                   13244:                         }
                   13245:                     }
                   13246:                 }
                   13247:             } else {
                   13248:                 return;
                   13249:             }
                   13250:         } else {
                   13251:             return;
                   13252:         }
                   13253:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13254:         $restitle =~ s/\W+/_/g;
                   13255:         if ($restitle eq '') {
                   13256:             $restitle = ($resurl =~ m{/[^/]+$});
                   13257:             if ($restitle eq '') {
                   13258:                 $restitle = time;
                   13259:             }
                   13260:         }
1.1075.2.48  raeburn  13261:         if (length($restitle) > 12) {
                   13262:             $restitle = substr($restitle,0,12);
                   13263:         }
1.1015    raeburn  13264:         push(@pathitems,$restitle);
                   13265:         $path .= join('/',@pathitems);
                   13266:     }
                   13267:     return ($path,$multiresp);
                   13268: }
                   13269: 
                   13270: =pod
                   13271: 
1.464     albertel 13272: =back
1.41      ng       13273: 
1.112     bowersj2 13274: =head1 CSV Upload/Handling functions
1.38      albertel 13275: 
1.41      ng       13276: =over 4
                   13277: 
1.648     raeburn  13278: =item * &upfile_store($r)
1.41      ng       13279: 
                   13280: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13281: needs $env{'form.upfile'}
1.41      ng       13282: returns $datatoken to be put into hidden field
                   13283: 
                   13284: =cut
1.31      albertel 13285: 
                   13286: sub upfile_store {
                   13287:     my $r=shift;
1.258     albertel 13288:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13289:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13290:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13291:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13292: 
1.1075.2.128  raeburn  13293:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   13294:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   13295:                                      time.'_'.$$);
                   13296:     return if ($datatoken eq '');
                   13297: 
1.31      albertel 13298:     {
1.158     raeburn  13299:         my $datafile = $r->dir_config('lonDaemons').
                   13300:                            '/tmp/'.$datatoken.'.tmp';
1.1075.2.128  raeburn  13301:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 13302:             print $fh $env{'form.upfile'};
1.158     raeburn  13303:             close($fh);
                   13304:         }
1.31      albertel 13305:     }
                   13306:     return $datatoken;
                   13307: }
                   13308: 
1.56      matthew  13309: =pod
                   13310: 
1.1075.2.128  raeburn  13311: =item * &load_tmp_file($r,$datatoken)
1.41      ng       13312: 
                   13313: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1075.2.128  raeburn  13314: $datatoken is the name to assign to the temporary file.
1.258     albertel 13315: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13316: 
                   13317: =cut
1.31      albertel 13318: 
                   13319: sub load_tmp_file {
1.1075.2.128  raeburn  13320:     my ($r,$datatoken) = @_;
                   13321:     return if ($datatoken eq '');
1.31      albertel 13322:     my @studentdata=();
                   13323:     {
1.158     raeburn  13324:         my $studentfile = $r->dir_config('lonDaemons').
1.1075.2.128  raeburn  13325:                               '/tmp/'.$datatoken.'.tmp';
                   13326:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  13327:             @studentdata=<$fh>;
                   13328:             close($fh);
                   13329:         }
1.31      albertel 13330:     }
1.258     albertel 13331:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13332: }
                   13333: 
1.1075.2.128  raeburn  13334: sub valid_datatoken {
                   13335:     my ($datatoken) = @_;
1.1075.2.131  raeburn  13336:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1075.2.128  raeburn  13337:         return $datatoken;
                   13338:     }
                   13339:     return;
                   13340: }
                   13341: 
1.56      matthew  13342: =pod
                   13343: 
1.648     raeburn  13344: =item * &upfile_record_sep()
1.41      ng       13345: 
                   13346: Separate uploaded file into records
                   13347: returns array of records,
1.258     albertel 13348: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13349: 
                   13350: =cut
1.31      albertel 13351: 
                   13352: sub upfile_record_sep {
1.258     albertel 13353:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13354:     } else {
1.248     albertel 13355: 	my @records;
1.258     albertel 13356: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13357: 	    if ($line=~/^\s*$/) { next; }
                   13358: 	    push(@records,$line);
                   13359: 	}
                   13360: 	return @records;
1.31      albertel 13361:     }
                   13362: }
                   13363: 
1.56      matthew  13364: =pod
                   13365: 
1.648     raeburn  13366: =item * &record_sep($record)
1.41      ng       13367: 
1.258     albertel 13368: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13369: 
                   13370: =cut
                   13371: 
1.263     www      13372: sub takeleft {
                   13373:     my $index=shift;
                   13374:     return substr('0000'.$index,-4,4);
                   13375: }
                   13376: 
1.31      albertel 13377: sub record_sep {
                   13378:     my $record=shift;
                   13379:     my %components=();
1.258     albertel 13380:     if ($env{'form.upfiletype'} eq 'xml') {
                   13381:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13382:         my $i=0;
1.356     albertel 13383:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13384:             $field=~s/^(\"|\')//;
                   13385:             $field=~s/(\"|\')$//;
1.263     www      13386:             $components{&takeleft($i)}=$field;
1.31      albertel 13387:             $i++;
                   13388:         }
1.258     albertel 13389:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13390:         my $i=0;
1.356     albertel 13391:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13392:             $field=~s/^(\"|\')//;
                   13393:             $field=~s/(\"|\')$//;
1.263     www      13394:             $components{&takeleft($i)}=$field;
1.31      albertel 13395:             $i++;
                   13396:         }
                   13397:     } else {
1.561     www      13398:         my $separator=',';
1.480     banghart 13399:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13400:             $separator=';';
1.480     banghart 13401:         }
1.31      albertel 13402:         my $i=0;
1.561     www      13403: # the character we are looking for to indicate the end of a quote or a record 
                   13404:         my $looking_for=$separator;
                   13405: # do not add the characters to the fields
                   13406:         my $ignore=0;
                   13407: # we just encountered a separator (or the beginning of the record)
                   13408:         my $just_found_separator=1;
                   13409: # store the field we are working on here
                   13410:         my $field='';
                   13411: # work our way through all characters in record
                   13412:         foreach my $character ($record=~/(.)/g) {
                   13413:             if ($character eq $looking_for) {
                   13414:                if ($character ne $separator) {
                   13415: # Found the end of a quote, again looking for separator
                   13416:                   $looking_for=$separator;
                   13417:                   $ignore=1;
                   13418:                } else {
                   13419: # Found a separator, store away what we got
                   13420:                   $components{&takeleft($i)}=$field;
                   13421: 	          $i++;
                   13422:                   $just_found_separator=1;
                   13423:                   $ignore=0;
                   13424:                   $field='';
                   13425:                }
                   13426:                next;
                   13427:             }
                   13428: # single or double quotation marks after a separator indicate beginning of a quote
                   13429: # we are now looking for the end of the quote and need to ignore separators
                   13430:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13431:                $looking_for=$character;
                   13432:                next;
                   13433:             }
                   13434: # ignore would be true after we reached the end of a quote
                   13435:             if ($ignore) { next; }
                   13436:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13437:             $field.=$character;
                   13438:             $just_found_separator=0; 
1.31      albertel 13439:         }
1.561     www      13440: # catch the very last entry, since we never encountered the separator
                   13441:         $components{&takeleft($i)}=$field;
1.31      albertel 13442:     }
                   13443:     return %components;
                   13444: }
                   13445: 
1.144     matthew  13446: ######################################################
                   13447: ######################################################
                   13448: 
1.56      matthew  13449: =pod
                   13450: 
1.648     raeburn  13451: =item * &upfile_select_html()
1.41      ng       13452: 
1.144     matthew  13453: Return HTML code to select a file from the users machine and specify 
                   13454: the file type.
1.41      ng       13455: 
                   13456: =cut
                   13457: 
1.144     matthew  13458: ######################################################
                   13459: ######################################################
1.31      albertel 13460: sub upfile_select_html {
1.144     matthew  13461:     my %Types = (
                   13462:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13463:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13464:                  space => &mt('Space separated'),
                   13465:                  tab   => &mt('Tabulator separated'),
                   13466: #                 xml   => &mt('HTML/XML'),
                   13467:                  );
                   13468:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13469:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13470:     foreach my $type (sort(keys(%Types))) {
                   13471:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13472:     }
                   13473:     $Str .= "</select>\n";
                   13474:     return $Str;
1.31      albertel 13475: }
                   13476: 
1.301     albertel 13477: sub get_samples {
                   13478:     my ($records,$toget) = @_;
                   13479:     my @samples=({});
                   13480:     my $got=0;
                   13481:     foreach my $rec (@$records) {
                   13482: 	my %temp = &record_sep($rec);
                   13483: 	if (! grep(/\S/, values(%temp))) { next; }
                   13484: 	if (%temp) {
                   13485: 	    $samples[$got]=\%temp;
                   13486: 	    $got++;
                   13487: 	    if ($got == $toget) { last; }
                   13488: 	}
                   13489:     }
                   13490:     return \@samples;
                   13491: }
                   13492: 
1.144     matthew  13493: ######################################################
                   13494: ######################################################
                   13495: 
1.56      matthew  13496: =pod
                   13497: 
1.648     raeburn  13498: =item * &csv_print_samples($r,$records)
1.41      ng       13499: 
                   13500: Prints a table of sample values from each column uploaded $r is an
                   13501: Apache Request ref, $records is an arrayref from
                   13502: &Apache::loncommon::upfile_record_sep
                   13503: 
                   13504: =cut
                   13505: 
1.144     matthew  13506: ######################################################
                   13507: ######################################################
1.31      albertel 13508: sub csv_print_samples {
                   13509:     my ($r,$records) = @_;
1.662     bisitz   13510:     my $samples = &get_samples($records,5);
1.301     albertel 13511: 
1.594     raeburn  13512:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13513:               &start_data_table_header_row());
1.356     albertel 13514:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13515:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13516:     $r->print(&end_data_table_header_row());
1.301     albertel 13517:     foreach my $hash (@$samples) {
1.594     raeburn  13518: 	$r->print(&start_data_table_row());
1.356     albertel 13519: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13520: 	    $r->print('<td>');
1.356     albertel 13521: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13522: 	    $r->print('</td>');
                   13523: 	}
1.594     raeburn  13524: 	$r->print(&end_data_table_row());
1.31      albertel 13525:     }
1.594     raeburn  13526:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13527: }
                   13528: 
1.144     matthew  13529: ######################################################
                   13530: ######################################################
                   13531: 
1.56      matthew  13532: =pod
                   13533: 
1.648     raeburn  13534: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13535: 
                   13536: Prints a table to create associations between values and table columns.
1.144     matthew  13537: 
1.41      ng       13538: $r is an Apache Request ref,
                   13539: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13540: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13541: 
                   13542: =cut
                   13543: 
1.144     matthew  13544: ######################################################
                   13545: ######################################################
1.31      albertel 13546: sub csv_print_select_table {
                   13547:     my ($r,$records,$d) = @_;
1.301     albertel 13548:     my $i=0;
                   13549:     my $samples = &get_samples($records,1);
1.144     matthew  13550:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13551: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13552:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13553:               '<th>'.&mt('Column').'</th>'.
                   13554:               &end_data_table_header_row()."\n");
1.356     albertel 13555:     foreach my $array_ref (@$d) {
                   13556: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13557: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13558: 
1.875     bisitz   13559: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13560: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13561: 	$r->print('<option value="none"></option>');
1.356     albertel 13562: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13563: 	    $r->print('<option value="'.$sample.'"'.
                   13564:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13565:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13566: 	}
1.594     raeburn  13567: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13568: 	$i++;
                   13569:     }
1.594     raeburn  13570:     $r->print(&end_data_table());
1.31      albertel 13571:     $i--;
                   13572:     return $i;
                   13573: }
1.56      matthew  13574: 
1.144     matthew  13575: ######################################################
                   13576: ######################################################
                   13577: 
1.56      matthew  13578: =pod
1.31      albertel 13579: 
1.648     raeburn  13580: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13581: 
                   13582: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13583: 
                   13584: $r is an Apache Request ref,
                   13585: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13586: $d is an array of 2 element arrays (internal name, displayed name)
                   13587: 
                   13588: =cut
                   13589: 
1.144     matthew  13590: ######################################################
                   13591: ######################################################
1.31      albertel 13592: sub csv_samples_select_table {
                   13593:     my ($r,$records,$d) = @_;
                   13594:     my $i=0;
1.144     matthew  13595:     #
1.662     bisitz   13596:     my $max_samples = 5;
                   13597:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13598:     $r->print(&start_data_table().
                   13599:               &start_data_table_header_row().'<th>'.
                   13600:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13601:               &end_data_table_header_row());
1.301     albertel 13602: 
                   13603:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13604: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13605: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13606: 	foreach my $option (@$d) {
                   13607: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13608: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13609:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13610:                       $display.'</option>');
1.31      albertel 13611: 	}
                   13612: 	$r->print('</select></td><td>');
1.662     bisitz   13613: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13614: 	    if (defined($samples->[$line]{$key})) { 
                   13615: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13616: 	    }
                   13617: 	}
1.594     raeburn  13618: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13619: 	$i++;
                   13620:     }
1.594     raeburn  13621:     $r->print(&end_data_table());
1.31      albertel 13622:     $i--;
                   13623:     return($i);
1.115     matthew  13624: }
                   13625: 
1.144     matthew  13626: ######################################################
                   13627: ######################################################
                   13628: 
1.115     matthew  13629: =pod
                   13630: 
1.648     raeburn  13631: =item * &clean_excel_name($name)
1.115     matthew  13632: 
                   13633: Returns a replacement for $name which does not contain any illegal characters.
                   13634: 
                   13635: =cut
                   13636: 
1.144     matthew  13637: ######################################################
                   13638: ######################################################
1.115     matthew  13639: sub clean_excel_name {
                   13640:     my ($name) = @_;
                   13641:     $name =~ s/[:\*\?\/\\]//g;
                   13642:     if (length($name) > 31) {
                   13643:         $name = substr($name,0,31);
                   13644:     }
                   13645:     return $name;
1.25      albertel 13646: }
1.84      albertel 13647: 
1.85      albertel 13648: =pod
                   13649: 
1.648     raeburn  13650: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13651: 
                   13652: Returns either 1 or undef
                   13653: 
                   13654: 1 if the part is to be hidden, undef if it is to be shown
                   13655: 
                   13656: Arguments are:
                   13657: 
                   13658: $id the id of the part to be checked
                   13659: $symb, optional the symb of the resource to check
                   13660: $udom, optional the domain of the user to check for
                   13661: $uname, optional the username of the user to check for
                   13662: 
                   13663: =cut
1.84      albertel 13664: 
                   13665: sub check_if_partid_hidden {
                   13666:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13667:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13668: 					 $symb,$udom,$uname);
1.141     albertel 13669:     my $truth=1;
                   13670:     #if the string starts with !, then the list is the list to show not hide
                   13671:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13672:     my @hiddenlist=split(/,/,$hiddenparts);
                   13673:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13674: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13675:     }
1.141     albertel 13676:     return !$truth;
1.84      albertel 13677: }
1.127     matthew  13678: 
1.138     matthew  13679: 
                   13680: ############################################################
                   13681: ############################################################
                   13682: 
                   13683: =pod
                   13684: 
1.157     matthew  13685: =back 
                   13686: 
1.138     matthew  13687: =head1 cgi-bin script and graphing routines
                   13688: 
1.157     matthew  13689: =over 4
                   13690: 
1.648     raeburn  13691: =item * &get_cgi_id()
1.138     matthew  13692: 
                   13693: Inputs: none
                   13694: 
                   13695: Returns an id which can be used to pass environment variables
                   13696: to various cgi-bin scripts.  These environment variables will
                   13697: be removed from the users environment after a given time by
                   13698: the routine &Apache::lonnet::transfer_profile_to_env.
                   13699: 
                   13700: =cut
                   13701: 
                   13702: ############################################################
                   13703: ############################################################
1.152     albertel 13704: my $uniq=0;
1.136     matthew  13705: sub get_cgi_id {
1.154     albertel 13706:     $uniq=($uniq+1)%100000;
1.280     albertel 13707:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13708: }
                   13709: 
1.127     matthew  13710: ############################################################
                   13711: ############################################################
                   13712: 
                   13713: =pod
                   13714: 
1.648     raeburn  13715: =item * &DrawBarGraph()
1.127     matthew  13716: 
1.138     matthew  13717: Facilitates the plotting of data in a (stacked) bar graph.
                   13718: Puts plot definition data into the users environment in order for 
                   13719: graph.png to plot it.  Returns an <img> tag for the plot.
                   13720: The bars on the plot are labeled '1','2',...,'n'.
                   13721: 
                   13722: Inputs:
                   13723: 
                   13724: =over 4
                   13725: 
                   13726: =item $Title: string, the title of the plot
                   13727: 
                   13728: =item $xlabel: string, text describing the X-axis of the plot
                   13729: 
                   13730: =item $ylabel: string, text describing the Y-axis of the plot
                   13731: 
                   13732: =item $Max: scalar, the maximum Y value to use in the plot
                   13733: If $Max is < any data point, the graph will not be rendered.
                   13734: 
1.140     matthew  13735: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13736: they are plotted.  If undefined, default values will be used.
                   13737: 
1.178     matthew  13738: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13739: 
1.138     matthew  13740: =item @Values: An array of array references.  Each array reference holds data
                   13741: to be plotted in a stacked bar chart.
                   13742: 
1.239     matthew  13743: =item If the final element of @Values is a hash reference the key/value
                   13744: pairs will be added to the graph definition.
                   13745: 
1.138     matthew  13746: =back
                   13747: 
                   13748: Returns:
                   13749: 
                   13750: An <img> tag which references graph.png and the appropriate identifying
                   13751: information for the plot.
                   13752: 
1.127     matthew  13753: =cut
                   13754: 
                   13755: ############################################################
                   13756: ############################################################
1.134     matthew  13757: sub DrawBarGraph {
1.178     matthew  13758:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13759:     #
                   13760:     if (! defined($colors)) {
                   13761:         $colors = ['#33ff00', 
                   13762:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13763:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13764:                   ]; 
                   13765:     }
1.228     matthew  13766:     my $extra_settings = {};
                   13767:     if (ref($Values[-1]) eq 'HASH') {
                   13768:         $extra_settings = pop(@Values);
                   13769:     }
1.127     matthew  13770:     #
1.136     matthew  13771:     my $identifier = &get_cgi_id();
                   13772:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13773:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13774:         return '';
                   13775:     }
1.225     matthew  13776:     #
                   13777:     my @Labels;
                   13778:     if (defined($labels)) {
                   13779:         @Labels = @$labels;
                   13780:     } else {
                   13781:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  13782:             push(@Labels,$i+1);
1.225     matthew  13783:         }
                   13784:     }
                   13785:     #
1.129     matthew  13786:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13787:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13788:     my %ValuesHash;
                   13789:     my $NumSets=1;
                   13790:     foreach my $array (@Values) {
                   13791:         next if (! ref($array));
1.136     matthew  13792:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13793:             join(',',@$array);
1.129     matthew  13794:     }
1.127     matthew  13795:     #
1.136     matthew  13796:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13797:     if ($NumBars < 3) {
                   13798:         $width = 120+$NumBars*32;
1.220     matthew  13799:         $xskip = 1;
1.225     matthew  13800:         $bar_width = 30;
                   13801:     } elsif ($NumBars < 5) {
                   13802:         $width = 120+$NumBars*20;
                   13803:         $xskip = 1;
                   13804:         $bar_width = 20;
1.220     matthew  13805:     } elsif ($NumBars < 10) {
1.136     matthew  13806:         $width = 120+$NumBars*15;
                   13807:         $xskip = 1;
                   13808:         $bar_width = 15;
                   13809:     } elsif ($NumBars <= 25) {
                   13810:         $width = 120+$NumBars*11;
                   13811:         $xskip = 5;
                   13812:         $bar_width = 8;
                   13813:     } elsif ($NumBars <= 50) {
                   13814:         $width = 120+$NumBars*8;
                   13815:         $xskip = 5;
                   13816:         $bar_width = 4;
                   13817:     } else {
                   13818:         $width = 120+$NumBars*8;
                   13819:         $xskip = 5;
                   13820:         $bar_width = 4;
                   13821:     }
                   13822:     #
1.137     matthew  13823:     $Max = 1 if ($Max < 1);
                   13824:     if ( int($Max) < $Max ) {
                   13825:         $Max++;
                   13826:         $Max = int($Max);
                   13827:     }
1.127     matthew  13828:     $Title  = '' if (! defined($Title));
                   13829:     $xlabel = '' if (! defined($xlabel));
                   13830:     $ylabel = '' if (! defined($ylabel));
1.369     www      13831:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13832:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13833:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13834:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13835:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13836:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13837:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13838:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13839:     $ValuesHash{$id.'.height'}   = $height;
                   13840:     $ValuesHash{$id.'.width'}    = $width;
                   13841:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13842:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13843:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13844:     #
1.228     matthew  13845:     # Deal with other parameters
                   13846:     while (my ($key,$value) = each(%$extra_settings)) {
                   13847:         $ValuesHash{$id.'.'.$key} = $value;
                   13848:     }
                   13849:     #
1.646     raeburn  13850:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13851:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13852: }
                   13853: 
                   13854: ############################################################
                   13855: ############################################################
                   13856: 
                   13857: =pod
                   13858: 
1.648     raeburn  13859: =item * &DrawXYGraph()
1.137     matthew  13860: 
1.138     matthew  13861: Facilitates the plotting of data in an XY graph.
                   13862: Puts plot definition data into the users environment in order for 
                   13863: graph.png to plot it.  Returns an <img> tag for the plot.
                   13864: 
                   13865: Inputs:
                   13866: 
                   13867: =over 4
                   13868: 
                   13869: =item $Title: string, the title of the plot
                   13870: 
                   13871: =item $xlabel: string, text describing the X-axis of the plot
                   13872: 
                   13873: =item $ylabel: string, text describing the Y-axis of the plot
                   13874: 
                   13875: =item $Max: scalar, the maximum Y value to use in the plot
                   13876: If $Max is < any data point, the graph will not be rendered.
                   13877: 
                   13878: =item $colors: Array ref containing the hex color codes for the data to be 
                   13879: plotted in.  If undefined, default values will be used.
                   13880: 
                   13881: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13882: 
                   13883: =item $Ydata: Array ref containing Array refs.  
1.185     www      13884: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13885: 
                   13886: =item %Values: hash indicating or overriding any default values which are 
                   13887: passed to graph.png.  
                   13888: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13889: 
                   13890: =back
                   13891: 
                   13892: Returns:
                   13893: 
                   13894: An <img> tag which references graph.png and the appropriate identifying
                   13895: information for the plot.
                   13896: 
1.137     matthew  13897: =cut
                   13898: 
                   13899: ############################################################
                   13900: ############################################################
                   13901: sub DrawXYGraph {
                   13902:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13903:     #
                   13904:     # Create the identifier for the graph
                   13905:     my $identifier = &get_cgi_id();
                   13906:     my $id = 'cgi.'.$identifier;
                   13907:     #
                   13908:     $Title  = '' if (! defined($Title));
                   13909:     $xlabel = '' if (! defined($xlabel));
                   13910:     $ylabel = '' if (! defined($ylabel));
                   13911:     my %ValuesHash = 
                   13912:         (
1.369     www      13913:          $id.'.title'  => &escape($Title),
                   13914:          $id.'.xlabel' => &escape($xlabel),
                   13915:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13916:          $id.'.y_max_value'=> $Max,
                   13917:          $id.'.labels'     => join(',',@$Xlabels),
                   13918:          $id.'.PlotType'   => 'XY',
                   13919:          );
                   13920:     #
                   13921:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13922:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13923:     }
                   13924:     #
                   13925:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13926:         return '';
                   13927:     }
                   13928:     my $NumSets=1;
1.138     matthew  13929:     foreach my $array (@{$Ydata}){
1.137     matthew  13930:         next if (! ref($array));
                   13931:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13932:     }
1.138     matthew  13933:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13934:     #
                   13935:     # Deal with other parameters
                   13936:     while (my ($key,$value) = each(%Values)) {
                   13937:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13938:     }
                   13939:     #
1.646     raeburn  13940:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13941:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13942: }
                   13943: 
                   13944: ############################################################
                   13945: ############################################################
                   13946: 
                   13947: =pod
                   13948: 
1.648     raeburn  13949: =item * &DrawXYYGraph()
1.138     matthew  13950: 
                   13951: Facilitates the plotting of data in an XY graph with two Y axes.
                   13952: Puts plot definition data into the users environment in order for 
                   13953: graph.png to plot it.  Returns an <img> tag for the plot.
                   13954: 
                   13955: Inputs:
                   13956: 
                   13957: =over 4
                   13958: 
                   13959: =item $Title: string, the title of the plot
                   13960: 
                   13961: =item $xlabel: string, text describing the X-axis of the plot
                   13962: 
                   13963: =item $ylabel: string, text describing the Y-axis of the plot
                   13964: 
                   13965: =item $colors: Array ref containing the hex color codes for the data to be 
                   13966: plotted in.  If undefined, default values will be used.
                   13967: 
                   13968: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13969: 
                   13970: =item $Ydata1: The first data set
                   13971: 
                   13972: =item $Min1: The minimum value of the left Y-axis
                   13973: 
                   13974: =item $Max1: The maximum value of the left Y-axis
                   13975: 
                   13976: =item $Ydata2: The second data set
                   13977: 
                   13978: =item $Min2: The minimum value of the right Y-axis
                   13979: 
                   13980: =item $Max2: The maximum value of the left Y-axis
                   13981: 
                   13982: =item %Values: hash indicating or overriding any default values which are 
                   13983: passed to graph.png.  
                   13984: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13985: 
                   13986: =back
                   13987: 
                   13988: Returns:
                   13989: 
                   13990: An <img> tag which references graph.png and the appropriate identifying
                   13991: information for the plot.
1.136     matthew  13992: 
                   13993: =cut
                   13994: 
                   13995: ############################################################
                   13996: ############################################################
1.137     matthew  13997: sub DrawXYYGraph {
                   13998:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13999:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14000:     #
                   14001:     # Create the identifier for the graph
                   14002:     my $identifier = &get_cgi_id();
                   14003:     my $id = 'cgi.'.$identifier;
                   14004:     #
                   14005:     $Title  = '' if (! defined($Title));
                   14006:     $xlabel = '' if (! defined($xlabel));
                   14007:     $ylabel = '' if (! defined($ylabel));
                   14008:     my %ValuesHash = 
                   14009:         (
1.369     www      14010:          $id.'.title'  => &escape($Title),
                   14011:          $id.'.xlabel' => &escape($xlabel),
                   14012:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14013:          $id.'.labels' => join(',',@$Xlabels),
                   14014:          $id.'.PlotType' => 'XY',
                   14015:          $id.'.NumSets' => 2,
1.137     matthew  14016:          $id.'.two_axes' => 1,
                   14017:          $id.'.y1_max_value' => $Max1,
                   14018:          $id.'.y1_min_value' => $Min1,
                   14019:          $id.'.y2_max_value' => $Max2,
                   14020:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14021:          );
                   14022:     #
1.137     matthew  14023:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14024:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14025:     }
                   14026:     #
                   14027:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14028:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14029:         return '';
                   14030:     }
                   14031:     my $NumSets=1;
1.137     matthew  14032:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14033:         next if (! ref($array));
                   14034:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14035:     }
                   14036:     #
                   14037:     # Deal with other parameters
                   14038:     while (my ($key,$value) = each(%Values)) {
                   14039:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14040:     }
                   14041:     #
1.646     raeburn  14042:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14043:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14044: }
                   14045: 
                   14046: ############################################################
                   14047: ############################################################
                   14048: 
                   14049: =pod
                   14050: 
1.157     matthew  14051: =back 
                   14052: 
1.139     matthew  14053: =head1 Statistics helper routines?  
                   14054: 
                   14055: Bad place for them but what the hell.
                   14056: 
1.157     matthew  14057: =over 4
                   14058: 
1.648     raeburn  14059: =item * &chartlink()
1.139     matthew  14060: 
                   14061: Returns a link to the chart for a specific student.  
                   14062: 
                   14063: Inputs:
                   14064: 
                   14065: =over 4
                   14066: 
                   14067: =item $linktext: The text of the link
                   14068: 
                   14069: =item $sname: The students username
                   14070: 
                   14071: =item $sdomain: The students domain
                   14072: 
                   14073: =back
                   14074: 
1.157     matthew  14075: =back
                   14076: 
1.139     matthew  14077: =cut
                   14078: 
                   14079: ############################################################
                   14080: ############################################################
                   14081: sub chartlink {
                   14082:     my ($linktext, $sname, $sdomain) = @_;
                   14083:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14084:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14085:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14086:        '">'.$linktext.'</a>';
1.153     matthew  14087: }
                   14088: 
                   14089: #######################################################
                   14090: #######################################################
                   14091: 
                   14092: =pod
                   14093: 
                   14094: =head1 Course Environment Routines
1.157     matthew  14095: 
                   14096: =over 4
1.153     matthew  14097: 
1.648     raeburn  14098: =item * &restore_course_settings()
1.153     matthew  14099: 
1.648     raeburn  14100: =item * &store_course_settings()
1.153     matthew  14101: 
                   14102: Restores/Store indicated form parameters from the course environment.
                   14103: Will not overwrite existing values of the form parameters.
                   14104: 
                   14105: Inputs: 
                   14106: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14107: 
                   14108: a hash ref describing the data to be stored.  For example:
                   14109:    
                   14110: %Save_Parameters = ('Status' => 'scalar',
                   14111:     'chartoutputmode' => 'scalar',
                   14112:     'chartoutputdata' => 'scalar',
                   14113:     'Section' => 'array',
1.373     raeburn  14114:     'Group' => 'array',
1.153     matthew  14115:     'StudentData' => 'array',
                   14116:     'Maps' => 'array');
                   14117: 
                   14118: Returns: both routines return nothing
                   14119: 
1.631     raeburn  14120: =back
                   14121: 
1.153     matthew  14122: =cut
                   14123: 
                   14124: #######################################################
                   14125: #######################################################
                   14126: sub store_course_settings {
1.496     albertel 14127:     return &store_settings($env{'request.course.id'},@_);
                   14128: }
                   14129: 
                   14130: sub store_settings {
1.153     matthew  14131:     # save to the environment
                   14132:     # appenv the same items, just to be safe
1.300     albertel 14133:     my $udom  = $env{'user.domain'};
                   14134:     my $uname = $env{'user.name'};
1.496     albertel 14135:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14136:     my %SaveHash;
                   14137:     my %AppHash;
                   14138:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14139:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14140:         my $envname = 'environment.'.$basename;
1.258     albertel 14141:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14142:             # Save this value away
                   14143:             if ($type eq 'scalar' &&
1.258     albertel 14144:                 (! exists($env{$envname}) || 
                   14145:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14146:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14147:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14148:             } elsif ($type eq 'array') {
                   14149:                 my $stored_form;
1.258     albertel 14150:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14151:                     $stored_form = join(',',
                   14152:                                         map {
1.369     www      14153:                                             &escape($_);
1.258     albertel 14154:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14155:                 } else {
                   14156:                     $stored_form = 
1.369     www      14157:                         &escape($env{'form.'.$setting});
1.153     matthew  14158:                 }
                   14159:                 # Determine if the array contents are the same.
1.258     albertel 14160:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14161:                     $SaveHash{$basename} = $stored_form;
                   14162:                     $AppHash{$envname}   = $stored_form;
                   14163:                 }
                   14164:             }
                   14165:         }
                   14166:     }
                   14167:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14168:                                           $udom,$uname);
1.153     matthew  14169:     if ($put_result !~ /^(ok|delayed)/) {
                   14170:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14171:                                  'got error:'.$put_result);
                   14172:     }
                   14173:     # Make sure these settings stick around in this session, too
1.646     raeburn  14174:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14175:     return;
                   14176: }
                   14177: 
                   14178: sub restore_course_settings {
1.499     albertel 14179:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14180: }
                   14181: 
                   14182: sub restore_settings {
                   14183:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14184:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14185:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14186:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14187:             '.'.$setting;
1.258     albertel 14188:         if (exists($env{$envname})) {
1.153     matthew  14189:             if ($type eq 'scalar') {
1.258     albertel 14190:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14191:             } elsif ($type eq 'array') {
1.258     albertel 14192:                 $env{'form.'.$setting} = [ 
1.153     matthew  14193:                                            map { 
1.369     www      14194:                                                &unescape($_); 
1.258     albertel 14195:                                            } split(',',$env{$envname})
1.153     matthew  14196:                                            ];
                   14197:             }
                   14198:         }
                   14199:     }
1.127     matthew  14200: }
                   14201: 
1.618     raeburn  14202: #######################################################
                   14203: #######################################################
                   14204: 
                   14205: =pod
                   14206: 
                   14207: =head1 Domain E-mail Routines  
                   14208: 
                   14209: =over 4
                   14210: 
1.648     raeburn  14211: =item * &build_recipient_list()
1.618     raeburn  14212: 
1.1075.2.44  raeburn  14213: Build recipient lists for following types of e-mail:
1.766     raeburn  14214: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  14215: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14216: module change checking, student/employee ID conflict checks, as
                   14217: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14218: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14219: 
                   14220: Inputs:
1.1075.2.44  raeburn  14221: defmail (scalar - email address of default recipient),
                   14222: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14223: requestsmail, updatesmail, or idconflictsmail).
                   14224: 
1.619     raeburn  14225: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  14226: 
                   14227: origmail (scalar - email address of recipient from loncapa.conf,
                   14228: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  14229: 
1.1075.2.139  raeburn  14230: $requname username of requester (if mailing type is helpdeskmail)
                   14231: 
                   14232: $requdom domain of requester (if mailing type is helpdeskmail)
                   14233: 
                   14234: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   14235: 
1.655     raeburn  14236: Returns: comma separated list of addresses to which to send e-mail.
                   14237: 
                   14238: =back
1.618     raeburn  14239: 
                   14240: =cut
                   14241: 
                   14242: ############################################################
                   14243: ############################################################
                   14244: sub build_recipient_list {
1.1075.2.139  raeburn  14245:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  14246:     my @recipients;
1.1075.2.122  raeburn  14247:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14248:     my %domconfig =
1.1075.2.122  raeburn  14249:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14250:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14251:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14252:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14253:                 my @contacts = ('adminemail','supportemail');
                   14254:                 foreach my $item (@contacts) {
                   14255:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14256:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14257:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14258:                             push(@recipients,$addr);
                   14259:                         }
1.619     raeburn  14260:                     }
1.1075.2.122  raeburn  14261:                 }
                   14262:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14263:                 if ($mailing eq 'helpdeskmail') {
                   14264:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14265:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14266:                         my @ok_bccs;
                   14267:                         foreach my $bcc (@bccs) {
                   14268:                             $bcc =~ s/^\s+//g;
                   14269:                             $bcc =~ s/\s+$//g;
                   14270:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14271:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14272:                                     push(@ok_bccs,$bcc);
                   14273:                                 }
                   14274:                             }
                   14275:                         }
                   14276:                         if (@ok_bccs > 0) {
                   14277:                             $allbcc = join(', ',@ok_bccs);
                   14278:                         }
                   14279:                     }
                   14280:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14281:                 }
                   14282:             }
1.766     raeburn  14283:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14284:             $lastresort = $origmail;
1.618     raeburn  14285:         }
1.1075.2.139  raeburn  14286:         if ($mailing eq 'helpdeskmail') {
                   14287:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   14288:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   14289:                 my ($inststatus,$inststatus_checked);
                   14290:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   14291:                     ($env{'user.domain'} ne 'public')) {
                   14292:                     $inststatus_checked = 1;
                   14293:                     $inststatus = $env{'environment.inststatus'};
                   14294:                 }
                   14295:                 unless ($inststatus_checked) {
                   14296:                     if (($requname ne '') && ($requdom ne '')) {
                   14297:                         if (($requname =~ /^$match_username$/) &&
                   14298:                             ($requdom =~ /^$match_domain$/) &&
                   14299:                             (&Apache::lonnet::domain($requdom))) {
                   14300:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   14301:                                                                       $requdom);
                   14302:                             unless ($requhome eq 'no_host') {
                   14303:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   14304:                                 $inststatus = $userenv{'inststatus'};
                   14305:                                 $inststatus_checked = 1;
                   14306:                             }
                   14307:                         }
                   14308:                     }
                   14309:                 }
                   14310:                 unless ($inststatus_checked) {
                   14311:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   14312:                         my %srch = (srchby     => 'email',
                   14313:                                     srchdomain => $defdom,
                   14314:                                     srchterm   => $reqemail,
                   14315:                                     srchtype   => 'exact');
                   14316:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   14317:                         foreach my $uname (keys(%srch_results)) {
                   14318:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14319:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14320:                                 $inststatus_checked = 1;
                   14321:                                 last;
                   14322:                             }
                   14323:                         }
                   14324:                         unless ($inststatus_checked) {
                   14325:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   14326:                             if ($dirsrchres eq 'ok') {
                   14327:                                 foreach my $uname (keys(%srch_results)) {
                   14328:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14329:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14330:                                         $inststatus_checked = 1;
                   14331:                                         last;
                   14332:                                     }
                   14333:                                 }
                   14334:                             }
                   14335:                         }
                   14336:                     }
                   14337:                 }
                   14338:                 if ($inststatus ne '') {
                   14339:                     foreach my $status (split(/\:/,$inststatus)) {
                   14340:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   14341:                             my @contacts = ('adminemail','supportemail');
                   14342:                             foreach my $item (@contacts) {
                   14343:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   14344:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   14345:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14346:                                         push(@recipients,$addr);
                   14347:                                     }
                   14348:                                 }
                   14349:                             }
                   14350:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   14351:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   14352:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   14353:                                 my @ok_bccs;
                   14354:                                 foreach my $bcc (@bccs) {
                   14355:                                     $bcc =~ s/^\s+//g;
                   14356:                                     $bcc =~ s/\s+$//g;
                   14357:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14358:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14359:                                             push(@ok_bccs,$bcc);
                   14360:                                         }
                   14361:                                     }
                   14362:                                 }
                   14363:                                 if (@ok_bccs > 0) {
                   14364:                                     $allbcc = join(', ',@ok_bccs);
                   14365:                                 }
                   14366:                             }
                   14367:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   14368:                             last;
                   14369:                         }
                   14370:                     }
                   14371:                 }
                   14372:             }
                   14373:         }
1.619     raeburn  14374:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14375:         $lastresort = $origmail;
                   14376:     }
1.1075.2.128  raeburn  14377:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1075.2.122  raeburn  14378:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14379:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14380:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14381:             my %what = (
                   14382:                           perlvar => 1,
                   14383:                        );
                   14384:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14385:             if ($primary) {
                   14386:                 my $gotaddr;
                   14387:                 my ($result,$returnhash) =
                   14388:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14389:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14390:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14391:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14392:                         $gotaddr = 1;
                   14393:                     }
                   14394:                 }
                   14395:                 unless ($gotaddr) {
                   14396:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14397:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14398:                     unless ($uintdom eq $intdom) {
                   14399:                         my %domconfig =
                   14400:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14401:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14402:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14403:                                 my @contacts = ('adminemail','supportemail');
                   14404:                                 foreach my $item (@contacts) {
                   14405:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14406:                                         my $addr = $domconfig{'contacts'}{$item};
                   14407:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14408:                                             push(@recipients,$addr);
                   14409:                                         }
                   14410:                                     }
                   14411:                                 }
                   14412:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14413:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14414:                                 }
                   14415:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14416:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14417:                                     my @ok_bccs;
                   14418:                                     foreach my $bcc (@bccs) {
                   14419:                                         $bcc =~ s/^\s+//g;
                   14420:                                         $bcc =~ s/\s+$//g;
                   14421:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14422:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14423:                                                 push(@ok_bccs,$bcc);
                   14424:                                             }
                   14425:                                         }
                   14426:                                     }
                   14427:                                     if (@ok_bccs > 0) {
                   14428:                                         $allbcc = join(', ',@ok_bccs);
                   14429:                                     }
                   14430:                                 }
                   14431:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14432:                             }
                   14433:                         }
                   14434:                     }
                   14435:                 }
                   14436:             }
                   14437:         }
1.618     raeburn  14438:     }
1.688     raeburn  14439:     if (defined($defmail)) {
                   14440:         if ($defmail ne '') {
                   14441:             push(@recipients,$defmail);
                   14442:         }
1.618     raeburn  14443:     }
                   14444:     if ($otheremails) {
1.619     raeburn  14445:         my @others;
                   14446:         if ($otheremails =~ /,/) {
                   14447:             @others = split(/,/,$otheremails);
1.618     raeburn  14448:         } else {
1.619     raeburn  14449:             push(@others,$otheremails);
                   14450:         }
                   14451:         foreach my $addr (@others) {
                   14452:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14453:                 push(@recipients,$addr);
                   14454:             }
1.618     raeburn  14455:         }
                   14456:     }
1.1075.2.128  raeburn  14457:     if ($mailing eq 'helpdeskmail') {
1.1075.2.122  raeburn  14458:         if ((!@recipients) && ($lastresort ne '')) {
                   14459:             push(@recipients,$lastresort);
                   14460:         }
                   14461:     } elsif ($lastresort ne '') {
                   14462:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14463:             push(@recipients,$lastresort);
                   14464:         }
                   14465:     }
                   14466:     my $recipientlist = join(',',@recipients);
                   14467:     if (wantarray) {
                   14468:         return ($recipientlist,$allbcc,$addtext);
                   14469:     } else {
                   14470:         return $recipientlist;
                   14471:     }
1.618     raeburn  14472: }
                   14473: 
1.127     matthew  14474: ############################################################
                   14475: ############################################################
1.154     albertel 14476: 
1.655     raeburn  14477: =pod
                   14478: 
                   14479: =head1 Course Catalog Routines
                   14480: 
                   14481: =over 4
                   14482: 
                   14483: =item * &gather_categories()
                   14484: 
                   14485: Converts category definitions - keys of categories hash stored in  
                   14486: coursecategories in configuration.db on the primary library server in a 
                   14487: domain - to an array.  Also generates javascript and idx hash used to 
                   14488: generate Domain Coordinator interface for editing Course Categories.
                   14489: 
                   14490: Inputs:
1.663     raeburn  14491: 
1.655     raeburn  14492: categories (reference to hash of category definitions).
1.663     raeburn  14493: 
1.655     raeburn  14494: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14495:       categories and subcategories).
1.663     raeburn  14496: 
1.655     raeburn  14497: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14498:       editing Course Categories).
1.663     raeburn  14499: 
1.655     raeburn  14500: jsarray (reference to array of categories used to create Javascript arrays for
                   14501:          Domain Coordinator interface for editing Course Categories).
                   14502: 
                   14503: Returns: nothing
                   14504: 
                   14505: Side effects: populates cats, idx and jsarray. 
                   14506: 
                   14507: =cut
                   14508: 
                   14509: sub gather_categories {
                   14510:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14511:     my %counters;
                   14512:     my $num = 0;
                   14513:     foreach my $item (keys(%{$categories})) {
                   14514:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14515:         if ($container eq '' && $depth == 0) {
                   14516:             $cats->[$depth][$categories->{$item}] = $cat;
                   14517:         } else {
                   14518:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14519:         }
                   14520:         my ($escitem,$tail) = split(/:/,$item,2);
                   14521:         if ($counters{$tail} eq '') {
                   14522:             $counters{$tail} = $num;
                   14523:             $num ++;
                   14524:         }
                   14525:         if (ref($idx) eq 'HASH') {
                   14526:             $idx->{$item} = $counters{$tail};
                   14527:         }
                   14528:         if (ref($jsarray) eq 'ARRAY') {
                   14529:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14530:         }
                   14531:     }
                   14532:     return;
                   14533: }
                   14534: 
                   14535: =pod
                   14536: 
                   14537: =item * &extract_categories()
                   14538: 
                   14539: Used to generate breadcrumb trails for course categories.
                   14540: 
                   14541: Inputs:
1.663     raeburn  14542: 
1.655     raeburn  14543: categories (reference to hash of category definitions).
1.663     raeburn  14544: 
1.655     raeburn  14545: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14546:       categories and subcategories).
1.663     raeburn  14547: 
1.655     raeburn  14548: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14549: 
1.655     raeburn  14550: allitems (reference to hash - key is category key 
                   14551:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14552: 
1.655     raeburn  14553: idx (reference to hash of counters used in Domain Coordinator interface for
                   14554:       editing Course Categories).
1.663     raeburn  14555: 
1.655     raeburn  14556: jsarray (reference to array of categories used to create Javascript arrays for
                   14557:          Domain Coordinator interface for editing Course Categories).
                   14558: 
1.665     raeburn  14559: subcats (reference to hash of arrays containing all subcategories within each 
                   14560:          category, -recursive)
                   14561: 
1.1075.2.132  raeburn  14562: maxd (reference to hash used to hold max depth for all top-level categories).
                   14563: 
1.655     raeburn  14564: Returns: nothing
                   14565: 
                   14566: Side effects: populates trails and allitems hash references.
                   14567: 
                   14568: =cut
                   14569: 
                   14570: sub extract_categories {
1.1075.2.132  raeburn  14571:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  14572:     if (ref($categories) eq 'HASH') {
                   14573:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14574:         if (ref($cats->[0]) eq 'ARRAY') {
                   14575:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14576:                 my $name = $cats->[0][$i];
                   14577:                 my $item = &escape($name).'::0';
                   14578:                 my $trailstr;
                   14579:                 if ($name eq 'instcode') {
                   14580:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14581:                 } elsif ($name eq 'communities') {
                   14582:                     $trailstr = &mt('Communities');
1.655     raeburn  14583:                 } else {
                   14584:                     $trailstr = $name;
                   14585:                 }
                   14586:                 if ($allitems->{$item} eq '') {
                   14587:                     push(@{$trails},$trailstr);
                   14588:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14589:                 }
                   14590:                 my @parents = ($name);
                   14591:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14592:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14593:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14594:                         if (ref($subcats) eq 'HASH') {
                   14595:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14596:                         }
1.1075.2.132  raeburn  14597:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  14598:                     }
                   14599:                 } else {
                   14600:                     if (ref($subcats) eq 'HASH') {
                   14601:                         $subcats->{$item} = [];
1.655     raeburn  14602:                     }
1.1075.2.132  raeburn  14603:                     if (ref($maxd) eq 'HASH') {
                   14604:                         $maxd->{$name} = 1;
                   14605:                     }
1.655     raeburn  14606:                 }
                   14607:             }
                   14608:         }
                   14609:     }
                   14610:     return;
                   14611: }
                   14612: 
                   14613: =pod
                   14614: 
1.1075.2.56  raeburn  14615: =item * &recurse_categories()
1.655     raeburn  14616: 
                   14617: Recursively used to generate breadcrumb trails for course categories.
                   14618: 
                   14619: Inputs:
1.663     raeburn  14620: 
1.655     raeburn  14621: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14622:       categories and subcategories).
1.663     raeburn  14623: 
1.655     raeburn  14624: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14625: 
                   14626: category (current course category, for which breadcrumb trail is being generated).
                   14627: 
                   14628: trails (reference to array of breadcrumb trails for each category).
                   14629: 
1.655     raeburn  14630: allitems (reference to hash - key is category key
                   14631:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14632: 
1.655     raeburn  14633: parents (array containing containers directories for current category, 
                   14634:          back to top level). 
                   14635: 
                   14636: Returns: nothing
                   14637: 
                   14638: Side effects: populates trails and allitems hash references
                   14639: 
                   14640: =cut
                   14641: 
                   14642: sub recurse_categories {
1.1075.2.132  raeburn  14643:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  14644:     my $shallower = $depth - 1;
                   14645:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14646:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14647:             my $name = $cats->[$depth]{$category}[$k];
                   14648:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14649:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14650:             if ($allitems->{$item} eq '') {
                   14651:                 push(@{$trails},$trailstr);
                   14652:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14653:             }
                   14654:             my $deeper = $depth+1;
                   14655:             push(@{$parents},$category);
1.665     raeburn  14656:             if (ref($subcats) eq 'HASH') {
                   14657:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14658:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14659:                     my $higher;
                   14660:                     if ($j > 0) {
                   14661:                         $higher = &escape($parents->[$j]).':'.
                   14662:                                   &escape($parents->[$j-1]).':'.$j;
                   14663:                     } else {
                   14664:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14665:                     }
                   14666:                     push(@{$subcats->{$higher}},$subcat);
                   14667:                 }
                   14668:             }
                   14669:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1075.2.132  raeburn  14670:                                 $subcats,$maxd);
1.655     raeburn  14671:             pop(@{$parents});
                   14672:         }
                   14673:     } else {
                   14674:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.132  raeburn  14675:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  14676:         if ($allitems->{$item} eq '') {
                   14677:             push(@{$trails},$trailstr);
                   14678:             $allitems->{$item} = scalar(@{$trails})-1;
                   14679:         }
1.1075.2.132  raeburn  14680:         if (ref($maxd) eq 'HASH') {
                   14681:             if ($depth > $maxd->{$parents->[0]}) {
                   14682:                 $maxd->{$parents->[0]} = $depth;
                   14683:             }
                   14684:         }
1.655     raeburn  14685:     }
                   14686:     return;
                   14687: }
                   14688: 
1.663     raeburn  14689: =pod
                   14690: 
1.1075.2.56  raeburn  14691: =item * &assign_categories_table()
1.663     raeburn  14692: 
                   14693: Create a datatable for display of hierarchical categories in a domain,
                   14694: with checkboxes to allow a course to be categorized. 
                   14695: 
                   14696: Inputs:
                   14697: 
                   14698: cathash - reference to hash of categories defined for the domain (from
                   14699:           configuration.db)
                   14700: 
                   14701: currcat - scalar with an & separated list of categories assigned to a course. 
                   14702: 
1.919     raeburn  14703: type    - scalar contains course type (Course or Community).
                   14704: 
1.1075.2.117  raeburn  14705: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14706:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14707: 
1.663     raeburn  14708: Returns: $output (markup to be displayed) 
                   14709: 
                   14710: =cut
                   14711: 
                   14712: sub assign_categories_table {
1.1075.2.117  raeburn  14713:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  14714:     my $output;
                   14715:     if (ref($cathash) eq 'HASH') {
1.1075.2.132  raeburn  14716:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   14717:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  14718:         $maxdepth = scalar(@cats);
                   14719:         if (@cats > 0) {
                   14720:             my $itemcount = 0;
                   14721:             if (ref($cats[0]) eq 'ARRAY') {
                   14722:                 my @currcategories;
                   14723:                 if ($currcat ne '') {
                   14724:                     @currcategories = split('&',$currcat);
                   14725:                 }
1.919     raeburn  14726:                 my $table;
1.663     raeburn  14727:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14728:                     my $parent = $cats[0][$i];
1.919     raeburn  14729:                     next if ($parent eq 'instcode');
                   14730:                     if ($type eq 'Community') {
                   14731:                         next unless ($parent eq 'communities');
                   14732:                     } else {
                   14733:                         next if ($parent eq 'communities');
                   14734:                     }
1.663     raeburn  14735:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14736:                     my $item = &escape($parent).'::0';
                   14737:                     my $checked = '';
                   14738:                     if (@currcategories > 0) {
                   14739:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14740:                             $checked = ' checked="checked"';
1.663     raeburn  14741:                         }
                   14742:                     }
1.919     raeburn  14743:                     my $parent_title = $parent;
                   14744:                     if ($parent eq 'communities') {
                   14745:                         $parent_title = &mt('Communities');
                   14746:                     }
                   14747:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14748:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14749:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  14750:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14751:                     my $depth = 1;
                   14752:                     push(@path,$parent);
1.1075.2.117  raeburn  14753:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  14754:                     pop(@path);
1.919     raeburn  14755:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14756:                     $itemcount ++;
                   14757:                 }
1.919     raeburn  14758:                 if ($itemcount) {
                   14759:                     $output = &Apache::loncommon::start_data_table().
                   14760:                               $table.
                   14761:                               &Apache::loncommon::end_data_table();
                   14762:                 }
1.663     raeburn  14763:             }
                   14764:         }
                   14765:     }
                   14766:     return $output;
                   14767: }
                   14768: 
                   14769: =pod
                   14770: 
1.1075.2.56  raeburn  14771: =item * &assign_category_rows()
1.663     raeburn  14772: 
                   14773: Create a datatable row for display of nested categories in a domain,
                   14774: with checkboxes to allow a course to be categorized,called recursively.
                   14775: 
                   14776: Inputs:
                   14777: 
                   14778: itemcount - track row number for alternating colors
                   14779: 
                   14780: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14781:       categories and subcategories.
                   14782: 
                   14783: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14784: 
                   14785: parent - parent of current category item
                   14786: 
                   14787: path - Array containing all categories back up through the hierarchy from the
                   14788:        current category to the top level.
                   14789: 
                   14790: currcategories - reference to array of current categories assigned to the course
                   14791: 
1.1075.2.117  raeburn  14792: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14793:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14794: 
1.663     raeburn  14795: Returns: $output (markup to be displayed).
                   14796: 
                   14797: =cut
                   14798: 
                   14799: sub assign_category_rows {
1.1075.2.117  raeburn  14800:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  14801:     my ($text,$name,$item,$chgstr);
                   14802:     if (ref($cats) eq 'ARRAY') {
                   14803:         my $maxdepth = scalar(@{$cats});
                   14804:         if (ref($cats->[$depth]) eq 'HASH') {
                   14805:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14806:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14807:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  14808:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14809:                 for (my $j=0; $j<$numchildren; $j++) {
                   14810:                     $name = $cats->[$depth]{$parent}[$j];
                   14811:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14812:                     my $deeper = $depth+1;
                   14813:                     my $checked = '';
                   14814:                     if (ref($currcategories) eq 'ARRAY') {
                   14815:                         if (@{$currcategories} > 0) {
                   14816:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14817:                                 $checked = ' checked="checked"';
1.663     raeburn  14818:                             }
                   14819:                         }
                   14820:                     }
1.664     raeburn  14821:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14822:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14823:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  14824:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14825:                              '</td><td>';
1.663     raeburn  14826:                     if (ref($path) eq 'ARRAY') {
                   14827:                         push(@{$path},$name);
1.1075.2.117  raeburn  14828:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  14829:                         pop(@{$path});
                   14830:                     }
                   14831:                     $text .= '</td></tr>';
                   14832:                 }
                   14833:                 $text .= '</table></td>';
                   14834:             }
                   14835:         }
                   14836:     }
                   14837:     return $text;
                   14838: }
                   14839: 
1.1075.2.69  raeburn  14840: =pod
                   14841: 
                   14842: =back
                   14843: 
                   14844: =cut
                   14845: 
1.655     raeburn  14846: ############################################################
                   14847: ############################################################
                   14848: 
                   14849: 
1.443     albertel 14850: sub commit_customrole {
1.664     raeburn  14851:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14852:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14853:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14854:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14855:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14856:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14857:                  '</b><br />';
                   14858:     return $output;
                   14859: }
                   14860: 
                   14861: sub commit_standardrole {
1.1075.2.31  raeburn  14862:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14863:     my ($output,$logmsg,$linefeed);
                   14864:     if ($context eq 'auto') {
                   14865:         $linefeed = "\n";
                   14866:     } else {
                   14867:         $linefeed = "<br />\n";
                   14868:     }  
1.443     albertel 14869:     if ($three eq 'st') {
1.541     raeburn  14870:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  14871:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14872:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14873:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14874:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14875:         } else {
1.541     raeburn  14876:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14877:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14878:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14879:             if ($context eq 'auto') {
                   14880:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14881:             } else {
                   14882:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14883:                &mt('Add to classlist').': <b>ok</b>';
                   14884:             }
                   14885:             $output .= $linefeed;
1.443     albertel 14886:         }
                   14887:     } else {
                   14888:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14889:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14890:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14891:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14892:         if ($context eq 'auto') {
                   14893:             $output .= $result.$linefeed;
                   14894:         } else {
                   14895:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14896:         }
1.443     albertel 14897:     }
                   14898:     return $output;
                   14899: }
                   14900: 
                   14901: sub commit_studentrole {
1.1075.2.31  raeburn  14902:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14903:         $credits) = @_;
1.626     raeburn  14904:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14905:     if ($context eq 'auto') {
                   14906:         $linefeed = "\n";
                   14907:     } else {
                   14908:         $linefeed = '<br />'."\n";
                   14909:     }
1.443     albertel 14910:     if (defined($one) && defined($two)) {
                   14911:         my $cid=$one.'_'.$two;
                   14912:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14913:         my $secchange = 0;
                   14914:         my $expire_role_result;
                   14915:         my $modify_section_result;
1.628     raeburn  14916:         if ($oldsec ne '-1') { 
                   14917:             if ($oldsec ne $sec) {
1.443     albertel 14918:                 $secchange = 1;
1.628     raeburn  14919:                 my $now = time;
1.443     albertel 14920:                 my $uurl='/'.$cid;
                   14921:                 $uurl=~s/\_/\//g;
                   14922:                 if ($oldsec) {
                   14923:                     $uurl.='/'.$oldsec;
                   14924:                 }
1.626     raeburn  14925:                 $oldsecurl = $uurl;
1.628     raeburn  14926:                 $expire_role_result = 
1.652     raeburn  14927:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14928:                 if ($env{'request.course.sec'} ne '') { 
                   14929:                     if ($expire_role_result eq 'refused') {
                   14930:                         my @roles = ('st');
                   14931:                         my @statuses = ('previous');
                   14932:                         my @roledoms = ($one);
                   14933:                         my $withsec = 1;
                   14934:                         my %roleshash = 
                   14935:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14936:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14937:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14938:                             my ($oldstart,$oldend) = 
                   14939:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14940:                             if ($oldend > 0 && $oldend <= $now) {
                   14941:                                 $expire_role_result = 'ok';
                   14942:                             }
                   14943:                         }
                   14944:                     }
                   14945:                 }
1.443     albertel 14946:                 $result = $expire_role_result;
                   14947:             }
                   14948:         }
                   14949:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  14950:             $modify_section_result = 
                   14951:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14952:                                                            undef,undef,undef,$sec,
                   14953:                                                            $end,$start,'','',$cid,
                   14954:                                                            '',$context,$credits);
1.443     albertel 14955:             if ($modify_section_result =~ /^ok/) {
                   14956:                 if ($secchange == 1) {
1.628     raeburn  14957:                     if ($sec eq '') {
                   14958:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   14959:                     } else {
                   14960:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14961:                     }
1.443     albertel 14962:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14963:                     if ($sec eq '') {
                   14964:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14965:                     } else {
                   14966:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14967:                     }
1.443     albertel 14968:                 } else {
1.628     raeburn  14969:                     if ($sec eq '') {
                   14970:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14971:                     } else {
                   14972:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14973:                     }
1.443     albertel 14974:                 }
                   14975:             } else {
1.628     raeburn  14976:                 if ($secchange) {       
                   14977:                     $$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;
                   14978:                 } else {
                   14979:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14980:                 }
1.443     albertel 14981:             }
                   14982:             $result = $modify_section_result;
                   14983:         } elsif ($secchange == 1) {
1.628     raeburn  14984:             if ($oldsec eq '') {
1.1075.2.20  raeburn  14985:                 $$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  14986:             } else {
                   14987:                 $$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;
                   14988:             }
1.626     raeburn  14989:             if ($expire_role_result eq 'refused') {
                   14990:                 my $newsecurl = '/'.$cid;
                   14991:                 $newsecurl =~ s/\_/\//g;
                   14992:                 if ($sec ne '') {
                   14993:                     $newsecurl.='/'.$sec;
                   14994:                 }
                   14995:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14996:                     if ($sec eq '') {
                   14997:                         $$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;
                   14998:                     } else {
                   14999:                         $$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;
                   15000:                     }
                   15001:                 }
                   15002:             }
1.443     albertel 15003:         }
                   15004:     } else {
1.626     raeburn  15005:         $$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 15006:         $result = "error: incomplete course id\n";
                   15007:     }
                   15008:     return $result;
                   15009: }
                   15010: 
1.1075.2.25  raeburn  15011: sub show_role_extent {
                   15012:     my ($scope,$context,$role) = @_;
                   15013:     $scope =~ s{^/}{};
                   15014:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15015:     push(@courseroles,'co');
                   15016:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15017:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15018:         $scope =~ s{/}{_};
                   15019:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15020:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15021:         my ($audom,$auname) = split(/\//,$scope);
                   15022:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15023:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15024:     } else {
                   15025:         $scope =~ s{/$}{};
                   15026:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15027:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15028:     }
                   15029: }
                   15030: 
1.443     albertel 15031: ############################################################
                   15032: ############################################################
                   15033: 
1.566     albertel 15034: sub check_clone {
1.578     raeburn  15035:     my ($args,$linefeed) = @_;
1.566     albertel 15036:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15037:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15038:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   15039:     my $clonemsg;
                   15040:     my $can_clone = 0;
1.944     raeburn  15041:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15042:     if ($lctype ne 'community') {
                   15043:         $lctype = 'course';
                   15044:     }
1.566     albertel 15045:     if ($clonehome eq 'no_host') {
1.944     raeburn  15046:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15047:             $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'});
                   15048:         } else {
                   15049:             $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'});
                   15050:         }     
1.566     albertel 15051:     } else {
                   15052: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  15053:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15054:             if ($clonedesc{'type'} ne 'Community') {
                   15055:                  $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'});
                   15056:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15057:             }
                   15058:         }
1.1075.2.119  raeburn  15059: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15060:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15061: 	    $can_clone = 1;
                   15062: 	} else {
1.1075.2.95  raeburn  15063: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15064: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  15065:             if ($clonehash{'cloners'} eq '') {
                   15066:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15067:                 if ($domdefs{'canclone'}) {
                   15068:                     unless ($domdefs{'canclone'} eq 'none') {
                   15069:                         if ($domdefs{'canclone'} eq 'domain') {
                   15070:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15071:                                 $can_clone = 1;
                   15072:                             }
                   15073:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15074:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15075:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15076:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15077:                                 $can_clone = 1;
                   15078:                             }
                   15079:                         }
                   15080:                     }
1.908     raeburn  15081:                 }
1.1075.2.95  raeburn  15082:             } else {
                   15083: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15084:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15085:                     $can_clone = 1;
1.1075.2.95  raeburn  15086:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15087:                     $can_clone = 1;
1.1075.2.96  raeburn  15088:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15089:                     $can_clone = 1;
1.1075.2.95  raeburn  15090:                 }
                   15091:                 unless ($can_clone) {
1.1075.2.96  raeburn  15092:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15093:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  15094:                         my (%gotdomdefaults,%gotcodedefaults);
                   15095:                         foreach my $cloner (@cloners) {
                   15096:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15097:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15098:                                 my (%codedefaults,@code_order);
                   15099:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15100:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15101:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15102:                                     }
                   15103:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15104:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15105:                                     }
                   15106:                                 } else {
                   15107:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15108:                                                                             \%codedefaults,
                   15109:                                                                             \@code_order);
                   15110:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15111:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15112:                                 }
                   15113:                                 if (@code_order > 0) {
                   15114:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15115:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15116:                                                                                 $args->{'crscode'})) {
                   15117:                                         $can_clone = 1;
                   15118:                                         last;
                   15119:                                     }
                   15120:                                 }
                   15121:                             }
                   15122:                         }
                   15123:                     }
1.1075.2.96  raeburn  15124:                 }
                   15125:             }
                   15126:             unless ($can_clone) {
                   15127:                 my $ccrole = 'cc';
                   15128:                 if ($args->{'crstype'} eq 'Community') {
                   15129:                     $ccrole = 'co';
                   15130:                 }
                   15131:                 my %roleshash =
                   15132:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15133:                                                   $args->{'ccdomain'},
                   15134:                                                   'userroles',['active'],[$ccrole],
                   15135:                                                   [$args->{'clonedomain'}]);
                   15136:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15137:                     $can_clone = 1;
                   15138:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15139:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15140:                     $can_clone = 1;
1.1075.2.95  raeburn  15141:                 }
                   15142:             }
                   15143:             unless ($can_clone) {
                   15144:                 if ($args->{'crstype'} eq 'Community') {
                   15145:                     $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'});
                   15146:                 } else {
                   15147:                     $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  15148: 	        }
1.566     albertel 15149: 	    }
1.578     raeburn  15150:         }
1.566     albertel 15151:     }
                   15152:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15153: }
                   15154: 
1.444     albertel 15155: sub construct_course {
1.1075.2.119  raeburn  15156:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   15157:         $cnum,$category,$coderef) = @_;
1.444     albertel 15158:     my $outcome;
1.541     raeburn  15159:     my $linefeed =  '<br />'."\n";
                   15160:     if ($context eq 'auto') {
                   15161:         $linefeed = "\n";
                   15162:     }
1.566     albertel 15163: 
                   15164: #
                   15165: # Are we cloning?
                   15166: #
                   15167:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15168:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  15169: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 15170: 	if ($context ne 'auto') {
1.578     raeburn  15171:             if ($clonemsg ne '') {
                   15172: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   15173:             }
1.566     albertel 15174: 	}
                   15175: 	$outcome .= $clonemsg.$linefeed;
                   15176: 
                   15177:         if (!$can_clone) {
                   15178: 	    return (0,$outcome);
                   15179: 	}
                   15180:     }
                   15181: 
1.444     albertel 15182: #
                   15183: # Open course
                   15184: #
                   15185:     my $crstype = lc($args->{'crstype'});
                   15186:     my %cenv=();
                   15187:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15188:                                              $args->{'cdescr'},
                   15189:                                              $args->{'curl'},
                   15190:                                              $args->{'course_home'},
                   15191:                                              $args->{'nonstandard'},
                   15192:                                              $args->{'crscode'},
                   15193:                                              $args->{'ccuname'}.':'.
                   15194:                                              $args->{'ccdomain'},
1.882     raeburn  15195:                                              $args->{'crstype'},
1.885     raeburn  15196:                                              $cnum,$context,$category);
1.444     albertel 15197: 
                   15198:     # Note: The testing routines depend on this being output; see 
                   15199:     # Utils::Course. This needs to at least be output as a comment
                   15200:     # if anyone ever decides to not show this, and Utils::Course::new
                   15201:     # will need to be suitably modified.
1.541     raeburn  15202:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  15203:     if ($$courseid =~ /^error:/) {
                   15204:         return (0,$outcome);
                   15205:     }
                   15206: 
1.444     albertel 15207: #
                   15208: # Check if created correctly
                   15209: #
1.479     albertel 15210:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15211:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15212:     if ($crsuhome eq 'no_host') {
                   15213:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   15214:         return (0,$outcome);
                   15215:     }
1.541     raeburn  15216:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15217: 
1.444     albertel 15218: #
1.566     albertel 15219: # Do the cloning
                   15220: #   
                   15221:     if ($can_clone && $cloneid) {
                   15222: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   15223: 	if ($context ne 'auto') {
                   15224: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   15225: 	}
                   15226: 	$outcome .= $clonemsg.$linefeed;
                   15227: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15228: # Copy all files
1.637     www      15229: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 15230: # Restore URL
1.566     albertel 15231: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15232: # Restore title
1.566     albertel 15233: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15234: # Restore creation date, creator and creation context.
                   15235:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15236:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15237:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15238: # Mark as cloned
1.566     albertel 15239: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15240: # Need to clone grading mode
                   15241:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15242:         $cenv{'grading'}=$newenv{'grading'};
                   15243: # Do not clone these environment entries
                   15244:         &Apache::lonnet::del('environment',
                   15245:                   ['default_enrollment_start_date',
                   15246:                    'default_enrollment_end_date',
                   15247:                    'question.email',
                   15248:                    'policy.email',
                   15249:                    'comment.email',
                   15250:                    'pch.users.denied',
1.725     raeburn  15251:                    'plc.users.denied',
                   15252:                    'hidefromcat',
1.1075.2.36  raeburn  15253:                    'checkforpriv',
1.1075.2.59  raeburn  15254:                    'categories',
                   15255:                    'internal.uniquecode'],
1.638     www      15256:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  15257:         if ($args->{'textbook'}) {
                   15258:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15259:         }
1.444     albertel 15260:     }
1.566     albertel 15261: 
1.444     albertel 15262: #
                   15263: # Set environment (will override cloned, if existing)
                   15264: #
                   15265:     my @sections = ();
                   15266:     my @xlists = ();
                   15267:     if ($args->{'crstype'}) {
                   15268:         $cenv{'type'}=$args->{'crstype'};
                   15269:     }
                   15270:     if ($args->{'crsid'}) {
                   15271:         $cenv{'courseid'}=$args->{'crsid'};
                   15272:     }
                   15273:     if ($args->{'crscode'}) {
                   15274:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15275:     }
                   15276:     if ($args->{'crsquota'} ne '') {
                   15277:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15278:     } else {
                   15279:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15280:     }
                   15281:     if ($args->{'ccuname'}) {
                   15282:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15283:                                         ':'.$args->{'ccdomain'};
                   15284:     } else {
                   15285:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15286:     }
1.1075.2.31  raeburn  15287:     if ($args->{'defaultcredits'}) {
                   15288:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15289:     }
1.444     albertel 15290:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15291:     if ($args->{'crssections'}) {
                   15292:         $cenv{'internal.sectionnums'} = '';
                   15293:         if ($args->{'crssections'} =~ m/,/) {
                   15294:             @sections = split/,/,$args->{'crssections'};
                   15295:         } else {
                   15296:             $sections[0] = $args->{'crssections'};
                   15297:         }
                   15298:         if (@sections > 0) {
                   15299:             foreach my $item (@sections) {
                   15300:                 my ($sec,$gp) = split/:/,$item;
                   15301:                 my $class = $args->{'crscode'}.$sec;
                   15302:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15303:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15304:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15305:                     push(@badclasses,$class);
1.444     albertel 15306:                 }
                   15307:             }
                   15308:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15309:         }
                   15310:     }
                   15311: # do not hide course coordinator from staff listing, 
                   15312: # even if privileged
                   15313:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  15314: # add course coordinator's domain to domains to check for privileged users
                   15315: # if different to course domain
                   15316:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15317:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15318:     }
1.444     albertel 15319: # add crosslistings
                   15320:     if ($args->{'crsxlist'}) {
                   15321:         $cenv{'internal.crosslistings'}='';
                   15322:         if ($args->{'crsxlist'} =~ m/,/) {
                   15323:             @xlists = split/,/,$args->{'crsxlist'};
                   15324:         } else {
                   15325:             $xlists[0] = $args->{'crsxlist'};
                   15326:         }
                   15327:         if (@xlists > 0) {
                   15328:             foreach my $item (@xlists) {
                   15329:                 my ($xl,$gp) = split/:/,$item;
                   15330:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15331:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15332:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15333:                     push(@badclasses,$xl);
1.444     albertel 15334:                 }
                   15335:             }
                   15336:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15337:         }
                   15338:     }
                   15339:     if ($args->{'autoadds'}) {
                   15340:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15341:     }
                   15342:     if ($args->{'autodrops'}) {
                   15343:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15344:     }
                   15345: # check for notification of enrollment changes
                   15346:     my @notified = ();
                   15347:     if ($args->{'notify_owner'}) {
                   15348:         if ($args->{'ccuname'} ne '') {
                   15349:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15350:         }
                   15351:     }
                   15352:     if ($args->{'notify_dc'}) {
                   15353:         if ($uname ne '') { 
1.630     raeburn  15354:             push(@notified,$uname.':'.$udom);
1.444     albertel 15355:         }
                   15356:     }
                   15357:     if (@notified > 0) {
                   15358:         my $notifylist;
                   15359:         if (@notified > 1) {
                   15360:             $notifylist = join(',',@notified);
                   15361:         } else {
                   15362:             $notifylist = $notified[0];
                   15363:         }
                   15364:         $cenv{'internal.notifylist'} = $notifylist;
                   15365:     }
                   15366:     if (@badclasses > 0) {
                   15367:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  15368:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15369:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15370:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15371:         );
1.1075.2.119  raeburn  15372:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15373:                            &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  15374:         if ($context eq 'auto') {
                   15375:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  15376:         } else {
1.566     albertel 15377:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  15378:         }
                   15379:         foreach my $item (@badclasses) {
1.541     raeburn  15380:             if ($context eq 'auto') {
1.1075.2.119  raeburn  15381:                 $outcome .= " - $item\n";
1.541     raeburn  15382:             } else {
1.1075.2.119  raeburn  15383:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15384:             }
1.1075.2.119  raeburn  15385:         }
                   15386:         if ($context eq 'auto') {
                   15387:             $outcome .= $linefeed;
                   15388:         } else {
                   15389:             $outcome .= "</ul><br /><br /></div>\n";
                   15390:         }
1.444     albertel 15391:     }
                   15392:     if ($args->{'no_end_date'}) {
                   15393:         $args->{'endaccess'} = 0;
                   15394:     }
                   15395:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15396:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15397:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15398:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15399:     if ($args->{'showphotos'}) {
                   15400:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15401:     }
                   15402:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15403:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15404:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15405:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15406:             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'); 
                   15407:             if ($context eq 'auto') {
                   15408:                 $outcome .= $krb_msg;
                   15409:             } else {
1.566     albertel 15410:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15411:             }
                   15412:             $outcome .= $linefeed;
1.444     albertel 15413:         }
                   15414:     }
                   15415:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15416:        if ($args->{'setpolicy'}) {
                   15417:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15418:        }
                   15419:        if ($args->{'setcontent'}) {
                   15420:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15421:        }
1.1075.2.110  raeburn  15422:        if ($args->{'setcomment'}) {
                   15423:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15424:        }
1.444     albertel 15425:     }
                   15426:     if ($args->{'reshome'}) {
                   15427: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15428: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15429:     }
                   15430: #
                   15431: # course has keyed access
                   15432: #
                   15433:     if ($args->{'setkeys'}) {
                   15434:        $cenv{'keyaccess'}='yes';
                   15435:     }
                   15436: # if specified, key authority is not course, but user
                   15437: # only active if keyaccess is yes
                   15438:     if ($args->{'keyauth'}) {
1.487     albertel 15439: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15440: 	$user = &LONCAPA::clean_username($user);
                   15441: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15442: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15443: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15444: 	}
                   15445:     }
                   15446: 
1.1075.2.59  raeburn  15447: #
                   15448: #  generate and store uniquecode (available to course requester), if course should have one.
                   15449: #
                   15450:     if ($args->{'uniquecode'}) {
                   15451:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15452:         if ($code) {
                   15453:             $cenv{'internal.uniquecode'} = $code;
                   15454:             my %crsinfo =
                   15455:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15456:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15457:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15458:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15459:             }
                   15460:             if (ref($coderef)) {
                   15461:                 $$coderef = $code;
                   15462:             }
                   15463:         }
                   15464:     }
                   15465: 
1.444     albertel 15466:     if ($args->{'disresdis'}) {
                   15467:         $cenv{'pch.roles.denied'}='st';
                   15468:     }
                   15469:     if ($args->{'disablechat'}) {
                   15470:         $cenv{'plc.roles.denied'}='st';
                   15471:     }
                   15472: 
                   15473:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15474:     # course
                   15475:     $cenv{'course.helper.not.run'} = 1;
                   15476:     #
                   15477:     # Use new Randomseed
                   15478:     #
                   15479:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15480:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15481:     #
                   15482:     # The encryption code and receipt prefix for this course
                   15483:     #
                   15484:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15485:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15486:     #
                   15487:     # By default, use standard grading
                   15488:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15489: 
1.541     raeburn  15490:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15491:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15492: #
                   15493: # Open all assignments
                   15494: #
                   15495:     if ($args->{'openall'}) {
                   15496:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   15497:        my %storecontent = ($storeunder         => time,
                   15498:                            $storeunder.'.type' => 'date_start');
                   15499:        
                   15500:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  15501:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15502:    }
                   15503: #
                   15504: # Set first page
                   15505: #
                   15506:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15507: 	    || ($cloneid)) {
1.445     albertel 15508: 	use LONCAPA::map;
1.444     albertel 15509: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15510: 
                   15511: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15512:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15513: 
1.444     albertel 15514:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15515:         my $title; my $url;
                   15516:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15517: 	    $title=&mt('Syllabus');
1.444     albertel 15518:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15519:         } else {
1.963     raeburn  15520:             $title=&mt('Table of Contents');
1.444     albertel 15521:             $url='/adm/navmaps';
                   15522:         }
1.445     albertel 15523: 
                   15524:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15525: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15526: 
                   15527: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15528:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15529:     }
1.566     albertel 15530: 
                   15531:     return (1,$outcome);
1.444     albertel 15532: }
                   15533: 
1.1075.2.59  raeburn  15534: sub make_unique_code {
                   15535:     my ($cdom,$cnum) = @_;
                   15536:     # get lock on uniquecodes db
                   15537:     my $lockhash = {
                   15538:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15539:                                                   ':'.$env{'user.domain'},
                   15540:                    };
                   15541:     my $tries = 0;
                   15542:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15543:     my ($code,$error);
                   15544: 
                   15545:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15546:         $tries ++;
                   15547:         sleep 1;
                   15548:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15549:     }
                   15550:     if ($gotlock eq 'ok') {
                   15551:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15552:         my $gotcode;
                   15553:         my $attempts = 0;
                   15554:         while ((!$gotcode) && ($attempts < 100)) {
                   15555:             $code = &generate_code();
                   15556:             if (!exists($currcodes{$code})) {
                   15557:                 $gotcode = 1;
                   15558:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15559:                     $error = 'nostore';
                   15560:                 }
                   15561:             }
                   15562:             $attempts ++;
                   15563:         }
                   15564:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15565:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15566:     } else {
                   15567:         $error = 'nolock';
                   15568:     }
                   15569:     return ($code,$error);
                   15570: }
                   15571: 
                   15572: sub generate_code {
                   15573:     my $code;
                   15574:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15575:     for (my $i=0; $i<6; $i++) {
                   15576:         my $lettnum = int (rand 2);
                   15577:         my $item = '';
                   15578:         if ($lettnum) {
                   15579:             $item = $letts[int( rand(18) )];
                   15580:         } else {
                   15581:             $item = 1+int( rand(8) );
                   15582:         }
                   15583:         $code .= $item;
                   15584:     }
                   15585:     return $code;
                   15586: }
                   15587: 
1.444     albertel 15588: ############################################################
                   15589: ############################################################
                   15590: 
1.953     droeschl 15591: #SD
                   15592: # only Community and Course, or anything else?
1.378     raeburn  15593: sub course_type {
                   15594:     my ($cid) = @_;
                   15595:     if (!defined($cid)) {
                   15596:         $cid = $env{'request.course.id'};
                   15597:     }
1.404     albertel 15598:     if (defined($env{'course.'.$cid.'.type'})) {
                   15599:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15600:     } else {
                   15601:         return 'Course';
1.377     raeburn  15602:     }
                   15603: }
1.156     albertel 15604: 
1.406     raeburn  15605: sub group_term {
                   15606:     my $crstype = &course_type();
                   15607:     my %names = (
                   15608:                   'Course' => 'group',
1.865     raeburn  15609:                   'Community' => 'group',
1.406     raeburn  15610:                 );
                   15611:     return $names{$crstype};
                   15612: }
                   15613: 
1.902     raeburn  15614: sub course_types {
1.1075.2.59  raeburn  15615:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  15616:     my %typename = (
                   15617:                          official   => 'Official course',
                   15618:                          unofficial => 'Unofficial course',
                   15619:                          community  => 'Community',
1.1075.2.59  raeburn  15620:                          textbook   => 'Textbook course',
1.902     raeburn  15621:                    );
                   15622:     return (\@types,\%typename);
                   15623: }
                   15624: 
1.156     albertel 15625: sub icon {
                   15626:     my ($file)=@_;
1.505     albertel 15627:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15628:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15629:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15630:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15631: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15632: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15633: 	            $curfext.".gif") {
                   15634: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15635: 		$curfext.".gif";
                   15636: 	}
                   15637:     }
1.249     albertel 15638:     return &lonhttpdurl($iconname);
1.154     albertel 15639: } 
1.84      albertel 15640: 
1.575     albertel 15641: sub lonhttpdurl {
1.692     www      15642: #
                   15643: # Had been used for "small fry" static images on separate port 8080.
                   15644: # Modify here if lightweight http functionality desired again.
                   15645: # Currently eliminated due to increasing firewall issues.
                   15646: #
1.575     albertel 15647:     my ($url)=@_;
1.692     www      15648:     return $url;
1.215     albertel 15649: }
                   15650: 
1.213     albertel 15651: sub connection_aborted {
                   15652:     my ($r)=@_;
                   15653:     $r->print(" ");$r->rflush();
                   15654:     my $c = $r->connection;
                   15655:     return $c->aborted();
                   15656: }
                   15657: 
1.221     foxr     15658: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15659: #    strings as 'strings'.
                   15660: sub escape_single {
1.221     foxr     15661:     my ($input) = @_;
1.223     albertel 15662:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15663:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15664:     return $input;
                   15665: }
1.223     albertel 15666: 
1.222     foxr     15667: #  Same as escape_single, but escape's "'s  This 
                   15668: #  can be used for  "strings"
                   15669: sub escape_double {
                   15670:     my ($input) = @_;
                   15671:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15672:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15673:     return $input;
                   15674: }
1.223     albertel 15675:  
1.222     foxr     15676: #   Escapes the last element of a full URL.
                   15677: sub escape_url {
                   15678:     my ($url)   = @_;
1.238     raeburn  15679:     my @urlslices = split(/\//, $url,-1);
1.369     www      15680:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  15681:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15682: }
1.462     albertel 15683: 
1.820     raeburn  15684: sub compare_arrays {
                   15685:     my ($arrayref1,$arrayref2) = @_;
                   15686:     my (@difference,%count);
                   15687:     @difference = ();
                   15688:     %count = ();
                   15689:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15690:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15691:         foreach my $element (keys(%count)) {
                   15692:             if ($count{$element} == 1) {
                   15693:                 push(@difference,$element);
                   15694:             }
                   15695:         }
                   15696:     }
                   15697:     return @difference;
                   15698: }
                   15699: 
1.817     bisitz   15700: # -------------------------------------------------------- Initialize user login
1.462     albertel 15701: sub init_user_environment {
1.463     albertel 15702:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15703:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15704: 
                   15705:     my $public=($username eq 'public' && $domain eq 'public');
                   15706: 
                   15707: # See if old ID present, if so, remove
                   15708: 
1.1062    raeburn  15709:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15710:     my $now=time;
                   15711: 
                   15712:     if ($public) {
                   15713: 	my $max_public=100;
                   15714: 	my $oldest;
                   15715: 	my $oldest_time=0;
                   15716: 	for(my $next=1;$next<=$max_public;$next++) {
                   15717: 	    if (-e $lonids."/publicuser_$next.id") {
                   15718: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15719: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15720: 		    $oldest_time=$mtime;
                   15721: 		    $oldest=$next;
                   15722: 		}
                   15723: 	    } else {
                   15724: 		$cookie="publicuser_$next";
                   15725: 		last;
                   15726: 	    }
                   15727: 	}
                   15728: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15729:     } else {
1.463     albertel 15730: 	# if this isn't a robot, kill any existing non-robot sessions
                   15731: 	if (!$args->{'robot'}) {
                   15732: 	    opendir(DIR,$lonids);
                   15733: 	    while ($filename=readdir(DIR)) {
                   15734: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1075.2.136  raeburn  15735:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   15736:                             &GDBM_READER(),0640)) {
                   15737:                         my $linkedfile;
                   15738:                         if (exists($oldenv{'user.linkedenv'})) {
                   15739:                             $linkedfile = $oldenv{'user.linkedenv'};
                   15740:                         }
                   15741:                         untie(%oldenv);
                   15742:                         if (unlink("$lonids/$filename")) {
                   15743:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   15744:                                 if (-l "$lonids/$linkedfile.id") {
                   15745:                                     unlink("$lonids/$linkedfile.id");
                   15746:                                 }
                   15747:                             }
                   15748:                         }
                   15749:                     } else {
                   15750:                         unlink($lonids.'/'.$filename);
                   15751:                     }
1.463     albertel 15752: 		}
1.462     albertel 15753: 	    }
1.463     albertel 15754: 	    closedir(DIR);
1.1075.2.84  raeburn  15755: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15756:             my $namespace = 'nohist_courseeditor';
                   15757:             my $lockingkey = 'paste'."\0".'locked_num';
                   15758:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15759:                                                 $domain,$username);
                   15760:             if (exists($lockhash{$lockingkey})) {
                   15761:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15762:                 unless ($delresult eq 'ok') {
                   15763:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15764:                 }
                   15765:             }
1.462     albertel 15766: 	}
                   15767: # Give them a new cookie
1.463     albertel 15768: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15769: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15770: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15771:     
                   15772: # Initialize roles
                   15773: 
1.1062    raeburn  15774: 	($userroles,$firstaccenv,$timerintenv) = 
                   15775:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15776:     }
                   15777: # ------------------------------------ Check browser type and MathML capability
                   15778: 
1.1075.2.77  raeburn  15779:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15780:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15781: 
                   15782: # ------------------------------------------------------------- Get environment
                   15783: 
                   15784:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15785:     my ($tmp) = keys(%userenv);
                   15786:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15787:     } else {
                   15788: 	undef(%userenv);
                   15789:     }
                   15790:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15791: 	$form->{'interface'}=$userenv{'interface'};
                   15792:     }
                   15793:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15794: 
                   15795: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15796:     foreach my $option ('interface','localpath','localres') {
                   15797:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15798:     }
                   15799: # --------------------------------------------------------- Write first profile
                   15800: 
                   15801:     {
                   15802: 	my %initial_env = 
                   15803: 	    ("user.name"          => $username,
                   15804: 	     "user.domain"        => $domain,
                   15805: 	     "user.home"          => $authhost,
                   15806: 	     "browser.type"       => $clientbrowser,
                   15807: 	     "browser.version"    => $clientversion,
                   15808: 	     "browser.mathml"     => $clientmathml,
                   15809: 	     "browser.unicode"    => $clientunicode,
                   15810: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  15811:              "browser.mobile"     => $clientmobile,
                   15812:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  15813:              "browser.osversion"  => $clientosversion,
1.462     albertel 15814: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15815: 	     "request.course.fn"  => '',
                   15816: 	     "request.course.uri" => '',
                   15817: 	     "request.course.sec" => '',
                   15818: 	     "request.role"       => 'cm',
                   15819: 	     "request.role.adv"   => $env{'user.adv'},
                   15820: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15821: 
                   15822:         if ($form->{'localpath'}) {
                   15823: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15824: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15825:         }
                   15826: 	
                   15827: 	if ($form->{'interface'}) {
                   15828: 	    $form->{'interface'}=~s/\W//gs;
                   15829: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15830: 	    $env{'browser.interface'}=$form->{'interface'};
                   15831: 	}
                   15832: 
1.1075.2.54  raeburn  15833:         if ($form->{'iptoken'}) {
                   15834:             my $lonhost = $r->dir_config('lonHostID');
                   15835:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15836:             $env{'user.noloadbalance'} = $lonhost;
                   15837:         }
                   15838: 
1.1075.2.120  raeburn  15839:         if ($form->{'noloadbalance'}) {
                   15840:             my @hosts = &Apache::lonnet::current_machine_ids();
                   15841:             my $hosthere = $form->{'noloadbalance'};
                   15842:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   15843:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   15844:                 $env{'user.noloadbalance'} = $hosthere;
                   15845:             }
                   15846:         }
                   15847: 
1.1016    raeburn  15848:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  15849:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   15850:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  15851: 
1.1075.2.125  raeburn  15852:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   15853:                 $userenv{'availabletools.'.$tool} = 
                   15854:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15855:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   15856:             }
1.724     raeburn  15857: 
1.1075.2.125  raeburn  15858:             foreach my $crstype ('official','unofficial','community','textbook') {
                   15859:                 $userenv{'canrequest.'.$crstype} =
                   15860:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   15861:                                                       'reload','requestcourses',
                   15862:                                                       \%userenv,\%domdef,\%is_adv);
                   15863:             }
1.765     raeburn  15864: 
1.1075.2.125  raeburn  15865:             $userenv{'canrequest.author'} =
                   15866:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15867:                                                   'reload','requestauthor',
                   15868:                                                   \%userenv,\%domdef,\%is_adv);
                   15869:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15870:                                                  $domain,$username);
                   15871:             my $reqstatus = $reqauthor{'author_status'};
                   15872:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   15873:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   15874:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15875:                                                       $reqauthor{'author'}{'timestamp'};
                   15876:                 }
1.1075.2.14  raeburn  15877:             }
                   15878:         }
                   15879: 
1.462     albertel 15880: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15881: 
1.462     albertel 15882: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15883: 		 &GDBM_WRCREAT(),0640)) {
                   15884: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15885: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15886: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15887:             if (ref($firstaccenv) eq 'HASH') {
                   15888:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15889:             }
                   15890:             if (ref($timerintenv) eq 'HASH') {
                   15891:                 &_add_to_env(\%disk_env,$timerintenv);
                   15892:             }
1.463     albertel 15893: 	    if (ref($args->{'extra_env'})) {
                   15894: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15895: 	    }
1.462     albertel 15896: 	    untie(%disk_env);
                   15897: 	} else {
1.705     tempelho 15898: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15899: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15900: 	    return 'error: '.$!;
                   15901: 	}
                   15902:     }
                   15903:     $env{'request.role'}='cm';
                   15904:     $env{'request.role.adv'}=$env{'user.adv'};
                   15905:     $env{'browser.type'}=$clientbrowser;
                   15906: 
                   15907:     return $cookie;
                   15908: 
                   15909: }
                   15910: 
                   15911: sub _add_to_env {
                   15912:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15913:     if (ref($env_data) eq 'HASH') {
                   15914:         while (my ($key,$value) = each(%$env_data)) {
                   15915: 	    $idf->{$prefix.$key} = $value;
                   15916: 	    $env{$prefix.$key}   = $value;
                   15917:         }
1.462     albertel 15918:     }
                   15919: }
                   15920: 
1.685     tempelho 15921: # --- Get the symbolic name of a problem and the url
                   15922: sub get_symb {
                   15923:     my ($request,$silent) = @_;
1.726     raeburn  15924:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15925:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15926:     if ($symb eq '') {
                   15927:         if (!$silent) {
1.1071    raeburn  15928:             if (ref($request)) { 
                   15929:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15930:             }
1.685     tempelho 15931:             return ();
                   15932:         }
                   15933:     }
                   15934:     &Apache::lonenc::check_decrypt(\$symb);
                   15935:     return ($symb);
                   15936: }
                   15937: 
                   15938: # --------------------------------------------------------------Get annotation
                   15939: 
                   15940: sub get_annotation {
                   15941:     my ($symb,$enc) = @_;
                   15942: 
                   15943:     my $key = $symb;
                   15944:     if (!$enc) {
                   15945:         $key =
                   15946:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15947:     }
                   15948:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   15949:     return $annotation{$key};
                   15950: }
                   15951: 
                   15952: sub clean_symb {
1.731     raeburn  15953:     my ($symb,$delete_enc) = @_;
1.685     tempelho 15954: 
                   15955:     &Apache::lonenc::check_decrypt(\$symb);
                   15956:     my $enc = $env{'request.enc'};
1.731     raeburn  15957:     if ($delete_enc) {
1.730     raeburn  15958:         delete($env{'request.enc'});
                   15959:     }
1.685     tempelho 15960: 
                   15961:     return ($symb,$enc);
                   15962: }
1.462     albertel 15963: 
1.1075.2.69  raeburn  15964: ############################################################
                   15965: ############################################################
                   15966: 
                   15967: =pod
                   15968: 
                   15969: =head1 Routines for building display used to search for courses
                   15970: 
                   15971: 
                   15972: =over 4
                   15973: 
                   15974: =item * &build_filters()
                   15975: 
                   15976: Create markup for a table used to set filters to use when selecting
                   15977: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   15978: and quotacheck.pl
                   15979: 
                   15980: 
                   15981: Inputs:
                   15982: 
                   15983: filterlist - anonymous array of fields to include as potential filters
                   15984: 
                   15985: crstype - course type
                   15986: 
                   15987: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   15988:               to pop-open a course selector (will contain "extra element").
                   15989: 
                   15990: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   15991: 
                   15992: filter - anonymous hash of criteria and their values
                   15993: 
                   15994: action - form action
                   15995: 
                   15996: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   15997: 
                   15998: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   15999: 
                   16000: cloneruname - username of owner of new course who wants to clone
                   16001: 
                   16002: clonerudom - domain of owner of new course who wants to clone
                   16003: 
                   16004: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   16005: 
                   16006: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16007: 
                   16008: codedom - domain
                   16009: 
                   16010: formname - value of form element named "form".
                   16011: 
                   16012: fixeddom - domain, if fixed.
                   16013: 
                   16014: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   16015: 
                   16016: cnameelement - name of form element in form on opener page which will receive title of selected course
                   16017: 
                   16018: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16019: 
                   16020: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16021: 
                   16022: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16023: 
                   16024: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16025: 
                   16026: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16027: 
                   16028: 
                   16029: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16030: 
                   16031: 
                   16032: Side Effects: None
                   16033: 
                   16034: =cut
                   16035: 
                   16036: # ---------------------------------------------- search for courses based on last activity etc.
                   16037: 
                   16038: sub build_filters {
                   16039:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16040:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16041:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16042:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16043:         $clonetext,$clonewarning) = @_;
                   16044:     my ($list,$jscript);
                   16045:     my $onchange = 'javascript:updateFilters(this)';
                   16046:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16047:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16048:         $typeselectform,$instcodetitle);
                   16049:     if ($formname eq '') {
                   16050:         $formname = $caller;
                   16051:     }
                   16052:     foreach my $item (@{$filterlist}) {
                   16053:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16054:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16055:             if ($item eq 'domainfilter') {
                   16056:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16057:             } elsif ($item eq 'coursefilter') {
                   16058:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16059:             } elsif ($item eq 'ownerfilter') {
                   16060:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16061:             } elsif ($item eq 'ownerdomfilter') {
                   16062:                 $filter->{'ownerdomfilter'} =
                   16063:                     &LONCAPA::clean_domain($filter->{$item});
                   16064:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16065:                                                        'ownerdomfilter',1);
                   16066:             } elsif ($item eq 'personfilter') {
                   16067:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16068:             } elsif ($item eq 'persondomfilter') {
                   16069:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16070:                                                         'persondomfilter',1);
                   16071:             } else {
                   16072:                 $filter->{$item} =~ s/\W//g;
                   16073:             }
                   16074:             if (!$filter->{$item}) {
                   16075:                 $filter->{$item} = '';
                   16076:             }
                   16077:         }
                   16078:         if ($item eq 'domainfilter') {
                   16079:             my $allow_blank = 1;
                   16080:             if ($formname eq 'portform') {
                   16081:                 $allow_blank=0;
                   16082:             } elsif ($formname eq 'studentform') {
                   16083:                 $allow_blank=0;
                   16084:             }
                   16085:             if ($fixeddom) {
                   16086:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16087:                                     ' value="'.$codedom.'" />'.
                   16088:                                     &Apache::lonnet::domain($codedom,'description');
                   16089:             } else {
                   16090:                 $domainselectform = &select_dom_form($filter->{$item},
                   16091:                                                      'domainfilter',
                   16092:                                                       $allow_blank,'',$onchange);
                   16093:             }
                   16094:         } else {
                   16095:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16096:         }
                   16097:     }
                   16098: 
                   16099:     # last course activity filter and selection
                   16100:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16101: 
                   16102:     # course created filter and selection
                   16103:     if (exists($filter->{'createdfilter'})) {
                   16104:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16105:     }
                   16106: 
                   16107:     my %lt = &Apache::lonlocal::texthash(
                   16108:                 'cac' => "$crstype Activity",
                   16109:                 'ccr' => "$crstype Created",
                   16110:                 'cde' => "$crstype Title",
                   16111:                 'cdo' => "$crstype Domain",
                   16112:                 'ins' => 'Institutional Code',
                   16113:                 'inc' => 'Institutional Categorization',
                   16114:                 'cow' => "$crstype Owner/Co-owner",
                   16115:                 'cop' => "$crstype Personnel Includes",
                   16116:                 'cog' => 'Type',
                   16117:              );
                   16118: 
                   16119:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16120:         my $typeval = 'Course';
                   16121:         if ($crstype eq 'Community') {
                   16122:             $typeval = 'Community';
                   16123:         }
                   16124:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16125:     } else {
                   16126:         $typeselectform =  '<select name="type" size="1"';
                   16127:         if ($onchange) {
                   16128:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16129:         }
                   16130:         $typeselectform .= '>'."\n";
                   16131:         foreach my $posstype ('Course','Community') {
                   16132:             $typeselectform.='<option value="'.$posstype.'"'.
                   16133:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   16134:         }
                   16135:         $typeselectform.="</select>";
                   16136:     }
                   16137: 
                   16138:     my ($cloneableonlyform,$cloneabletitle);
                   16139:     if (exists($filter->{'cloneableonly'})) {
                   16140:         my $cloneableon = '';
                   16141:         my $cloneableoff = ' checked="checked"';
                   16142:         if ($filter->{'cloneableonly'}) {
                   16143:             $cloneableon = $cloneableoff;
                   16144:             $cloneableoff = '';
                   16145:         }
                   16146:         $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>';
                   16147:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  16148:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  16149:         } else {
                   16150:             $cloneabletitle = &mt('Cloneable by you');
                   16151:         }
                   16152:     }
                   16153:     my $officialjs;
                   16154:     if ($crstype eq 'Course') {
                   16155:         if (exists($filter->{'instcodefilter'})) {
                   16156: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16157: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16158:             if ($codedom) {
                   16159:                 $officialjs = 1;
                   16160:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16161:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16162:                                                                   $officialjs,$codetitlesref);
                   16163:                 if ($jscript) {
                   16164:                     $jscript = '<script type="text/javascript">'."\n".
                   16165:                                '// <![CDATA['."\n".
                   16166:                                $jscript."\n".
                   16167:                                '// ]]>'."\n".
                   16168:                                '</script>'."\n";
                   16169:                 }
                   16170:             }
                   16171:             if ($instcodeform eq '') {
                   16172:                 $instcodeform =
                   16173:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16174:                     $list->{'instcodefilter'}.'" />';
                   16175:                 $instcodetitle = $lt{'ins'};
                   16176:             } else {
                   16177:                 $instcodetitle = $lt{'inc'};
                   16178:             }
                   16179:             if ($fixeddom) {
                   16180:                 $instcodetitle .= '<br />('.$codedom.')';
                   16181:             }
                   16182:         }
                   16183:     }
                   16184:     my $output = qq|
                   16185: <form method="post" name="filterpicker" action="$action">
                   16186: <input type="hidden" name="form" value="$formname" />
                   16187: |;
                   16188:     if ($formname eq 'modifycourse') {
                   16189:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16190:                    '<input type="hidden" name="prevphase" value="'.
                   16191:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  16192:     } elsif ($formname eq 'quotacheck') {
                   16193:         $output .= qq|
                   16194: <input type="hidden" name="sortby" value="" />
                   16195: <input type="hidden" name="sortorder" value="" />
                   16196: |;
                   16197:     } else {
1.1075.2.69  raeburn  16198:         my $name_input;
                   16199:         if ($cnameelement ne '') {
                   16200:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16201:                           $cnameelement.'" />';
                   16202:         }
                   16203:         $output .= qq|
                   16204: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16205: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   16206: $name_input
                   16207: $roleelement
                   16208: $multelement
                   16209: $typeelement
                   16210: |;
                   16211:         if ($formname eq 'portform') {
                   16212:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16213:         }
                   16214:     }
                   16215:     if ($fixeddom) {
                   16216:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16217:     }
                   16218:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16219:     if ($sincefilterform) {
                   16220:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16221:                   .$sincefilterform
                   16222:                   .&Apache::lonhtmlcommon::row_closure();
                   16223:     }
                   16224:     if ($createdfilterform) {
                   16225:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16226:                   .$createdfilterform
                   16227:                   .&Apache::lonhtmlcommon::row_closure();
                   16228:     }
                   16229:     if ($domainselectform) {
                   16230:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16231:                   .$domainselectform
                   16232:                   .&Apache::lonhtmlcommon::row_closure();
                   16233:     }
                   16234:     if ($typeselectform) {
                   16235:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16236:             $output .= $typeselectform;
                   16237:         } else {
                   16238:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16239:                       .$typeselectform
                   16240:                       .&Apache::lonhtmlcommon::row_closure();
                   16241:         }
                   16242:     }
                   16243:     if ($instcodeform) {
                   16244:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16245:                   .$instcodeform
                   16246:                   .&Apache::lonhtmlcommon::row_closure();
                   16247:     }
                   16248:     if (exists($filter->{'ownerfilter'})) {
                   16249:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16250:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16251:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16252:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16253:                    $ownerdomselectform.'</td></tr></table>'.
                   16254:                    &Apache::lonhtmlcommon::row_closure();
                   16255:     }
                   16256:     if (exists($filter->{'personfilter'})) {
                   16257:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16258:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16259:                    '<input type="text" name="personfilter" size="20" value="'.
                   16260:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16261:                    $persondomselectform.'</td></tr></table>'.
                   16262:                    &Apache::lonhtmlcommon::row_closure();
                   16263:     }
                   16264:     if (exists($filter->{'coursefilter'})) {
                   16265:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16266:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16267:                   .$list->{'coursefilter'}.'" />'
                   16268:                   .&Apache::lonhtmlcommon::row_closure();
                   16269:     }
                   16270:     if ($cloneableonlyform) {
                   16271:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16272:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16273:     }
                   16274:     if (exists($filter->{'descriptfilter'})) {
                   16275:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16276:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16277:                   .$list->{'descriptfilter'}.'" />'
                   16278:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16279:     }
                   16280:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16281:                '<input type="hidden" name="updater" value="" />'."\n".
                   16282:                '<input type="submit" name="gosearch" value="'.
                   16283:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16284:     return $jscript.$clonewarning.$output;
                   16285: }
                   16286: 
                   16287: =pod
                   16288: 
                   16289: =item * &timebased_select_form()
                   16290: 
                   16291: Create markup for a dropdown list used to select a time-based
                   16292: filter e.g., Course Activity, Course Created, when searching for courses
                   16293: or communities
                   16294: 
                   16295: Inputs:
                   16296: 
                   16297: item - name of form element (sincefilter or createdfilter)
                   16298: 
                   16299: filter - anonymous hash of criteria and their values
                   16300: 
                   16301: Returns: HTML for a select box contained a blank, then six time selections,
                   16302:          with value set in incoming form variables currently selected.
                   16303: 
                   16304: Side Effects: None
                   16305: 
                   16306: =cut
                   16307: 
                   16308: sub timebased_select_form {
                   16309:     my ($item,$filter) = @_;
                   16310:     if (ref($filter) eq 'HASH') {
                   16311:         $filter->{$item} =~ s/[^\d-]//g;
                   16312:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16313:         return &select_form(
                   16314:                             $filter->{$item},
                   16315:                             $item,
                   16316:                             {      '-1' => '',
                   16317:                                 '86400' => &mt('today'),
                   16318:                                '604800' => &mt('last week'),
                   16319:                               '2592000' => &mt('last month'),
                   16320:                               '7776000' => &mt('last three months'),
                   16321:                              '15552000' => &mt('last six months'),
                   16322:                              '31104000' => &mt('last year'),
                   16323:                     'select_form_order' =>
                   16324:                            ['-1','86400','604800','2592000','7776000',
                   16325:                             '15552000','31104000']});
                   16326:     }
                   16327: }
                   16328: 
                   16329: =pod
                   16330: 
                   16331: =item * &js_changer()
                   16332: 
                   16333: Create script tag containing Javascript used to submit course search form
                   16334: when course type or domain is changed, and also to hide 'Searching ...' on
                   16335: page load completion for page showing search result.
                   16336: 
                   16337: Inputs: None
                   16338: 
                   16339: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   16340: 
                   16341: Side Effects: None
                   16342: 
                   16343: =cut
                   16344: 
                   16345: sub js_changer {
                   16346:     return <<ENDJS;
                   16347: <script type="text/javascript">
                   16348: // <![CDATA[
                   16349: function updateFilters(caller) {
                   16350:     if (typeof(caller) != "undefined") {
                   16351:         document.filterpicker.updater.value = caller.name;
                   16352:     }
                   16353:     document.filterpicker.submit();
                   16354: }
                   16355: 
                   16356: function hideSearching() {
                   16357:     if (document.getElementById('searching')) {
                   16358:         document.getElementById('searching').style.display = 'none';
                   16359:     }
                   16360:     return;
                   16361: }
                   16362: 
                   16363: // ]]>
                   16364: </script>
                   16365: 
                   16366: ENDJS
                   16367: }
                   16368: 
                   16369: =pod
                   16370: 
                   16371: =item * &search_courses()
                   16372: 
                   16373: Process selected filters form course search form and pass to lonnet::courseiddump
                   16374: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16375: 
                   16376: Inputs:
                   16377: 
                   16378: dom - domain being searched
                   16379: 
                   16380: type - course type ('Course' or 'Community' or '.' if any).
                   16381: 
                   16382: filter - anonymous hash of criteria and their values
                   16383: 
                   16384: numtitles - for institutional codes - number of categories
                   16385: 
                   16386: cloneruname - optional username of new course owner
                   16387: 
                   16388: clonerudom - optional domain of new course owner
                   16389: 
1.1075.2.95  raeburn  16390: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  16391:             (used when DC is using course creation form)
                   16392: 
                   16393: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16394: 
1.1075.2.95  raeburn  16395: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16396:            (and so can clone automatically)
                   16397: 
                   16398: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16399: 
                   16400: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   16401:               courses to clone
1.1075.2.69  raeburn  16402: 
                   16403: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16404: 
                   16405: 
                   16406: Side Effects: None
                   16407: 
                   16408: =cut
                   16409: 
                   16410: 
                   16411: sub search_courses {
1.1075.2.95  raeburn  16412:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16413:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  16414:     my (%courses,%showcourses,$cloner);
                   16415:     if (($filter->{'ownerfilter'} ne '') ||
                   16416:         ($filter->{'ownerdomfilter'} ne '')) {
                   16417:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16418:                                        $filter->{'ownerdomfilter'};
                   16419:     }
                   16420:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16421:         if (!$filter->{$item}) {
                   16422:             $filter->{$item}='.';
                   16423:         }
                   16424:     }
                   16425:     my $now = time;
                   16426:     my $timefilter =
                   16427:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16428:     my ($createdbefore,$createdafter);
                   16429:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16430:         $createdbefore = $now;
                   16431:         $createdafter = $now-$filter->{'createdfilter'};
                   16432:     }
                   16433:     my ($instcodefilter,$regexpok);
                   16434:     if ($numtitles) {
                   16435:         if ($env{'form.official'} eq 'on') {
                   16436:             $instcodefilter =
                   16437:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16438:             $regexpok = 1;
                   16439:         } elsif ($env{'form.official'} eq 'off') {
                   16440:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16441:             unless ($instcodefilter eq '') {
                   16442:                 $regexpok = -1;
                   16443:             }
                   16444:         }
                   16445:     } else {
                   16446:         $instcodefilter = $filter->{'instcodefilter'};
                   16447:     }
                   16448:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16449:     if ($type eq '') { $type = '.'; }
                   16450: 
                   16451:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16452:         $cloner = $cloneruname.':'.$clonerudom;
                   16453:     }
                   16454:     %courses = &Apache::lonnet::courseiddump($dom,
                   16455:                                              $filter->{'descriptfilter'},
                   16456:                                              $timefilter,
                   16457:                                              $instcodefilter,
                   16458:                                              $filter->{'combownerfilter'},
                   16459:                                              $filter->{'coursefilter'},
                   16460:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  16461:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  16462:                                              $filter->{'cloneableonly'},
                   16463:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  16464:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  16465:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16466:         my $ccrole;
                   16467:         if ($type eq 'Community') {
                   16468:             $ccrole = 'co';
                   16469:         } else {
                   16470:             $ccrole = 'cc';
                   16471:         }
                   16472:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16473:                                                      $filter->{'persondomfilter'},
                   16474:                                                      'userroles',undef,
                   16475:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16476:                                                      $dom);
                   16477:         foreach my $role (keys(%rolehash)) {
                   16478:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16479:             my $cid = $cdom.'_'.$cnum;
                   16480:             if (exists($courses{$cid})) {
                   16481:                 if (ref($courses{$cid}) eq 'HASH') {
                   16482:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16483:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  16484:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  16485:                         }
                   16486:                     } else {
                   16487:                         $courses{$cid}{roles} = [$courserole];
                   16488:                     }
                   16489:                     $showcourses{$cid} = $courses{$cid};
                   16490:                 }
                   16491:             }
                   16492:         }
                   16493:         %courses = %showcourses;
                   16494:     }
                   16495:     return %courses;
                   16496: }
                   16497: 
                   16498: =pod
                   16499: 
                   16500: =back
                   16501: 
1.1075.2.88  raeburn  16502: =head1 Routines for version requirements for current course.
                   16503: 
                   16504: =over 4
                   16505: 
                   16506: =item * &check_release_required()
                   16507: 
                   16508: Compares required LON-CAPA version with version on server, and
                   16509: if required version is newer looks for a server with the required version.
                   16510: 
                   16511: Looks first at servers in user's owen domain; if none suitable, looks at
                   16512: servers in course's domain are permitted to host sessions for user's domain.
                   16513: 
                   16514: Inputs:
                   16515: 
                   16516: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16517: 
                   16518: $courseid - Course ID of current course
                   16519: 
                   16520: $rolecode - User's current role in course (for switchserver query string).
                   16521: 
                   16522: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16523: 
                   16524: 
                   16525: Returns:
                   16526: 
                   16527: $switchserver - query string tp append to /adm/switchserver call (if
                   16528:                 current server's LON-CAPA version is too old.
                   16529: 
                   16530: $warning - Message is displayed if no suitable server could be found.
                   16531: 
                   16532: =cut
                   16533: 
                   16534: sub check_release_required {
                   16535:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16536:     my ($switchserver,$warning);
                   16537:     if ($required ne '') {
                   16538:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16539:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16540:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16541:             my $otherserver;
                   16542:             if (($major eq '' && $minor eq '') ||
                   16543:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16544:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16545:                 my $switchlcrev =
                   16546:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16547:                                                            $userdomserver);
                   16548:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16549:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16550:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16551:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16552:                     if ($cdom ne $env{'user.domain'}) {
                   16553:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16554:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16555:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16556:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16557:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16558:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16559:                         my $canhost =
                   16560:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16561:                                                               $coursedomserver,
                   16562:                                                               $remoterev,
                   16563:                                                               $udomdefaults{'remotesessions'},
                   16564:                                                               $defdomdefaults{'hostedsessions'});
                   16565: 
                   16566:                         if ($canhost) {
                   16567:                             $otherserver = $coursedomserver;
                   16568:                         } else {
                   16569:                             $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.");
                   16570:                         }
                   16571:                     } else {
                   16572:                         $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).");
                   16573:                     }
                   16574:                 } else {
                   16575:                     $otherserver = $userdomserver;
                   16576:                 }
                   16577:             }
                   16578:             if ($otherserver ne '') {
                   16579:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16580:             }
                   16581:         }
                   16582:     }
                   16583:     return ($switchserver,$warning);
                   16584: }
                   16585: 
                   16586: =pod
                   16587: 
                   16588: =item * &check_release_result()
                   16589: 
                   16590: Inputs:
                   16591: 
                   16592: $switchwarning - Warning message if no suitable server found to host session.
                   16593: 
                   16594: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16595:                 and current role.
                   16596: 
                   16597: Returns: HTML to display with information about requirement to switch server.
                   16598:          Either displaying warning with link to Roles/Courses screen or
                   16599:          display link to switchserver.
                   16600: 
1.1075.2.69  raeburn  16601: =cut
                   16602: 
1.1075.2.88  raeburn  16603: sub check_release_result {
                   16604:     my ($switchwarning,$switchserver) = @_;
                   16605:     my $output = &start_page('Selected course unavailable on this server').
                   16606:                  '<p class="LC_warning">';
                   16607:     if ($switchwarning) {
                   16608:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16609:         if (&show_course()) {
                   16610:             $output .= &mt('Display courses');
                   16611:         } else {
                   16612:             $output .= &mt('Display roles');
                   16613:         }
                   16614:         $output .= '</a>';
                   16615:     } elsif ($switchserver) {
                   16616:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16617:                    '<br />'.
                   16618:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16619:                    &mt('Switch Server').
                   16620:                    '</a>';
                   16621:     }
                   16622:     $output .= '</p>'.&end_page();
                   16623:     return $output;
                   16624: }
                   16625: 
                   16626: =pod
                   16627: 
                   16628: =item * &needs_coursereinit()
                   16629: 
                   16630: Determine if course contents stored for user's session needs to be
                   16631: refreshed, because content has changed since "Big Hash" last tied.
                   16632: 
                   16633: Check for change is made if time last checked is more than 10 minutes ago
                   16634: (by default).
                   16635: 
                   16636: Inputs:
                   16637: 
                   16638: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16639: 
                   16640: $interval (optional) - Time which may elapse (in s) between last check for content
                   16641:                        change in current course. (default: 600 s).
                   16642: 
                   16643: Returns: an array; first element is:
                   16644: 
                   16645: =over 4
                   16646: 
                   16647: 'switch' - if content updates mean user's session
                   16648:            needs to be switched to a server running a newer LON-CAPA version
                   16649: 
                   16650: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16651:            on current server hosting user's session
                   16652: 
                   16653: ''       - if no action required.
                   16654: 
                   16655: =back
                   16656: 
                   16657: If first item element is 'switch':
                   16658: 
                   16659: second item is $switchwarning - Warning message if no suitable server found to host session.
                   16660: 
                   16661: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16662:                               and current role.
                   16663: 
                   16664: otherwise: no other elements returned.
                   16665: 
                   16666: =back
                   16667: 
                   16668: =cut
                   16669: 
                   16670: sub needs_coursereinit {
                   16671:     my ($loncaparev,$interval) = @_;
                   16672:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16673:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16674:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16675:     my $now = time;
                   16676:     if ($interval eq '') {
                   16677:         $interval = 600;
                   16678:     }
                   16679:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16680:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16681:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16682:         if ($lastchange > $env{'request.course.tied'}) {
                   16683:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16684:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16685:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16686:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16687:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16688:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16689:                     my ($switchserver,$switchwarning) =
                   16690:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16691:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16692:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16693:                         return ('switch',$switchwarning,$switchserver);
                   16694:                     }
                   16695:                 }
                   16696:             }
                   16697:             return ('update');
                   16698:         }
                   16699:     }
                   16700:     return ();
                   16701: }
1.1075.2.69  raeburn  16702: 
1.1075.2.11  raeburn  16703: sub update_content_constraints {
                   16704:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16705:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16706:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16707:     my %checkresponsetypes;
                   16708:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   16709:         my ($item,$name,$value) = split(/:/,$key);
                   16710:         if ($item eq 'resourcetag') {
                   16711:             if ($name eq 'responsetype') {
                   16712:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16713:             }
                   16714:         }
                   16715:     }
                   16716:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16717:     if (defined($navmap)) {
                   16718:         my %allresponses;
                   16719:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16720:             my %responses = $res->responseTypes();
                   16721:             foreach my $key (keys(%responses)) {
                   16722:                 next unless(exists($checkresponsetypes{$key}));
                   16723:                 $allresponses{$key} += $responses{$key};
                   16724:             }
                   16725:         }
                   16726:         foreach my $key (keys(%allresponses)) {
                   16727:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16728:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16729:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16730:             }
                   16731:         }
                   16732:         undef($navmap);
                   16733:     }
                   16734:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16735:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16736:     }
                   16737:     return;
                   16738: }
                   16739: 
1.1075.2.27  raeburn  16740: sub allmaps_incourse {
                   16741:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16742:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16743:         $cid = $env{'request.course.id'};
                   16744:         $cdom = $env{'course.'.$cid.'.domain'};
                   16745:         $cnum = $env{'course.'.$cid.'.num'};
                   16746:         $chome = $env{'course.'.$cid.'.home'};
                   16747:     }
                   16748:     my %allmaps = ();
                   16749:     my $lastchange =
                   16750:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16751:     if ($lastchange > $env{'request.course.tied'}) {
                   16752:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16753:         unless ($ferr) {
                   16754:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16755:         }
                   16756:     }
                   16757:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16758:     if (defined($navmap)) {
                   16759:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16760:             $allmaps{$res->src()} = 1;
                   16761:         }
                   16762:     }
                   16763:     return \%allmaps;
                   16764: }
                   16765: 
1.1075.2.11  raeburn  16766: sub parse_supplemental_title {
                   16767:     my ($title) = @_;
                   16768: 
                   16769:     my ($foldertitle,$renametitle);
                   16770:     if ($title =~ /&amp;&amp;&amp;/) {
                   16771:         $title = &HTML::Entites::decode($title);
                   16772:     }
                   16773:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16774:         $renametitle=$4;
                   16775:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16776:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16777:         my $name =  &plainname($uname,$udom);
                   16778:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16779:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16780:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16781:             $name.': <br />'.$foldertitle;
                   16782:     }
                   16783:     if (wantarray) {
                   16784:         return ($title,$foldertitle,$renametitle);
                   16785:     }
                   16786:     return $title;
                   16787: }
                   16788: 
1.1075.2.43  raeburn  16789: sub recurse_supplemental {
                   16790:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16791:     if ($suppmap) {
                   16792:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16793:         if ($fatal) {
                   16794:             $errors ++;
                   16795:         } else {
                   16796:             if ($#LONCAPA::map::resources > 0) {
                   16797:                 foreach my $res (@LONCAPA::map::resources) {
                   16798:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16799:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  16800:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16801:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  16802:                         } else {
                   16803:                             $numfiles ++;
                   16804:                         }
                   16805:                     }
                   16806:                 }
                   16807:             }
                   16808:         }
                   16809:     }
                   16810:     return ($numfiles,$errors);
                   16811: }
                   16812: 
1.1075.2.18  raeburn  16813: sub symb_to_docspath {
1.1075.2.119  raeburn  16814:     my ($symb,$navmapref) = @_;
                   16815:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  16816:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16817:     if ($resurl=~/\.(sequence|page)$/) {
                   16818:         $mapurl=$resurl;
                   16819:     } elsif ($resurl eq 'adm/navmaps') {
                   16820:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16821:     }
                   16822:     my $mapresobj;
1.1075.2.119  raeburn  16823:     unless (ref($$navmapref)) {
                   16824:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   16825:     }
                   16826:     if (ref($$navmapref)) {
                   16827:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  16828:     }
                   16829:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16830:     my $type=$2;
                   16831:     my $path;
                   16832:     if (ref($mapresobj)) {
                   16833:         my $pcslist = $mapresobj->map_hierarchy();
                   16834:         if ($pcslist ne '') {
                   16835:             foreach my $pc (split(/,/,$pcslist)) {
                   16836:                 next if ($pc <= 1);
1.1075.2.119  raeburn  16837:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  16838:                 if (ref($res)) {
                   16839:                     my $thisurl = $res->src();
                   16840:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16841:                     my $thistitle = $res->title();
                   16842:                     $path .= '&'.
                   16843:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  16844:                              &escape($thistitle).
1.1075.2.18  raeburn  16845:                              ':'.$res->randompick().
                   16846:                              ':'.$res->randomout().
                   16847:                              ':'.$res->encrypted().
                   16848:                              ':'.$res->randomorder().
                   16849:                              ':'.$res->is_page();
                   16850:                 }
                   16851:             }
                   16852:         }
                   16853:         $path =~ s/^\&//;
                   16854:         my $maptitle = $mapresobj->title();
                   16855:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16856:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16857:         }
                   16858:         $path .= (($path ne '')? '&' : '').
                   16859:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16860:                  &escape($maptitle).
1.1075.2.18  raeburn  16861:                  ':'.$mapresobj->randompick().
                   16862:                  ':'.$mapresobj->randomout().
                   16863:                  ':'.$mapresobj->encrypted().
                   16864:                  ':'.$mapresobj->randomorder().
                   16865:                  ':'.$mapresobj->is_page();
                   16866:     } else {
                   16867:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16868:         my $ispage = (($type eq 'page')? 1 : '');
                   16869:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16870:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16871:         }
                   16872:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16873:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  16874:     }
                   16875:     unless ($mapurl eq 'default') {
                   16876:         $path = 'default&'.
1.1075.2.46  raeburn  16877:                 &escape('Main Content').
1.1075.2.18  raeburn  16878:                 ':::::&'.$path;
                   16879:     }
                   16880:     return $path;
                   16881: }
                   16882: 
1.1075.2.14  raeburn  16883: sub captcha_display {
1.1075.2.137  raeburn  16884:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  16885:     my ($output,$error);
1.1075.2.107  raeburn  16886:     my ($captcha,$pubkey,$privkey,$version) =
1.1075.2.137  raeburn  16887:         &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  16888:     if ($captcha eq 'original') {
                   16889:         $output = &create_captcha();
                   16890:         unless ($output) {
                   16891:             $error = 'captcha';
                   16892:         }
                   16893:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16894:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  16895:         unless ($output) {
                   16896:             $error = 'recaptcha';
                   16897:         }
                   16898:     }
1.1075.2.107  raeburn  16899:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  16900: }
                   16901: 
                   16902: sub captcha_response {
1.1075.2.137  raeburn  16903:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  16904:     my ($captcha_chk,$captcha_error);
1.1075.2.137  raeburn  16905:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  16906:     if ($captcha eq 'original') {
                   16907:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16908:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16909:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  16910:     } else {
                   16911:         $captcha_chk = 1;
                   16912:     }
                   16913:     return ($captcha_chk,$captcha_error);
                   16914: }
                   16915: 
                   16916: sub get_captcha_config {
1.1075.2.137  raeburn  16917:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1075.2.107  raeburn  16918:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  16919:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   16920:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   16921:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16922:     if ($context eq 'usercreation') {
                   16923:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   16924:         if (ref($domconfig{$context}) eq 'HASH') {
                   16925:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   16926:             if (ref($hashtocheck) eq 'HASH') {
                   16927:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   16928:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   16929:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   16930:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   16931:                     }
                   16932:                     if ($privkey && $pubkey) {
                   16933:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  16934:                         $version = $hashtocheck->{'recaptchaversion'};
                   16935:                         if ($version ne '2') {
                   16936:                             $version = 1;
                   16937:                         }
1.1075.2.14  raeburn  16938:                     } else {
                   16939:                         $captcha = 'original';
                   16940:                     }
                   16941:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   16942:                     $captcha = 'original';
                   16943:                 }
                   16944:             }
                   16945:         } else {
                   16946:             $captcha = 'captcha';
                   16947:         }
                   16948:     } elsif ($context eq 'login') {
                   16949:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   16950:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   16951:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   16952:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   16953:             if ($privkey && $pubkey) {
                   16954:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  16955:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   16956:                 if ($version ne '2') {
                   16957:                     $version = 1;
                   16958:                 }
1.1075.2.14  raeburn  16959:             } else {
                   16960:                 $captcha = 'original';
                   16961:             }
                   16962:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   16963:             $captcha = 'original';
                   16964:         }
1.1075.2.137  raeburn  16965:     } elsif ($context eq 'passwords') {
                   16966:         if ($dom_in_effect) {
                   16967:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   16968:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   16969:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   16970:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   16971:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   16972:                 }
                   16973:                 if ($privkey && $pubkey) {
                   16974:                     $captcha = 'recaptcha';
                   16975:                     $version = $passwdconf{'recaptchaversion'};
                   16976:                     if ($version ne '2') {
                   16977:                         $version = 1;
                   16978:                     }
                   16979:                 } else {
                   16980:                     $captcha = 'original';
                   16981:                 }
                   16982:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   16983:                 $captcha = 'original';
                   16984:             }
                   16985:         }
1.1075.2.14  raeburn  16986:     }
1.1075.2.107  raeburn  16987:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  16988: }
                   16989: 
                   16990: sub create_captcha {
                   16991:     my %captcha_params = &captcha_settings();
                   16992:     my ($output,$maxtries,$tries) = ('',10,0);
                   16993:     while ($tries < $maxtries) {
                   16994:         $tries ++;
                   16995:         my $captcha = Authen::Captcha->new (
                   16996:                                            output_folder => $captcha_params{'output_dir'},
                   16997:                                            data_folder   => $captcha_params{'db_dir'},
                   16998:                                           );
                   16999:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17000: 
                   17001:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17002:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17003:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  17004:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17005:                       '<br />'.
                   17006:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  17007:             last;
                   17008:         }
                   17009:     }
                   17010:     return $output;
                   17011: }
                   17012: 
                   17013: sub captcha_settings {
                   17014:     my %captcha_params = (
                   17015:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17016:                            www_output_dir => "/captchaspool",
                   17017:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17018:                            numchars       => '5',
                   17019:                          );
                   17020:     return %captcha_params;
                   17021: }
                   17022: 
                   17023: sub check_captcha {
                   17024:     my ($captcha_chk,$captcha_error);
                   17025:     my $code = $env{'form.code'};
                   17026:     my $md5sum = $env{'form.crypt'};
                   17027:     my %captcha_params = &captcha_settings();
                   17028:     my $captcha = Authen::Captcha->new(
                   17029:                       output_folder => $captcha_params{'output_dir'},
                   17030:                       data_folder   => $captcha_params{'db_dir'},
                   17031:                   );
1.1075.2.26  raeburn  17032:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  17033:     my %captcha_hash = (
                   17034:                         0       => 'Code not checked (file error)',
                   17035:                        -1      => 'Failed: code expired',
                   17036:                        -2      => 'Failed: invalid code (not in database)',
                   17037:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17038:     );
                   17039:     if ($captcha_chk != 1) {
                   17040:         $captcha_error = $captcha_hash{$captcha_chk}
                   17041:     }
                   17042:     return ($captcha_chk,$captcha_error);
                   17043: }
                   17044: 
                   17045: sub create_recaptcha {
1.1075.2.107  raeburn  17046:     my ($pubkey,$version) = @_;
                   17047:     if ($version >= 2) {
                   17048:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17049:     } else {
                   17050:         my $use_ssl;
                   17051:         if ($ENV{'SERVER_PORT'} == 443) {
                   17052:             $use_ssl = 1;
                   17053:         }
                   17054:         my $captcha = Captcha::reCAPTCHA->new;
                   17055:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17056:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17057:                &mt('If the text is hard to read, [_1] will replace them.',
                   17058:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17059:                '<br /><br />';
                   17060:      }
1.1075.2.14  raeburn  17061: }
                   17062: 
                   17063: sub check_recaptcha {
1.1075.2.107  raeburn  17064:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  17065:     my $captcha_chk;
1.1075.2.107  raeburn  17066:     if ($version >= 2) {
                   17067:         my $ua = LWP::UserAgent->new;
                   17068:         $ua->timeout(10);
                   17069:         my %info = (
                   17070:                      secret   => $privkey,
                   17071:                      response => $env{'form.g-recaptcha-response'},
                   17072:                      remoteip => $ENV{'REMOTE_ADDR'},
                   17073:                    );
                   17074:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   17075:         if ($response->is_success)  {
                   17076:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17077:             if (ref($data) eq 'HASH') {
                   17078:                 if ($data->{'success'}) {
                   17079:                     $captcha_chk = 1;
                   17080:                 }
                   17081:             }
                   17082:         }
                   17083:     } else {
                   17084:         my $captcha = Captcha::reCAPTCHA->new;
                   17085:         my $captcha_result =
                   17086:             $captcha->check_answer(
                   17087:                                     $privkey,
                   17088:                                     $ENV{'REMOTE_ADDR'},
                   17089:                                     $env{'form.recaptcha_challenge_field'},
                   17090:                                     $env{'form.recaptcha_response_field'},
                   17091:                                   );
                   17092:         if ($captcha_result->{is_valid}) {
                   17093:             $captcha_chk = 1;
                   17094:         }
1.1075.2.14  raeburn  17095:     }
                   17096:     return $captcha_chk;
                   17097: }
                   17098: 
1.1075.2.64  raeburn  17099: sub emailusername_info {
1.1075.2.103  raeburn  17100:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  17101:     my %titles = &Apache::lonlocal::texthash (
                   17102:                      lastname      => 'Last Name',
                   17103:                      firstname     => 'First Name',
                   17104:                      institution   => 'School/college/university',
                   17105:                      location      => "School's city, state/province, country",
                   17106:                      web           => "School's web address",
                   17107:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  17108:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  17109:                  );
                   17110:     return (\@fields,\%titles);
                   17111: }
                   17112: 
1.1075.2.56  raeburn  17113: sub cleanup_html {
                   17114:     my ($incoming) = @_;
                   17115:     my $outgoing;
                   17116:     if ($incoming ne '') {
                   17117:         $outgoing = $incoming;
                   17118:         $outgoing =~ s/;/&#059;/g;
                   17119:         $outgoing =~ s/\#/&#035;/g;
                   17120:         $outgoing =~ s/\&/&#038;/g;
                   17121:         $outgoing =~ s/</&#060;/g;
                   17122:         $outgoing =~ s/>/&#062;/g;
                   17123:         $outgoing =~ s/\(/&#040/g;
                   17124:         $outgoing =~ s/\)/&#041;/g;
                   17125:         $outgoing =~ s/"/&#034;/g;
                   17126:         $outgoing =~ s/'/&#039;/g;
                   17127:         $outgoing =~ s/\$/&#036;/g;
                   17128:         $outgoing =~ s{/}{&#047;}g;
                   17129:         $outgoing =~ s/=/&#061;/g;
                   17130:         $outgoing =~ s/\\/&#092;/g
                   17131:     }
                   17132:     return $outgoing;
                   17133: }
                   17134: 
1.1075.2.74  raeburn  17135: # Checks for critical messages and returns a redirect url if one exists.
                   17136: # $interval indicates how often to check for messages.
                   17137: sub critical_redirect {
                   17138:     my ($interval) = @_;
                   17139:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   17140:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   17141:                                         $env{'user.name'});
                   17142:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   17143:         my $redirecturl;
                   17144:         if ($what[0]) {
                   17145:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   17146:                 $redirecturl='/adm/email?critical=display';
                   17147:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17148:                 return (1, $url);
                   17149:             }
                   17150:         }
                   17151:     }
                   17152:     return ();
                   17153: }
                   17154: 
1.1075.2.64  raeburn  17155: # Use:
                   17156: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17157: #
                   17158: ##################################################
                   17159: #          password associated functions         #
                   17160: ##################################################
                   17161: sub des_keys {
                   17162:     # Make a new key for DES encryption.
                   17163:     # Each key has two parts which are returned separately.
                   17164:     # Please note:  Each key must be passed through the &hex function
                   17165:     # before it is output to the web browser.  The hex versions cannot
                   17166:     # be used to decrypt.
                   17167:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17168:                 '8','9','a','b','c','d','e','f');
                   17169:     my $lkey='';
                   17170:     for (0..7) {
                   17171:         $lkey.=$hexstr[rand(15)];
                   17172:     }
                   17173:     my $ukey='';
                   17174:     for (0..7) {
                   17175:         $ukey.=$hexstr[rand(15)];
                   17176:     }
                   17177:     return ($lkey,$ukey);
                   17178: }
                   17179: 
                   17180: sub des_decrypt {
                   17181:     my ($key,$cyphertext) = @_;
                   17182:     my $keybin=pack("H16",$key);
                   17183:     my $cypher;
                   17184:     if ($Crypt::DES::VERSION>=2.03) {
                   17185:         $cypher=new Crypt::DES $keybin;
                   17186:     } else {
                   17187:         $cypher=new DES $keybin;
                   17188:     }
1.1075.2.106  raeburn  17189:     my $plaintext='';
                   17190:     my $cypherlength = length($cyphertext);
                   17191:     my $numchunks = int($cypherlength/32);
                   17192:     for (my $j=0; $j<$numchunks; $j++) {
                   17193:         my $start = $j*32;
                   17194:         my $cypherblock = substr($cyphertext,$start,32);
                   17195:         my $chunk =
                   17196:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17197:         $chunk .=
                   17198:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17199:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17200:         $plaintext .= $chunk;
                   17201:     }
1.1075.2.64  raeburn  17202:     return $plaintext;
                   17203: }
                   17204: 
1.1075.2.141.  .1(raebu 17205:20): sub make_short_symbs {
                   17206:20):     my ($cdom,$cnum,$navmap) = @_;
                   17207:20):     return unless (ref($navmap));
                   17208:20):     my ($numnew,@errors);
                   17209:20):     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   17210:20):     if (@toshorten) {
                   17211:20):         my (%maps,%resources,%titles);
                   17212:20):         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   17213:20):                                                                'shorturls',$cdom,$cnum);
                   17214:20):         my %tocreate;
                   17215:20):         if (keys(%resources)) {
                   17216:20):             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   17217:20):                 my $symb = $resources{$item};
                   17218:20):                 if ($symb) {
                   17219:20):                     $tocreate{$cnum.'&'.$symb} = 1;
                   17220:20):                 }
                   17221:20):             }
                   17222:20):         }
                   17223:20):         if (keys(%tocreate)) {
                   17224:20):             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   17225:20):             my $su = Short::URL->new(no_vowels => 1);
                   17226:20):             my $init = '';
                   17227:20):             my (%newunique,%addcourse,%courseonly,%failed);
                   17228:20):             # get lock on tiny db
                   17229:20):             my $now = time;
                   17230:20):             my $lockhash = {
                   17231:20):                                 "lock\0$now" => $env{'user.name'}.
                   17232:20):                                                 ':'.$env{'user.domain'},
                   17233:20):                             };
                   17234:20):             my $tries = 0;
                   17235:20):             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   17236:20):             my ($code,$error);
                   17237:20):             while (($gotlock ne 'ok') && ($tries<3)) {
                   17238:20):                 $tries ++;
                   17239:20):                 sleep 1;
                   17240:20):                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   17241:20):             }
                   17242:20):             if ($gotlock eq 'ok') {
                   17243:20):                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   17244:20):                                        \%addcourse,\%courseonly,\%failed);
                   17245:20):                 if (keys(%failed)) {
                   17246:20):                     my $numfailed = scalar(keys(%failed));
                   17247:20):                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   17248:20):                 }
                   17249:20):                 if (keys(%newunique)) {
                   17250:20):                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   17251:20):                     if ($putres eq 'ok') {
                   17252:20):                         $numnew = scalar(keys(%newunique));
                   17253:20):                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   17254:20):                         unless ($newputres eq 'ok') {
                   17255:20):                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   17256:20):                         }
                   17257:20):                     } else {
                   17258:20):                         push(@errors,&mt('error: could not store unique six character URLs'));
                   17259:20):                     }
                   17260:20):                 }
                   17261:20):             }
                   17262:20):         }
                   17263:20):     }
                   17264:20):     return ($numnew,\@errors);
                   17265:20): }
                   17266:20): 
                   17267:20): sub shorten_symbs {
                   17268:20):     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   17269:20):     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   17270:20):                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   17271:20):                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   17272:20):     my (%possibles,%collisions);
                   17273:20):     foreach my $key (keys(%{$tocreate})) {
                   17274:20):         my $num = String::CRC32::crc32($key);
                   17275:20):         my $tiny = $su->encode($num,$init);
                   17276:20):         if ($tiny) {
                   17277:20):             $possibles{$tiny} = $key;
                   17278:20):         }
                   17279:20):     }
                   17280:20):     if (!$init) {
                   17281:20):         $init = 1;
                   17282:20):     } else {
                   17283:20):         $init ++;
                   17284:20):     }
                   17285:20):     if (keys(%possibles)) {
                   17286:20):         my @posstiny = keys(%possibles);
                   17287:20):         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   17288:20):         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   17289:20):         if (keys(%currtiny)) {
                   17290:20):             foreach my $key (keys(%currtiny)) {
                   17291:20):                 next if ($currtiny{$key} eq '');
                   17292:20):                 if ($currtiny{$key} eq $possibles{$key}) {
                   17293:20):                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   17294:20):                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   17295:20):                         $courseonly->{$tsymb} = $key;
                   17296:20):                     }
                   17297:20):                 } else {
                   17298:20):                     $collisions{$possibles{$key}} = 1;
                   17299:20):                 }
                   17300:20):                 delete($possibles{$key});
                   17301:20):             }
                   17302:20):         }
                   17303:20):         foreach my $key (keys(%possibles)) {
                   17304:20):             $newunique->{$key} = $possibles{$key};
                   17305:20):             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   17306:20):             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   17307:20):                 $addcourse->{$tsymb} = $key;
                   17308:20):             }
                   17309:20):         }
                   17310:20):     }
                   17311:20):     if (keys(%collisions)) {
                   17312:20):         if ($init <5) {
                   17313:20):             if (!$init) {
                   17314:20):                 $init = 1;
                   17315:20):             } else {
                   17316:20):                 $init ++;
                   17317:20):             }
                   17318:20):             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   17319:20):                                    $newunique,$addcourse,$courseonly,$failed);
                   17320:20):         } else {
                   17321:20):             foreach my $key (keys(%collisions)) {
                   17322:20):                 $failed->{$key} = 1;
                   17323:20):                 $failed->{$key} = 1;
                   17324:20):             }
                   17325:20):         }
                   17326:20):     }
                   17327:20):     return $init;
                   17328:20): }
                   17329:20): 
1.1075.2.135  raeburn  17330: sub is_nonframeable {
                   17331:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   17332:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
                   17333:     return if (($remprotocol eq '') || ($remhost eq ''));
                   17334: 
                   17335:     $remprotocol = lc($remprotocol);
                   17336:     $remhost = lc($remhost);
                   17337:     my $remport = 80;
                   17338:     if ($remprotocol eq 'https') {
                   17339:         $remport = 443;
                   17340:     }
                   17341:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
                   17342:     if ($cached) {
                   17343:         unless ($nocache) {
                   17344:             if ($result) {
                   17345:                 return 1;
                   17346:             } else {
                   17347:                 return 0;
                   17348:             }
                   17349:         }
                   17350:     }
                   17351:     my $uselink;
                   17352:     my $request = new HTTP::Request('HEAD',$url);
1.1075.2.141.  .2(raebu 17353:20):     my $ua = LWP::UserAgent->new;
                   17354:20):     $ua->timeout(5);
                   17355:20):     my $response=$ua->request($request);
1.1075.2.135  raeburn  17356:     if ($response->is_success()) {
                   17357:         my $secpolicy = lc($response->header('content-security-policy'));
                   17358:         my $xframeop = lc($response->header('x-frame-options'));
                   17359:         $secpolicy =~ s/^\s+|\s+$//g;
                   17360:         $xframeop =~ s/^\s+|\s+$//g;
                   17361:         if (($secpolicy ne '') || ($xframeop ne '')) {
                   17362:             my $remotehost = $remprotocol.'://'.$remhost;
                   17363:             my ($origin,$protocol,$port);
                   17364:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   17365:                 $port = $ENV{'SERVER_PORT'};
                   17366:             } else {
                   17367:                 $port = 80;
                   17368:             }
                   17369:             if ($absolute eq '') {
                   17370:                 $protocol = 'http:';
                   17371:                 if ($port == 443) {
                   17372:                     $protocol = 'https:';
                   17373:                 }
                   17374:                 $origin = $protocol.'//'.lc($hostname);
                   17375:             } else {
                   17376:                 $origin = lc($absolute);
                   17377:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   17378:             }
                   17379:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   17380:                 my $framepolicy = $1;
                   17381:                 $framepolicy =~ s/^\s+|\s+$//g;
                   17382:                 my @policies = split(/\s+/,$framepolicy);
                   17383:                 if (@policies) {
                   17384:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   17385:                         $uselink = 1;
                   17386:                     } else {
                   17387:                         $uselink = 1;
                   17388:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   17389:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   17390:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   17391:                             undef($uselink);
                   17392:                         }
                   17393:                         if ($uselink) {
                   17394:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   17395:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   17396:                                     undef($uselink);
                   17397:                                 }
                   17398:                             }
                   17399:                         }
                   17400:                         if ($uselink) {
                   17401:                             my @possok;
                   17402:                             if ($ip ne '') {
                   17403:                                 push(@possok,$ip);
                   17404:                             }
                   17405:                             my $hoststr = '';
                   17406:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   17407:                                 if ($hoststr eq '') {
                   17408:                                     $hoststr = $part;
                   17409:                                 } else {
                   17410:                                     $hoststr = "$part.$hoststr";
                   17411:                                 }
                   17412:                                 if ($hoststr eq $hostname) {
                   17413:                                     push(@possok,$hostname);
                   17414:                                 } else {
                   17415:                                     push(@possok,"*.$hoststr");
                   17416:                                 }
                   17417:                             }
                   17418:                             if (@possok) {
                   17419:                                 foreach my $poss (@possok) {
                   17420:                                     last if (!$uselink);
                   17421:                                     foreach my $policy (@policies) {
                   17422:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   17423:                                             undef($uselink);
                   17424:                                             last;
                   17425:                                         }
                   17426:                                     }
                   17427:                                 }
                   17428:                             }
                   17429:                         }
                   17430:                     }
                   17431:                 }
                   17432:             } elsif ($xframeop ne '') {
                   17433:                 $uselink = 1;
                   17434:                 my @policies = split(/\s*,\s*/,$xframeop);
                   17435:                 if (@policies) {
                   17436:                     unless (grep(/^deny$/,@policies)) {
                   17437:                         if ($origin ne '') {
                   17438:                             if (grep(/^sameorigin$/,@policies)) {
                   17439:                                 if ($remotehost eq $origin) {
                   17440:                                     undef($uselink);
                   17441:                                 }
                   17442:                             }
                   17443:                             if ($uselink) {
                   17444:                                 foreach my $policy (@policies) {
                   17445:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   17446:                                         my $allowfrom = $1;
                   17447:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   17448:                                             undef($uselink);
                   17449:                                             last;
                   17450:                                         }
                   17451:                                     }
                   17452:                                 }
                   17453:                             }
                   17454:                         }
                   17455:                     }
                   17456:                 }
                   17457:             }
                   17458:         }
                   17459:     }
                   17460:     if ($nocache) {
                   17461:         if ($cached) {
                   17462:             my $devalidate;
                   17463:             if ($uselink && !$result) {
                   17464:                 $devalidate = 1;
                   17465:             } elsif (!$uselink && $result) {
                   17466:                 $devalidate = 1;
                   17467:             }
                   17468:             if ($devalidate) {
                   17469:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   17470:             }
                   17471:         }
                   17472:     } else {
                   17473:         if ($uselink) {
                   17474:             $result = 1;
                   17475:         } else {
                   17476:             $result = 0;
                   17477:         }
                   17478:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   17479:     }
                   17480:     return $uselink;
                   17481: }
                   17482: 
1.112     bowersj2 17483: 1;
                   17484: __END__;
1.41      ng       17485: 

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