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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1279  ! raeburn     4: # $Id: loncommon.pm,v 1.1278 2017/03/21 23:19: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.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    74: use DateTime::TimeZone;
1.1241    raeburn    75: use DateTime::Locale;
1.1220    raeburn    76: use Encode();
1.1091    foxr       77: use Text::Aspell;
1.1094    raeburn    78: use Authen::Captcha;
                     79: use Captcha::reCAPTCHA;
1.1234    raeburn    80: use JSON::DWIW;
                     81: use LWP::UserAgent;
1.1174    raeburn    82: use Crypt::DES;
                     83: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   84: use MIME::Lite;
                     85: use MIME::Types;
1.117     www        86: 
1.517     raeburn    87: # ---------------------------------------------- Designs
                     88: use vars qw(%defaultdesign);
                     89: 
1.22      www        90: my $readit;
                     91: 
1.517     raeburn    92: 
1.157     matthew    93: ##
                     94: ## Global Variables
                     95: ##
1.46      matthew    96: 
1.643     foxr       97: 
                     98: # ----------------------------------------------- SSI with retries:
                     99: #
                    100: 
                    101: =pod
                    102: 
1.648     raeburn   103: =head1 Server Side include with retries:
1.643     foxr      104: 
                    105: =over 4
                    106: 
1.648     raeburn   107: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      108: 
                    109: Performs an ssi with some number of retries.  Retries continue either
                    110: until the result is ok or until the retry count supplied by the
                    111: caller is exhausted.  
                    112: 
                    113: Inputs:
1.648     raeburn   114: 
                    115: =over 4
                    116: 
1.643     foxr      117: resource   - Identifies the resource to insert.
1.648     raeburn   118: 
1.643     foxr      119: retries    - Count of the number of retries allowed.
1.648     raeburn   120: 
1.643     foxr      121: form       - Hash that identifies the rendering options.
                    122: 
1.648     raeburn   123: =back
                    124: 
                    125: Returns:
                    126: 
                    127: =over 4
                    128: 
1.643     foxr      129: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   130: 
1.643     foxr      131: response   - The response from the last attempt (which may or may not have been successful.
                    132: 
1.648     raeburn   133: =back
                    134: 
                    135: =back
                    136: 
1.643     foxr      137: =cut
                    138: 
                    139: sub ssi_with_retries {
                    140:     my ($resource, $retries, %form) = @_;
                    141: 
                    142: 
                    143:     my $ok = 0;			# True if we got a good response.
                    144:     my $content;
                    145:     my $response;
                    146: 
                    147:     # Try to get the ssi done. within the retries count:
                    148: 
                    149:     do {
                    150: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    151: 	$ok      = $response->is_success;
1.650     www       152:         if (!$ok) {
                    153:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    154:         }
1.643     foxr      155: 	$retries--;
                    156:     } while (!$ok && ($retries > 0));
                    157: 
                    158:     if (!$ok) {
                    159: 	$content = '';		# On error return an empty content.
                    160:     }
                    161:     return ($content, $response);
                    162: 
                    163: }
                    164: 
                    165: 
                    166: 
1.20      www       167: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  168: my %language;
1.124     www       169: my %supported_language;
1.1088    foxr      170: my %supported_codes;
1.1048    foxr      171: my %latex_language;		# For choosing hyphenation in <transl..>
                    172: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  173: my %cprtag;
1.192     taceyjo1  174: my %scprtag;
1.351     www       175: my %fe; my %fd; my %fm;
1.41      ng        176: my %category_extensions;
1.12      harris41  177: 
1.46      matthew   178: # ---------------------------------------------- Thesaurus variables
1.144     matthew   179: #
                    180: # %Keywords:
                    181: #      A hash used by &keyword to determine if a word is considered a keyword.
                    182: # $thesaurus_db_file 
                    183: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   184: 
                    185: my %Keywords;
                    186: my $thesaurus_db_file;
                    187: 
1.144     matthew   188: #
                    189: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    190: # thesaurus.tab, and filecategories.tab.
                    191: #
1.18      www       192: BEGIN {
1.46      matthew   193:     # Variable initialization
                    194:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    195:     #
1.22      www       196:     unless ($readit) {
1.12      harris41  197: # ------------------------------------------------------------------- languages
                    198:     {
1.158     raeburn   199:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    200:                                    '/language.tab';
                    201:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  202:             while (my $line = <$fh>) {
                    203:                 next if ($line=~/^\#/);
                    204:                 chomp($line);
1.1088    foxr      205:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   206:                 $language{$key}=$val.' - '.$enc;
                    207:                 if ($sup) {
                    208:                     $supported_language{$key}=$sup;
1.1088    foxr      209: 		    $supported_codes{$key}   = $code;
1.158     raeburn   210:                 }
1.1048    foxr      211: 		if ($latex) {
                    212: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      213: 		    $latex_language{$code} = $latex;
1.1048    foxr      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';
                    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';
                    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';
                    251:     if ( open (my $fh,"<$designfile") ) {
                    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';
                    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.1263    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';
                    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.999     www       433:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
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.793     raeburn   448:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       449:         var title = 'Student_Browser';
1.74      www       450:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    451:         options += ',width=700,height=600';
                    452:         stdeditbrowser = open(url,title,options,'1');
                    453:         stdeditbrowser.focus();
                    454:     }
1.824     bisitz    455: // ]]>
1.74      www       456: </script>
                    457: ENDSTDBRW
                    458: }
1.42      matthew   459: 
1.1003    www       460: sub resourcebrowser_javascript {
                    461:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       462:    return (<<'ENDRESBRW');
1.1003    www       463: <script type="text/javascript" language="Javascript">
                    464: // <![CDATA[
                    465:     var reseditbrowser;
1.1004    www       466:     function openresbrowser(formname,reslink) {
1.1005    www       467:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       468:         var title = 'Resource_Browser';
                    469:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       470:         options += ',width=700,height=500';
1.1004    www       471:         reseditbrowser = open(url,title,options,'1');
                    472:         reseditbrowser.focus();
1.1003    www       473:     }
                    474: // ]]>
                    475: </script>
1.1004    www       476: ENDRESBRW
1.1003    www       477: }
                    478: 
1.74      www       479: sub selectstudent_link {
1.999     www       480:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    481:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    482:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    483:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  484:    if ($env{'request.course.id'}) {  
1.302     albertel  485:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    486: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    487: 					'/'.$env{'request.course.sec'})) {
1.111     www       488: 	   return '';
                    489:        }
1.999     www       490:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   491:        if ($courseadvonly)  {
                    492:            $callargs .= ",'',1,1";
                    493:        }
                    494:        return '<span class="LC_nobreak">'.
                    495:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    496:               &mt('Select User').'</a></span>';
1.74      www       497:    }
1.258     albertel  498:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       499:        $callargs .= ",'',1"; 
1.793     raeburn   500:        return '<span class="LC_nobreak">'.
                    501:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    502:               &mt('Select User').'</a></span>';
1.111     www       503:    }
                    504:    return '';
1.91      www       505: }
                    506: 
1.1004    www       507: sub selectresource_link {
                    508:    my ($form,$reslink,$arg)=@_;
                    509:    
                    510:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    511:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    512:    unless ($env{'request.course.id'}) { return $arg; }
                    513:    return '<span class="LC_nobreak">'.
                    514:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    515:               $arg.'</a></span>';
                    516: }
                    517: 
                    518: 
                    519: 
1.653     raeburn   520: sub authorbrowser_javascript {
                    521:     return <<"ENDAUTHORBRW";
1.776     bisitz    522: <script type="text/javascript" language="JavaScript">
1.824     bisitz    523: // <![CDATA[
1.653     raeburn   524: var stdeditbrowser;
                    525: 
                    526: function openauthorbrowser(formname,udom) {
                    527:     var url = '/adm/pickauthor?';
                    528:     url += 'form='+formname+'&roledom='+udom;
                    529:     var title = 'Author_Browser';
                    530:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    531:     options += ',width=700,height=600';
                    532:     stdeditbrowser = open(url,title,options,'1');
                    533:     stdeditbrowser.focus();
                    534: }
                    535: 
1.824     bisitz    536: // ]]>
1.653     raeburn   537: </script>
                    538: ENDAUTHORBRW
                    539: }
                    540: 
1.91      www       541: sub coursebrowser_javascript {
1.1116    raeburn   542:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   543:         $credits_element,$instcode) = @_;
1.932     raeburn   544:     my $wintitle = 'Course_Browser';
1.931     raeburn   545:     if ($crstype eq 'Community') {
1.932     raeburn   546:         $wintitle = 'Community_Browser';
1.909     raeburn   547:     }
1.876     raeburn   548:     my $id_functions = &javascript_index_functions();
                    549:     my $output = '
1.776     bisitz    550: <script type="text/javascript" language="JavaScript">
1.824     bisitz    551: // <![CDATA[
1.468     raeburn   552:     var stdeditbrowser;'."\n";
1.876     raeburn   553: 
                    554:     $output .= <<"ENDSTDBRW";
1.909     raeburn   555:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       556:         var url = '/adm/pickcourse?';
1.895     raeburn   557:         var formid = getFormIdByName(formname);
1.876     raeburn   558:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  559:         if (domainfilter != null) {
                    560:            if (domainfilter != '') {
                    561:                url += 'domainfilter='+domainfilter+'&';
                    562: 	   }
                    563:         }
1.91      www       564:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  565: 	                            '&cdomelement='+udom+
                    566:                                     '&cnameelement='+desc;
1.468     raeburn   567:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   568:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   569:                 url += '&roleelement='+extra_element;
                    570:                 if (domainfilter == null || domainfilter == '') {
                    571:                     url += '&domainfilter='+extra_element;
                    572:                 }
1.234     raeburn   573:             }
1.468     raeburn   574:             else {
                    575:                 if (formname == 'portform') {
                    576:                     url += '&setroles='+extra_element;
1.800     raeburn   577:                 } else {
                    578:                     if (formname == 'rules') {
                    579:                         url += '&fixeddom='+extra_element; 
                    580:                     }
1.468     raeburn   581:                 }
                    582:             }     
1.230     raeburn   583:         }
1.909     raeburn   584:         if (type != null && type != '') {
                    585:             url += '&type='+type;
                    586:         }
                    587:         if (type_elem != null && type_elem != '') {
                    588:             url += '&typeelement='+type_elem;
                    589:         }
1.872     raeburn   590:         if (formname == 'ccrs') {
                    591:             var ownername = document.forms[formid].ccuname.value;
                    592:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   593:             url += '&cloner='+ownername+':'+ownerdom;
                    594:             if (type == 'Course') {
                    595:                 url += '&crscode='+document.forms[formid].crscode.value;
                    596:             }
1.1221    raeburn   597:         }
                    598:         if (formname == 'requestcrs') {
                    599:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   600:         }
1.293     raeburn   601:         if (multflag !=null && multflag != '') {
                    602:             url += '&multiple='+multflag;
                    603:         }
1.909     raeburn   604:         var title = '$wintitle';
1.91      www       605:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    606:         options += ',width=700,height=600';
                    607:         stdeditbrowser = open(url,title,options,'1');
                    608:         stdeditbrowser.focus();
                    609:     }
1.876     raeburn   610: $id_functions
                    611: ENDSTDBRW
1.1116    raeburn   612:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    613:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    614:                                       $credits_element);
1.876     raeburn   615:     }
                    616:     $output .= '
                    617: // ]]>
                    618: </script>';
                    619:     return $output;
                    620: }
                    621: 
                    622: sub javascript_index_functions {
                    623:     return <<"ENDJS";
                    624: 
                    625: function getFormIdByName(formname) {
                    626:     for (var i=0;i<document.forms.length;i++) {
                    627:         if (document.forms[i].name == formname) {
                    628:             return i;
                    629:         }
                    630:     }
                    631:     return -1;
                    632: }
                    633: 
                    634: function getIndexByName(formid,item) {
                    635:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    636:         if (document.forms[formid].elements[i].name == item) {
                    637:             return i;
                    638:         }
                    639:     }
                    640:     return -1;
                    641: }
1.468     raeburn   642: 
1.876     raeburn   643: function getDomainFromSelectbox(formname,udom) {
                    644:     var userdom;
                    645:     var formid = getFormIdByName(formname);
                    646:     if (formid > -1) {
                    647:         var domid = getIndexByName(formid,udom);
                    648:         if (domid > -1) {
                    649:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    650:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    651:             }
                    652:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    653:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   654:             }
                    655:         }
                    656:     }
1.876     raeburn   657:     return userdom;
                    658: }
                    659: 
                    660: ENDJS
1.468     raeburn   661: 
1.876     raeburn   662: }
                    663: 
1.1017    raeburn   664: sub javascript_array_indexof {
1.1018    raeburn   665:     return <<ENDJS;
1.1017    raeburn   666: <script type="text/javascript" language="JavaScript">
                    667: // <![CDATA[
                    668: 
                    669: if (!Array.prototype.indexOf) {
                    670:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    671:         "use strict";
                    672:         if (this === void 0 || this === null) {
                    673:             throw new TypeError();
                    674:         }
                    675:         var t = Object(this);
                    676:         var len = t.length >>> 0;
                    677:         if (len === 0) {
                    678:             return -1;
                    679:         }
                    680:         var n = 0;
                    681:         if (arguments.length > 0) {
                    682:             n = Number(arguments[1]);
1.1088    foxr      683:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   684:                 n = 0;
                    685:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    686:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    687:             }
                    688:         }
                    689:         if (n >= len) {
                    690:             return -1;
                    691:         }
                    692:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    693:         for (; k < len; k++) {
                    694:             if (k in t && t[k] === searchElement) {
                    695:                 return k;
                    696:             }
                    697:         }
                    698:         return -1;
                    699:     }
                    700: }
                    701: 
                    702: // ]]>
                    703: </script>
                    704: 
                    705: ENDJS
                    706: 
                    707: }
                    708: 
1.876     raeburn   709: sub userbrowser_javascript {
                    710:     my $id_functions = &javascript_index_functions();
                    711:     return <<"ENDUSERBRW";
                    712: 
1.888     raeburn   713: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   714:     var url = '/adm/pickuser?';
                    715:     var userdom = getDomainFromSelectbox(formname,udom);
                    716:     if (userdom != null) {
                    717:        if (userdom != '') {
                    718:            url += 'srchdom='+userdom+'&';
                    719:        }
                    720:     }
                    721:     url += 'form=' + formname + '&unameelement='+uname+
                    722:                                 '&udomelement='+udom+
                    723:                                 '&ulastelement='+ulast+
                    724:                                 '&ufirstelement='+ufirst+
                    725:                                 '&uemailelement='+uemail+
1.881     raeburn   726:                                 '&hideudomelement='+hideudom+
                    727:                                 '&coursedom='+crsdom;
1.888     raeburn   728:     if ((caller != null) && (caller != undefined)) {
                    729:         url += '&caller='+caller;
                    730:     }
1.876     raeburn   731:     var title = 'User_Browser';
                    732:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    733:     options += ',width=700,height=600';
                    734:     var stdeditbrowser = open(url,title,options,'1');
                    735:     stdeditbrowser.focus();
                    736: }
                    737: 
1.888     raeburn   738: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   739:     var formid = getFormIdByName(formname);
                    740:     if (formid > -1) {
1.888     raeburn   741:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   742:         var domid = getIndexByName(formid,udom);
                    743:         var hidedomid = getIndexByName(formid,origdom);
                    744:         if (hidedomid > -1) {
                    745:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   746:             var unameval = document.forms[formid].elements[unameid].value;
                    747:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    748:                 if (domid > -1) {
                    749:                     var slct = document.forms[formid].elements[domid];
                    750:                     if (slct.type == 'select-one') {
                    751:                         var i;
                    752:                         for (i=0;i<slct.length;i++) {
                    753:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    754:                         }
                    755:                     }
                    756:                     if (slct.type == 'hidden') {
                    757:                         slct.value = fixeddom;
1.876     raeburn   758:                     }
                    759:                 }
1.468     raeburn   760:             }
                    761:         }
                    762:     }
1.876     raeburn   763:     return;
                    764: }
                    765: 
                    766: $id_functions
                    767: ENDUSERBRW
1.468     raeburn   768: }
                    769: 
                    770: sub setsec_javascript {
1.1116    raeburn   771:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   772:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    773:         $communityrolestr);
                    774:     if ($role_element ne '') {
                    775:         my @allroles = ('st','ta','ep','in','ad');
                    776:         foreach my $crstype ('Course','Community') {
                    777:             if ($crstype eq 'Community') {
                    778:                 foreach my $role (@allroles) {
                    779:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    780:                 }
                    781:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    782:             } else {
                    783:                 foreach my $role (@allroles) {
                    784:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    785:                 }
                    786:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    787:             }
                    788:         }
                    789:         $rolestr = '"'.join('","',@allroles).'"';
                    790:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    791:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    792:     }
1.468     raeburn   793:     my $setsections = qq|
                    794: function setSect(sectionlist) {
1.629     raeburn   795:     var sectionsArray = new Array();
                    796:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    797:         sectionsArray = sectionlist.split(",");
                    798:     }
1.468     raeburn   799:     var numSections = sectionsArray.length;
                    800:     document.$formname.$sec_element.length = 0;
                    801:     if (numSections == 0) {
                    802:         document.$formname.$sec_element.multiple=false;
                    803:         document.$formname.$sec_element.size=1;
                    804:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    805:     } else {
                    806:         if (numSections == 1) {
                    807:             document.$formname.$sec_element.multiple=false;
                    808:             document.$formname.$sec_element.size=1;
                    809:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    810:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    811:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    812:         } else {
                    813:             for (var i=0; i<numSections; i++) {
                    814:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    815:             }
                    816:             document.$formname.$sec_element.multiple=true
                    817:             if (numSections < 3) {
                    818:                 document.$formname.$sec_element.size=numSections;
                    819:             } else {
                    820:                 document.$formname.$sec_element.size=3;
                    821:             }
                    822:             document.$formname.$sec_element.options[0].selected = false
                    823:         }
                    824:     }
1.91      www       825: }
1.905     raeburn   826: 
                    827: function setRole(crstype) {
1.468     raeburn   828: |;
1.905     raeburn   829:     if ($role_element eq '') {
                    830:         $setsections .= '    return;
                    831: }
                    832: ';
                    833:     } else {
                    834:         $setsections .= qq|
                    835:     var elementLength = document.$formname.$role_element.length;
                    836:     var allroles = Array($rolestr);
                    837:     var courserolenames = Array($courserolestr);
                    838:     var communityrolenames = Array($communityrolestr);
                    839:     if (elementLength != undefined) {
                    840:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    841:             if (crstype == 'Course') {
                    842:                 return;
                    843:             } else {
                    844:                 allroles[5] = 'co';
                    845:                 for (var i=0; i<6; i++) {
                    846:                     document.$formname.$role_element.options[i].value = allroles[i];
                    847:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    848:                 }
                    849:             }
                    850:         } else {
                    851:             if (crstype == 'Community') {
                    852:                 return;
                    853:             } else {
                    854:                 allroles[5] = 'cc';
                    855:                 for (var i=0; i<6; i++) {
                    856:                     document.$formname.$role_element.options[i].value = allroles[i];
                    857:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    858:                 }
                    859:             }
                    860:         }
                    861:     }
                    862:     return;
                    863: }
                    864: |;
                    865:     }
1.1116    raeburn   866:     if ($credits_element) {
                    867:         $setsections .= qq|
                    868: function setCredits(defaultcredits) {
                    869:     document.$formname.$credits_element.value = defaultcredits;
                    870:     return;
                    871: }
                    872: |;
                    873:     }
1.468     raeburn   874:     return $setsections;
                    875: }
                    876: 
1.91      www       877: sub selectcourse_link {
1.909     raeburn   878:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    879:        $typeelement) = @_;
                    880:    my $type = $selecttype;
1.871     raeburn   881:    my $linktext = &mt('Select Course');
                    882:    if ($selecttype eq 'Community') {
1.909     raeburn   883:        $linktext = &mt('Select Community');
1.1239    raeburn   884:    } elsif ($selecttype eq 'Placement') {
                    885:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   886:    } elsif ($selecttype eq 'Course/Community') {
                    887:        $linktext = &mt('Select Course/Community');
1.909     raeburn   888:        $type = '';
1.1019    raeburn   889:    } elsif ($selecttype eq 'Select') {
                    890:        $linktext = &mt('Select');
                    891:        $type = '';
1.871     raeburn   892:    }
1.787     bisitz    893:    return '<span class="LC_nobreak">'
                    894:          ."<a href='"
                    895:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    896:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   897:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   898:          ."'>".$linktext.'</a>'
1.787     bisitz    899:          .'</span>';
1.74      www       900: }
1.42      matthew   901: 
1.653     raeburn   902: sub selectauthor_link {
                    903:    my ($form,$udom)=@_;
                    904:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    905:           &mt('Select Author').'</a>';
                    906: }
                    907: 
1.876     raeburn   908: sub selectuser_link {
1.881     raeburn   909:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   910:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   911:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   912:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   913:            ');">'.$linktext.'</a>';
1.876     raeburn   914: }
                    915: 
1.273     raeburn   916: sub check_uncheck_jscript {
                    917:     my $jscript = <<"ENDSCRT";
                    918: function checkAll(field) {
                    919:     if (field.length > 0) {
                    920:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   921:             if (!field[i].disabled) { 
                    922:                 field[i].checked = true;
                    923:             }
1.273     raeburn   924:         }
                    925:     } else {
1.1093    raeburn   926:         if (!field.disabled) { 
                    927:             field.checked = true;
                    928:         }
1.273     raeburn   929:     }
                    930: }
                    931:  
                    932: function uncheckAll(field) {
                    933:     if (field.length > 0) {
                    934:         for (i = 0; i < field.length; i++) {
                    935:             field[i].checked = false ;
1.543     albertel  936:         }
                    937:     } else {
1.273     raeburn   938:         field.checked = false ;
                    939:     }
                    940: }
                    941: ENDSCRT
                    942:     return $jscript;
                    943: }
                    944: 
1.656     www       945: sub select_timezone {
1.1256    raeburn   946:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    947:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   948:    if ($includeempty) {
                    949:        $output .= '<option value=""';
                    950:        if (($selected eq '') || ($selected eq 'local')) {
                    951:            $output .= ' selected="selected" ';
                    952:        }
                    953:        $output .= '> </option>';
                    954:    }
1.657     raeburn   955:    my @timezones = DateTime::TimeZone->all_names;
                    956:    foreach my $tzone (@timezones) {
                    957:        $output.= '<option value="'.$tzone.'"';
                    958:        if ($tzone eq $selected) {
                    959:            $output.=' selected="selected"';
                    960:        }
                    961:        $output.=">$tzone</option>\n";
1.656     www       962:    }
                    963:    $output.="</select>";
                    964:    return $output;
                    965: }
1.273     raeburn   966: 
1.687     raeburn   967: sub select_datelocale {
1.1256    raeburn   968:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    969:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   970:     if ($includeempty) {
                    971:         $output .= '<option value=""';
                    972:         if ($selected eq '') {
                    973:             $output .= ' selected="selected" ';
                    974:         }
                    975:         $output .= '> </option>';
                    976:     }
1.1241    raeburn   977:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   978:     my (@possibles,%locale_names);
1.1241    raeburn   979:     my @locales = DateTime::Locale->ids();
                    980:     foreach my $id (@locales) {
                    981:         if ($id ne '') {
                    982:             my ($en_terr,$native_terr);
                    983:             my $loc = DateTime::Locale->load($id);
                    984:             if (ref($loc)) {
                    985:                 $en_terr = $loc->name();
                    986:                 $native_terr = $loc->native_name();
1.687     raeburn   987:                 if (grep(/^en$/,@languages) || !@languages) {
                    988:                     if ($en_terr ne '') {
                    989:                         $locale_names{$id} = '('.$en_terr.')';
                    990:                     } elsif ($native_terr ne '') {
                    991:                         $locale_names{$id} = $native_terr;
                    992:                     }
                    993:                 } else {
                    994:                     if ($native_terr ne '') {
                    995:                         $locale_names{$id} = $native_terr.' ';
                    996:                     } elsif ($en_terr ne '') {
                    997:                         $locale_names{$id} = '('.$en_terr.')';
                    998:                     }
                    999:                 }
1.1220    raeburn  1000:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1001:                 push(@possibles,$id);
                   1002:             } 
1.687     raeburn  1003:         }
                   1004:     }
                   1005:     foreach my $item (sort(@possibles)) {
                   1006:         $output.= '<option value="'.$item.'"';
                   1007:         if ($item eq $selected) {
                   1008:             $output.=' selected="selected"';
                   1009:         }
                   1010:         $output.=">$item";
                   1011:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1012:             $output.='  '.$locale_names{$item};
1.687     raeburn  1013:         }
                   1014:         $output.="</option>\n";
                   1015:     }
                   1016:     $output.="</select>";
                   1017:     return $output;
                   1018: }
                   1019: 
1.792     raeburn  1020: sub select_language {
1.1256    raeburn  1021:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1022:     my %langchoices;
                   1023:     if ($includeempty) {
1.1117    raeburn  1024:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1025:     }
                   1026:     foreach my $id (&languageids()) {
                   1027:         my $code = &supportedlanguagecode($id);
                   1028:         if ($code) {
                   1029:             $langchoices{$code} = &plainlanguagedescription($id);
                   1030:         }
                   1031:     }
1.1117    raeburn  1032:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1033:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1034: }
                   1035: 
1.42      matthew  1036: =pod
1.36      matthew  1037: 
1.1088    foxr     1038: 
                   1039: =item * &list_languages()
                   1040: 
                   1041: Returns an array reference that is suitable for use in language prompters.
                   1042: Each array element is itself a two element array.  The first element
                   1043: is the language code.  The second element a descsriptiuon of the 
                   1044: language itself.  This is suitable for use in e.g.
                   1045: &Apache::edit::select_arg (once dereferenced that is).
                   1046: 
                   1047: =cut 
                   1048: 
                   1049: sub list_languages {
                   1050:     my @lang_choices;
                   1051: 
                   1052:     foreach my $id (&languageids()) {
                   1053: 	my $code = &supportedlanguagecode($id);
                   1054: 	if ($code) {
                   1055: 	    my $selector    = $supported_codes{$id};
                   1056: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1057: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1058: 	}
                   1059:     }
                   1060:     return \@lang_choices;
                   1061: }
                   1062: 
                   1063: =pod
                   1064: 
1.648     raeburn  1065: =item * &linked_select_forms(...)
1.36      matthew  1066: 
                   1067: linked_select_forms returns a string containing a <script></script> block
                   1068: and html for two <select> menus.  The select menus will be linked in that
                   1069: changing the value of the first menu will result in new values being placed
                   1070: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1071: order unless a defined order is provided.
1.36      matthew  1072: 
                   1073: linked_select_forms takes the following ordered inputs:
                   1074: 
                   1075: =over 4
                   1076: 
1.112     bowersj2 1077: =item * $formname, the name of the <form> tag
1.36      matthew  1078: 
1.112     bowersj2 1079: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1080: 
1.112     bowersj2 1081: =item * $firstdefault, the default value for the first menu
1.36      matthew  1082: 
1.112     bowersj2 1083: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1084: 
1.112     bowersj2 1085: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1086: 
1.112     bowersj2 1087: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1088: 
1.609     raeburn  1089: =item * $menuorder, the order of values in the first menu
                   1090: 
1.1115    raeburn  1091: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1092:         event for the first <select> tag
                   1093: 
                   1094: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1095:         event for the second <select> tag
                   1096: 
1.1245    raeburn  1097: =item * $suffix, to differentiate separate uses of select2data javascript
                   1098:         objects in a page.
                   1099: 
1.41      ng       1100: =back 
                   1101: 
1.36      matthew  1102: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1103: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1104: values for the first select menu.  The text that coincides with the 
1.41      ng       1105: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1106: and text for the second menu are given in the hash pointed to by 
                   1107: $menu{$choice1}->{'select2'}.  
                   1108: 
1.112     bowersj2 1109:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1110:                        default => "B3",
                   1111:                        select2 => { 
                   1112:                            B1 => "Choice B1",
                   1113:                            B2 => "Choice B2",
                   1114:                            B3 => "Choice B3",
                   1115:                            B4 => "Choice B4"
1.609     raeburn  1116:                            },
                   1117:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1118:                    },
                   1119:                A2 => { text =>"Choice A2" ,
                   1120:                        default => "C2",
                   1121:                        select2 => { 
                   1122:                            C1 => "Choice C1",
                   1123:                            C2 => "Choice C2",
                   1124:                            C3 => "Choice C3"
1.609     raeburn  1125:                            },
                   1126:                        order => ['C2','C1','C3'],
1.112     bowersj2 1127:                    },
                   1128:                A3 => { text =>"Choice A3" ,
                   1129:                        default => "D6",
                   1130:                        select2 => { 
                   1131:                            D1 => "Choice D1",
                   1132:                            D2 => "Choice D2",
                   1133:                            D3 => "Choice D3",
                   1134:                            D4 => "Choice D4",
                   1135:                            D5 => "Choice D5",
                   1136:                            D6 => "Choice D6",
                   1137:                            D7 => "Choice D7"
1.609     raeburn  1138:                            },
                   1139:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1140:                    }
                   1141:                );
1.36      matthew  1142: 
                   1143: =cut
                   1144: 
                   1145: sub linked_select_forms {
                   1146:     my ($formname,
                   1147:         $middletext,
                   1148:         $firstdefault,
                   1149:         $firstselectname,
                   1150:         $secondselectname, 
1.609     raeburn  1151:         $hashref,
                   1152:         $menuorder,
1.1115    raeburn  1153:         $onchangefirst,
1.1245    raeburn  1154:         $onchangesecond,
                   1155:         $suffix
1.36      matthew  1156:         ) = @_;
                   1157:     my $second = "document.$formname.$secondselectname";
                   1158:     my $first = "document.$formname.$firstselectname";
                   1159:     # output the javascript to do the changing
                   1160:     my $result = '';
1.776     bisitz   1161:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1162:     $result.="// <![CDATA[\n";
1.1245    raeburn  1163:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1164:     $" = '","';
                   1165:     my $debug = '';
                   1166:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1167:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1168:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1169:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1170:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1171:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1172:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1173:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1174:         }
1.36      matthew  1175:         $result.="\"@s2values\");\n";
1.1245    raeburn  1176:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1177:         my @s2texts;
                   1178:         foreach my $value (@s2values) {
1.1263    raeburn  1179:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1180:         }
                   1181:         $result.="\"@s2texts\");\n";
                   1182:     }
                   1183:     $"=' ';
                   1184:     $result.= <<"END";
                   1185: 
1.1245    raeburn  1186: function select1${suffix}_changed() {
1.36      matthew  1187:     // Determine new choice
1.1245    raeburn  1188:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1189:     // update select2
1.1245    raeburn  1190:     var values     = select2data${suffix}[newvalue].values;
                   1191:     var texts      = select2data${suffix}[newvalue].texts;
                   1192:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1193:     var i;
                   1194:     // out with the old
1.1245    raeburn  1195:     $second.options.length = 0;
                   1196:     // in with the new
1.36      matthew  1197:     for (i=0;i<values.length; i++) {
                   1198:         $second.options[i] = new Option(values[i]);
1.143     matthew  1199:         $second.options[i].value = values[i];
1.36      matthew  1200:         $second.options[i].text = texts[i];
                   1201:         if (values[i] == select2def) {
                   1202:             $second.options[i].selected = true;
                   1203:         }
                   1204:     }
                   1205: }
1.824     bisitz   1206: // ]]>
1.36      matthew  1207: </script>
                   1208: END
                   1209:     # output the initial values for the selection lists
1.1245    raeburn  1210:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1211:     my @order = sort(keys(%{$hashref}));
                   1212:     if (ref($menuorder) eq 'ARRAY') {
                   1213:         @order = @{$menuorder};
                   1214:     }
                   1215:     foreach my $value (@order) {
1.36      matthew  1216:         $result.="    <option value=\"$value\" ";
1.253     albertel 1217:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1218:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1219:     }
                   1220:     $result .= "</select>\n";
                   1221:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1222:     $result .= $middletext;
1.1115    raeburn  1223:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1224:     if ($onchangesecond) {
                   1225:         $result .= ' onchange="'.$onchangesecond.'"';
                   1226:     }
                   1227:     $result .= ">\n";
1.36      matthew  1228:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1229:     
                   1230:     my @secondorder = sort(keys(%select2));
                   1231:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1232:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1233:     }
                   1234:     foreach my $value (@secondorder) {
1.36      matthew  1235:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1236:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1237:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1238:     }
                   1239:     $result .= "</select>\n";
                   1240:     #    return $debug;
                   1241:     return $result;
                   1242: }   #  end of sub linked_select_forms {
                   1243: 
1.45      matthew  1244: =pod
1.44      bowersj2 1245: 
1.973     raeburn  1246: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1247: 
1.112     bowersj2 1248: Returns a string corresponding to an HTML link to the given help
                   1249: $topic, where $topic corresponds to the name of a .tex file in
                   1250: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1251: spaces. 
                   1252: 
                   1253: $text will optionally be linked to the same topic, allowing you to
                   1254: link text in addition to the graphic. If you do not want to link
                   1255: text, but wish to specify one of the later parameters, pass an
                   1256: empty string. 
                   1257: 
                   1258: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1259: the link will not open a new window. If false, the link will open
                   1260: a new window using Javascript. (Default is false.) 
                   1261: 
                   1262: $width and $height are optional numerical parameters that will
                   1263: override the width and height of the popped up window, which may
1.973     raeburn  1264: be useful for certain help topics with big pictures included.
                   1265: 
                   1266: $imgid is the id of the img tag used for the help icon. This may be
                   1267: used in a javascript call to switch the image src.  See 
                   1268: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1269: 
                   1270: =cut
                   1271: 
                   1272: sub help_open_topic {
1.973     raeburn  1273:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1274:     $text = "" if (not defined $text);
1.44      bowersj2 1275:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1276:     $width = 500 if (not defined $width);
1.44      bowersj2 1277:     $height = 400 if (not defined $height);
                   1278:     my $filename = $topic;
                   1279:     $filename =~ s/ /_/g;
                   1280: 
1.48      bowersj2 1281:     my $template = "";
                   1282:     my $link;
1.572     banghart 1283:     
1.159     www      1284:     $topic=~s/\W/\_/g;
1.44      bowersj2 1285: 
1.572     banghart 1286:     if (!$stayOnPage) {
1.1033    www      1287: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1288:     } elsif ($stayOnPage eq 'popup') {
                   1289:         $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 1290:     } else {
1.48      bowersj2 1291: 	$link = "/adm/help/${filename}.hlp";
                   1292:     }
                   1293: 
                   1294:     # Add the text
1.755     neumanie 1295:     if ($text ne "") {	
1.763     bisitz   1296: 	$template.='<span class="LC_help_open_topic">'
                   1297:                   .'<a target="_top" href="'.$link.'">'
                   1298:                   .$text.'</a>';
1.48      bowersj2 1299:     }
                   1300: 
1.763     bisitz   1301:     # (Always) Add the graphic
1.179     matthew  1302:     my $title = &mt('Online Help');
1.667     raeburn  1303:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1304:     if ($imgid ne '') {
                   1305:         $imgid = ' id="'.$imgid.'"';
                   1306:     }
1.763     bisitz   1307:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1308:               .'<img src="'.$helpicon.'" border="0"'
                   1309:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1310:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1311:               .' /></a>';
                   1312:     if ($text ne "") {	
                   1313:         $template.='</span>';
                   1314:     }
1.44      bowersj2 1315:     return $template;
                   1316: 
1.106     bowersj2 1317: }
                   1318: 
                   1319: # This is a quicky function for Latex cheatsheet editing, since it 
                   1320: # appears in at least four places
                   1321: sub helpLatexCheatsheet {
1.1037    www      1322:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1323:     my $out;
1.106     bowersj2 1324:     my $addOther = '';
1.732     raeburn  1325:     if ($topic) {
1.1037    www      1326: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1327:     }
                   1328:     $out = '<span>' # Start cheatsheet
                   1329: 	  .$addOther
                   1330:           .'<span>'
1.1037    www      1331: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1332: 	  .'</span> <span>'
1.1037    www      1333: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1334: 	  .'</span>';
1.732     raeburn  1335:     unless ($not_author) {
1.1186    kruse    1336:         $out .= '<span>'
                   1337:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1338:                .'</span> <span>'
                   1339:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1340: 	       .'</span>';
1.732     raeburn  1341:     }
1.763     bisitz   1342:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1343:     return $out;
1.172     www      1344: }
                   1345: 
1.430     albertel 1346: sub general_help {
                   1347:     my $helptopic='Student_Intro';
                   1348:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1349: 	$helptopic='Authoring_Intro';
1.907     raeburn  1350:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1351: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1352:     } elsif ($env{'request.role'}=~/^dc/) {
                   1353:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1354:     }
                   1355:     return $helptopic;
                   1356: }
                   1357: 
                   1358: sub update_help_link {
                   1359:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1360:     my $origurl = $ENV{'REQUEST_URI'};
                   1361:     $origurl=~s|^/~|/priv/|;
                   1362:     my $timestamp = time;
                   1363:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1364:         $$datum = &escape($$datum);
                   1365:     }
                   1366: 
                   1367:     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";
                   1368:     my $output .= <<"ENDOUTPUT";
                   1369: <script type="text/javascript">
1.824     bisitz   1370: // <![CDATA[
1.430     albertel 1371: banner_link = '$banner_link';
1.824     bisitz   1372: // ]]>
1.430     albertel 1373: </script>
                   1374: ENDOUTPUT
                   1375:     return $output;
                   1376: }
                   1377: 
                   1378: # now just updates the help link and generates a blue icon
1.193     raeburn  1379: sub help_open_menu {
1.430     albertel 1380:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1381: 	= @_;    
1.949     droeschl 1382:     $stayOnPage = 1;
1.430     albertel 1383:     my $output;
                   1384:     if ($component_help) {
                   1385: 	if (!$text) {
                   1386: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1387: 				       $width,$height);
                   1388: 	} else {
                   1389: 	    my $help_text;
                   1390: 	    $help_text=&unescape($topic);
                   1391: 	    $output='<table><tr><td>'.
                   1392: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1393: 				 $width,$height).'</td></tr></table>';
                   1394: 	}
                   1395:     }
                   1396:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1397:     return $output.$banner_link;
                   1398: }
                   1399: 
                   1400: sub top_nav_help {
                   1401:     my ($text) = @_;
1.436     albertel 1402:     $text = &mt($text);
1.949     droeschl 1403:     my $stay_on_page = 1;
                   1404: 
1.1168    raeburn  1405:     my ($link,$banner_link);
                   1406:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1407:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1408: 	                         : "javascript:helpMenu('open')";
                   1409:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1410:     }
1.201     raeburn  1411:     my $title = &mt('Get help');
1.1168    raeburn  1412:     if ($link) {
                   1413:         return <<"END";
1.436     albertel 1414: $banner_link
1.1159    raeburn  1415: <a href="$link" title="$title">$text</a>
1.436     albertel 1416: END
1.1168    raeburn  1417:     } else {
                   1418:         return '&nbsp;'.$text.'&nbsp;';
                   1419:     }
1.436     albertel 1420: }
                   1421: 
                   1422: sub help_menu_js {
1.1154    raeburn  1423:     my ($httphost) = @_;
1.949     droeschl 1424:     my $stayOnPage = 1;
1.436     albertel 1425:     my $width = 620;
                   1426:     my $height = 600;
1.430     albertel 1427:     my $helptopic=&general_help();
1.1154    raeburn  1428:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1429:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1430:     my $start_page =
                   1431:         &Apache::loncommon::start_page('Help Menu', undef,
                   1432: 				       {'frameset'    => 1,
                   1433: 					'js_ready'    => 1,
1.1154    raeburn  1434:                                         'use_absolute' => $httphost,
1.331     albertel 1435: 					'add_entries' => {
1.1168    raeburn  1436: 					    'border' => '0', 
1.579     raeburn  1437: 					    'rows'   => "110,*",},});
1.331     albertel 1438:     my $end_page =
                   1439:         &Apache::loncommon::end_page({'frameset' => 1,
                   1440: 				      'js_ready' => 1,});
                   1441: 
1.436     albertel 1442:     my $template .= <<"ENDTEMPLATE";
                   1443: <script type="text/javascript">
1.877     bisitz   1444: // <![CDATA[
1.253     albertel 1445: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1446: var banner_link = '';
1.243     raeburn  1447: function helpMenu(target) {
                   1448:     var caller = this;
                   1449:     if (target == 'open') {
                   1450:         var newWindow = null;
                   1451:         try {
1.262     albertel 1452:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1453:         }
                   1454:         catch(error) {
                   1455:             writeHelp(caller);
                   1456:             return;
                   1457:         }
                   1458:         if (newWindow) {
                   1459:             caller = newWindow;
                   1460:         }
1.193     raeburn  1461:     }
1.243     raeburn  1462:     writeHelp(caller);
                   1463:     return;
                   1464: }
                   1465: function writeHelp(caller) {
1.1168    raeburn  1466:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1467:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1468:     caller.document.close();
                   1469:     caller.focus();
1.193     raeburn  1470: }
1.877     bisitz   1471: // END LON-CAPA Internal -->
1.253     albertel 1472: // ]]>
1.436     albertel 1473: </script>
1.193     raeburn  1474: ENDTEMPLATE
                   1475:     return $template;
                   1476: }
                   1477: 
1.172     www      1478: sub help_open_bug {
                   1479:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1480:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1481:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1482:     $text = "" if (not defined $text);
                   1483: 	$stayOnPage=1;
1.184     albertel 1484:     $width = 600 if (not defined $width);
                   1485:     $height = 600 if (not defined $height);
1.172     www      1486: 
                   1487:     $topic=~s/\W+/\+/g;
                   1488:     my $link='';
                   1489:     my $template='';
1.379     albertel 1490:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1491: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1492:     if (!$stayOnPage)
                   1493:     {
                   1494: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1495:     }
                   1496:     else
                   1497:     {
                   1498: 	$link = $url;
                   1499:     }
                   1500:     # Add the text
                   1501:     if ($text ne "")
                   1502:     {
                   1503: 	$template .= 
                   1504:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1505:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1506:     }
                   1507: 
                   1508:     # Add the graphic
1.179     matthew  1509:     my $title = &mt('Report a Bug');
1.215     albertel 1510:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1511:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1512:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1513: ENDTEMPLATE
                   1514:     if ($text ne '') { $template.='</td></tr></table>' };
                   1515:     return $template;
                   1516: 
                   1517: }
                   1518: 
                   1519: sub help_open_faq {
                   1520:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1521:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1522:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1523:     $text = "" if (not defined $text);
                   1524: 	$stayOnPage=1;
                   1525:     $width = 350 if (not defined $width);
                   1526:     $height = 400 if (not defined $height);
                   1527: 
                   1528:     $topic=~s/\W+/\+/g;
                   1529:     my $link='';
                   1530:     my $template='';
                   1531:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1532:     if (!$stayOnPage)
                   1533:     {
                   1534: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1535:     }
                   1536:     else
                   1537:     {
                   1538: 	$link = $url;
                   1539:     }
                   1540: 
                   1541:     # Add the text
                   1542:     if ($text ne "")
                   1543:     {
                   1544: 	$template .= 
1.173     www      1545:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1546:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1547:     }
                   1548: 
                   1549:     # Add the graphic
1.179     matthew  1550:     my $title = &mt('View the FAQ');
1.215     albertel 1551:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1552:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1553:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1554: ENDTEMPLATE
                   1555:     if ($text ne '') { $template.='</td></tr></table>' };
                   1556:     return $template;
                   1557: 
1.44      bowersj2 1558: }
1.37      matthew  1559: 
1.180     matthew  1560: ###############################################################
                   1561: ###############################################################
                   1562: 
1.45      matthew  1563: =pod
                   1564: 
1.648     raeburn  1565: =item * &change_content_javascript():
1.256     matthew  1566: 
                   1567: This and the next function allow you to create small sections of an
                   1568: otherwise static HTML page that you can update on the fly with
                   1569: Javascript, even in Netscape 4.
                   1570: 
                   1571: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1572: must be written to the HTML page once. It will prove the Javascript
                   1573: function "change(name, content)". Calling the change function with the
                   1574: name of the section 
                   1575: you want to update, matching the name passed to C<changable_area>, and
                   1576: the new content you want to put in there, will put the content into
                   1577: that area.
                   1578: 
                   1579: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1580: to contain room for the original contents. You need to "make space"
                   1581: for whatever changes you wish to make, and be B<sure> to check your
                   1582: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1583: it's adequate for updating a one-line status display, but little more.
                   1584: This script will set the space to 100% width, so you only need to
                   1585: worry about height in Netscape 4.
                   1586: 
                   1587: Modern browsers are much less limiting, and if you can commit to the
                   1588: user not using Netscape 4, this feature may be used freely with
                   1589: pretty much any HTML.
                   1590: 
                   1591: =cut
                   1592: 
                   1593: sub change_content_javascript {
                   1594:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1595:     if ($env{'browser.type'} eq 'netscape' &&
                   1596: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1597: 	return (<<NETSCAPE4);
                   1598: 	function change(name, content) {
                   1599: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1600: 	    doc.open();
                   1601: 	    doc.write(content);
                   1602: 	    doc.close();
                   1603: 	}
                   1604: NETSCAPE4
                   1605:     } else {
                   1606: 	# Otherwise, we need to use semi-standards-compliant code
                   1607: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1608: 	# is really scary, and every useful browser supports it
                   1609: 	return (<<DOMBASED);
                   1610: 	function change(name, content) {
                   1611: 	    element = document.getElementById(name);
                   1612: 	    element.innerHTML = content;
                   1613: 	}
                   1614: DOMBASED
                   1615:     }
                   1616: }
                   1617: 
                   1618: =pod
                   1619: 
1.648     raeburn  1620: =item * &changable_area($name,$origContent):
1.256     matthew  1621: 
                   1622: This provides a "changable area" that can be modified on the fly via
                   1623: the Javascript code provided in C<change_content_javascript>. $name is
                   1624: the name you will use to reference the area later; do not repeat the
                   1625: same name on a given HTML page more then once. $origContent is what
                   1626: the area will originally contain, which can be left blank.
                   1627: 
                   1628: =cut
                   1629: 
                   1630: sub changable_area {
                   1631:     my ($name, $origContent) = @_;
                   1632: 
1.258     albertel 1633:     if ($env{'browser.type'} eq 'netscape' &&
                   1634: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1635: 	# If this is netscape 4, we need to use the Layer tag
                   1636: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1637:     } else {
                   1638: 	return "<span id='$name'>$origContent</span>";
                   1639:     }
                   1640: }
                   1641: 
                   1642: =pod
                   1643: 
1.648     raeburn  1644: =item * &viewport_geometry_js 
1.590     raeburn  1645: 
                   1646: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1647: 
                   1648: =cut
                   1649: 
                   1650: 
                   1651: sub viewport_geometry_js { 
                   1652:     return <<"GEOMETRY";
                   1653: var Geometry = {};
                   1654: function init_geometry() {
                   1655:     if (Geometry.init) { return };
                   1656:     Geometry.init=1;
                   1657:     if (window.innerHeight) {
                   1658:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1659:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1660:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1661:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1662:     }
                   1663:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1664:         Geometry.getViewportHeight =
                   1665:             function() { return document.documentElement.clientHeight; };
                   1666:         Geometry.getViewportWidth =
                   1667:             function() { return document.documentElement.clientWidth; };
                   1668: 
                   1669:         Geometry.getHorizontalScroll =
                   1670:             function() { return document.documentElement.scrollLeft; };
                   1671:         Geometry.getVerticalScroll =
                   1672:             function() { return document.documentElement.scrollTop; };
                   1673:     }
                   1674:     else if (document.body.clientHeight) {
                   1675:         Geometry.getViewportHeight =
                   1676:             function() { return document.body.clientHeight; };
                   1677:         Geometry.getViewportWidth =
                   1678:             function() { return document.body.clientWidth; };
                   1679:         Geometry.getHorizontalScroll =
                   1680:             function() { return document.body.scrollLeft; };
                   1681:         Geometry.getVerticalScroll =
                   1682:             function() { return document.body.scrollTop; };
                   1683:     }
                   1684: }
                   1685: 
                   1686: GEOMETRY
                   1687: }
                   1688: 
                   1689: =pod
                   1690: 
1.648     raeburn  1691: =item * &viewport_size_js()
1.590     raeburn  1692: 
                   1693: 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. 
                   1694: 
                   1695: =cut
                   1696: 
                   1697: sub viewport_size_js {
                   1698:     my $geometry = &viewport_geometry_js();
                   1699:     return <<"DIMS";
                   1700: 
                   1701: $geometry
                   1702: 
                   1703: function getViewportDims(width,height) {
                   1704:     init_geometry();
                   1705:     width.value = Geometry.getViewportWidth();
                   1706:     height.value = Geometry.getViewportHeight();
                   1707:     return;
                   1708: }
                   1709: 
                   1710: DIMS
                   1711: }
                   1712: 
                   1713: =pod
                   1714: 
1.648     raeburn  1715: =item * &resize_textarea_js()
1.565     albertel 1716: 
                   1717: emits the needed javascript to resize a textarea to be as big as possible
                   1718: 
                   1719: creates a function resize_textrea that takes two IDs first should be
                   1720: the id of the element to resize, second should be the id of a div that
                   1721: surrounds everything that comes after the textarea, this routine needs
                   1722: to be attached to the <body> for the onload and onresize events.
                   1723: 
1.648     raeburn  1724: =back
1.565     albertel 1725: 
                   1726: =cut
                   1727: 
                   1728: sub resize_textarea_js {
1.590     raeburn  1729:     my $geometry = &viewport_geometry_js();
1.565     albertel 1730:     return <<"RESIZE";
                   1731:     <script type="text/javascript">
1.824     bisitz   1732: // <![CDATA[
1.590     raeburn  1733: $geometry
1.565     albertel 1734: 
1.588     albertel 1735: function getX(element) {
                   1736:     var x = 0;
                   1737:     while (element) {
                   1738: 	x += element.offsetLeft;
                   1739: 	element = element.offsetParent;
                   1740:     }
                   1741:     return x;
                   1742: }
                   1743: function getY(element) {
                   1744:     var y = 0;
                   1745:     while (element) {
                   1746: 	y += element.offsetTop;
                   1747: 	element = element.offsetParent;
                   1748:     }
                   1749:     return y;
                   1750: }
                   1751: 
                   1752: 
1.565     albertel 1753: function resize_textarea(textarea_id,bottom_id) {
                   1754:     init_geometry();
                   1755:     var textarea        = document.getElementById(textarea_id);
                   1756:     //alert(textarea);
                   1757: 
1.588     albertel 1758:     var textarea_top    = getY(textarea);
1.565     albertel 1759:     var textarea_height = textarea.offsetHeight;
                   1760:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1761:     var bottom_top      = getY(bottom);
1.565     albertel 1762:     var bottom_height   = bottom.offsetHeight;
                   1763:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1764:     var fudge           = 23;
1.565     albertel 1765:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1766:     if (new_height < 300) {
                   1767: 	new_height = 300;
                   1768:     }
                   1769:     textarea.style.height=new_height+'px';
                   1770: }
1.824     bisitz   1771: // ]]>
1.565     albertel 1772: </script>
                   1773: RESIZE
                   1774: 
                   1775: }
                   1776: 
1.1205    golterma 1777: sub colorfuleditor_js {
1.1248    raeburn  1778:     my $browse_or_search;
                   1779:     my $respath;
                   1780:     my ($cnum,$cdom) = &crsauthor_url();
                   1781:     if ($cnum) {
                   1782:         $respath = "/res/$cdom/$cnum/";
                   1783:         my %js_lt = &Apache::lonlocal::texthash(
                   1784:             sunm => 'Sub-directory name',
                   1785:             save => 'Save page to make this permanent',
                   1786:         );
                   1787:         &js_escape(\%js_lt);
                   1788:         $browse_or_search = <<"END";
                   1789: 
                   1790:     function toggleChooser(form,element,titleid,only,search) {
                   1791:         var disp = 'none';
                   1792:         if (document.getElementById('chooser_'+element)) {
                   1793:             var curr = document.getElementById('chooser_'+element).style.display;
                   1794:             if (curr == 'none') {
                   1795:                 disp='inline';
                   1796:                 if (form.elements['chooser_'+element].length) {
                   1797:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1798:                         form.elements['chooser_'+element][i].checked = false;
                   1799:                     }
                   1800:                 }
                   1801:                 toggleResImport(form,element);
                   1802:             }
                   1803:             document.getElementById('chooser_'+element).style.display = disp;
                   1804:         }
                   1805:     }
                   1806: 
                   1807:     function toggleCrsFile(form,element,numdirs) {
                   1808:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1809:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1810:             if (curr == 'none') {
                   1811:                 if (numdirs) {
                   1812:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1813:                     if (numdirs > 1) {
                   1814:                         window['select1'+element+'_changed']();
                   1815:                     }
                   1816:                 }
                   1817:             } 
                   1818:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1819:             
                   1820:         }
                   1821:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1822:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1823:             if (document.getElementById('uploadcrsres_'+element)) {
                   1824:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1825:             }
                   1826:         }
                   1827:         return;
                   1828:     }
                   1829: 
                   1830:     function toggleCrsUpload(form,element,numcrsdirs) {
                   1831:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1832:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1833:         }
                   1834:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1835:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1836:             if (curr == 'none') {
                   1837:                 if (numcrsdirs) {
                   1838:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
                   1839:                    form.elements['newsubdir_'+element][0].checked = true;
                   1840:                    toggleNewsubdir(form,element);
                   1841:                 }
                   1842:             }
                   1843:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1844:         }
                   1845:         return;
                   1846:     }
                   1847: 
                   1848:     function toggleResImport(form,element) {
                   1849:         var choices = new Array('crsres','upload');
                   1850:         for (var i=0; i<choices.length; i++) {
                   1851:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1852:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1853:             }
                   1854:         }
                   1855:     }
                   1856: 
                   1857:     function toggleNewsubdir(form,element) {
                   1858:         var newsub = form.elements['newsubdir_'+element];
                   1859:         if (newsub) {
                   1860:             if (newsub.length) {
                   1861:                 for (var j=0; j<newsub.length; j++) {
                   1862:                     if (newsub[j].checked) {
                   1863:                         if (document.getElementById('newsubdirname_'+element)) {
                   1864:                             if (newsub[j].value == '1') {
                   1865:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1866:                                 if (document.getElementById('newsubdir_'+element)) {
                   1867:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1868:                                 }
                   1869:                             } else {
                   1870:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1871:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1872:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1873:                             }
                   1874:                         }
                   1875:                         break; 
                   1876:                     }
                   1877:                 }
                   1878:             }
                   1879:         }
                   1880:     }
                   1881: 
                   1882:     function updateCrsFile(form,element) {
                   1883:         var directory = form.elements['coursepath_'+element];
                   1884:         var filename = form.elements['coursefile_'+element];
                   1885:         var path = directory.options[directory.selectedIndex].value;
                   1886:         var file = filename.options[filename.selectedIndex].value;
                   1887:         form.elements[element].value = '$respath';
                   1888:         if (path == '/') {
                   1889:             form.elements[element].value += file;
                   1890:         } else {
                   1891:             form.elements[element].value += path+'/'+file;
                   1892:         }
                   1893:         unClean();
                   1894:         if (document.getElementById('previewimg_'+element)) {
                   1895:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1896:             var newsrc = document.getElementById('previewimg_'+element).src; 
                   1897:         }
                   1898:         if (document.getElementById('showimg_'+element)) {
                   1899:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1900:         }
                   1901:         toggleChooser(form,element);
                   1902:         return;
                   1903:     }
                   1904: 
                   1905:     function uploadDone(suffix,name) {
                   1906:         if (name) {
                   1907: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1908:             unClean();
                   1909:             toggleChooser(document.forms["lonhomework"],suffix);
                   1910:         }
                   1911:     }
                   1912: 
                   1913: \$(document).ready(function(){
                   1914: 
                   1915:     \$(document).delegate('form :submit', 'click', function( event ) {
                   1916:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   1917:             var buttonId = this.id;
                   1918:             var suffix = buttonId.toString();
                   1919:             suffix = suffix.replace(/^crsupload_/,'');
                   1920:             event.preventDefault();
                   1921:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   1922:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   1923:             \$(this.form).submit();
                   1924:             document.lonhomework.target = '';
                   1925:             if (document.getElementById('crsuploadto_'+suffix)) {
                   1926:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   1927:             }
                   1928:             return false;
                   1929:         }
                   1930:     });
                   1931: });
                   1932: END
                   1933:     }
1.1205    golterma 1934:     return <<"COLORFULEDIT"
                   1935: <script type="text/javascript">
                   1936: // <![CDATA[>
                   1937:     function fold_box(curDepth, lastresource){
                   1938: 
                   1939:     // we need a list because there can be several blocks you need to fold in one tag
                   1940:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1941:     // but there is only one folding button per tag
                   1942:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1943: 
                   1944:         if(block.item(0).style.display == 'none'){
                   1945: 
                   1946:             foldbutton.value = '@{[&mt("Hide")]}';
                   1947:             for (i = 0; i < block.length; i++){
                   1948:                 block.item(i).style.display = '';
                   1949:             }
                   1950:         }else{
                   1951: 
                   1952:             foldbutton.value = '@{[&mt("Show")]}';
                   1953:             for (i = 0; i < block.length; i++){
                   1954:                 // block.item(i).style.visibility = 'collapse';
                   1955:                 block.item(i).style.display = 'none';
                   1956:             }
                   1957:         };
                   1958:         saveState(lastresource);
                   1959:     }
                   1960: 
                   1961:     function saveState (lastresource) {
                   1962: 
                   1963:         var tag_list = getTagList();
                   1964:         if(tag_list != null){
                   1965:             var timestamp = new Date().getTime();
                   1966:             var key = lastresource;
                   1967: 
                   1968:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1969:             // starting with timestamp
                   1970:             var value = timestamp+';';
                   1971: 
                   1972:             // building the list of key-value pairs
                   1973:             for(var i = 0; i < tag_list.length; i++){
                   1974:                 value += tag_list[i]+',';
                   1975:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1976:             }
                   1977: 
                   1978:             // only iterate whole storage if nothing to override
                   1979:             if(localStorage.getItem(key) == null){        
                   1980: 
                   1981:                 // prevent storage from growing large
                   1982:                 if(localStorage.length > 50){
                   1983:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1984:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1985:                     var oldest_key;
                   1986:                     
                   1987:                     for(var i = 1; i < localStorage.length; i++){
                   1988:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1989:                             oldest_key = localStorage.key(i);
                   1990:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1991:                         }
                   1992:                     }
                   1993:                     localStorage.removeItem(oldest_key);
                   1994:                 }
                   1995:             }
                   1996:             localStorage.setItem(key,value);
                   1997:         }
                   1998:     }
                   1999: 
                   2000:     // restore folding status of blocks (on page load)
                   2001:     function restoreState (lastresource) {
                   2002:         if(localStorage.getItem(lastresource) != null){
                   2003:             var key = lastresource;
                   2004:             var value = localStorage.getItem(key);
                   2005:             var regex_delTimestamp = /^\d+;/;
                   2006: 
                   2007:             value.replace(regex_delTimestamp, '');
                   2008: 
                   2009:             var valueArr = value.split(';');
                   2010:             var pairs;
                   2011:             var elements;
                   2012:             for (var i = 0; i < valueArr.length; i++){
                   2013:                 pairs = valueArr[i].split(',');
                   2014:                 elements = document.getElementsByName(pairs[0]);
                   2015: 
                   2016:                 for (var j = 0; j < elements.length; j++){  
                   2017:                     elements[j].style.display = pairs[1];
                   2018:                     if (pairs[1] == "none"){
                   2019:                         var regex_id = /([_\\d]+)\$/;
                   2020:                         regex_id.exec(pairs[0]);
                   2021:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2022:                     }
                   2023:                 }
                   2024:             }
                   2025:         }
                   2026:     }
                   2027: 
                   2028:     function getTagList () {
                   2029:         
                   2030:         var stringToSearch = document.lonhomework.innerHTML;
                   2031: 
                   2032:         var ret = new Array();
                   2033:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2034:         var tag_list = stringToSearch.match(regex_findBlock);
                   2035: 
                   2036:         if(tag_list != null){
                   2037:             for(var i = 0; i < tag_list.length; i++){            
                   2038:                 ret.push(tag_list[i].replace(/"/, ''));
                   2039:             }
                   2040:         }
                   2041:         return ret;
                   2042:     }
                   2043: 
                   2044:     function saveScrollPosition (resource) {
                   2045:         var tag_list = getTagList();
                   2046: 
                   2047:         // we dont always want to jump to the first block
                   2048:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2049:         if(\$(window).scrollTop() > 170){
                   2050:             if(tag_list != null){
                   2051:                 var result;
                   2052:                 for(var i = 0; i < tag_list.length; i++){
                   2053:                     if(isElementInViewport(tag_list[i])){
                   2054:                         result += tag_list[i]+';';
                   2055:                     }
                   2056:                 }
                   2057:                 sessionStorage.setItem('anchor_'+resource, result);
                   2058:             }
                   2059:         } else {
                   2060:             // we dont need to save zero, just delete the item to leave everything tidy
                   2061:             sessionStorage.removeItem('anchor_'+resource);
                   2062:         }
                   2063:     }
                   2064: 
                   2065:     function restoreScrollPosition(resource){
                   2066: 
                   2067:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2068:         if(elem != null){
                   2069:             var tag_list = elem.split(';');
                   2070:             var elem_list;
                   2071: 
                   2072:             for(var i = 0; i < tag_list.length; i++){
                   2073:                 elem_list = document.getElementsByName(tag_list[i]);
                   2074:                 
                   2075:                 if(elem_list.length > 0){
                   2076:                     elem = elem_list[0];
                   2077:                     break;
                   2078:                 }
                   2079:             }
                   2080:             elem.scrollIntoView();
                   2081:         }
                   2082:     }
                   2083: 
                   2084:     function isElementInViewport(el) {
                   2085: 
                   2086:         // change to last element instead of first
                   2087:         var elem = document.getElementsByName(el);
                   2088:         var rect = elem[0].getBoundingClientRect();
                   2089: 
                   2090:         return (
                   2091:             rect.top >= 0 &&
                   2092:             rect.left >= 0 &&
                   2093:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2094:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2095:         );
                   2096:     }
                   2097:     
                   2098:     function autosize(depth){
                   2099:         var cmInst = window['cm'+depth];
                   2100:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2101: 
                   2102:         // is fixed size, switching to dynamic
                   2103:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2104:             cmInst.setSize("","auto");
                   2105:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2106:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2107: 
                   2108:         // is dynamic size, switching to fixed
                   2109:         } else {
                   2110:             cmInst.setSize("","300px");
                   2111:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2112:             sessionStorage.removeItem("autosized_"+depth);
                   2113:         }
                   2114:     }
                   2115: 
1.1248    raeburn  2116: $browse_or_search
1.1205    golterma 2117: 
                   2118: // ]]>
                   2119: </script>
                   2120: COLORFULEDIT
                   2121: }
                   2122: 
                   2123: sub xmleditor_js {
                   2124:     return <<XMLEDIT
                   2125: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2126: <script type="text/javascript">
                   2127: // <![CDATA[>
                   2128: 
                   2129:     function saveScrollPosition (resource) {
                   2130: 
                   2131:         var scrollPos = \$(window).scrollTop();
                   2132:         sessionStorage.setItem(resource,scrollPos);
                   2133:     }
                   2134: 
                   2135:     function restoreScrollPosition(resource){
                   2136: 
                   2137:         var scrollPos = sessionStorage.getItem(resource);
                   2138:         \$(window).scrollTop(scrollPos);
                   2139:     }
                   2140: 
                   2141:     // unless internet explorer
                   2142:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2143: 
                   2144:         \$(document).ready(function() {
                   2145:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2146:         });
                   2147:     }
                   2148: 
                   2149:     // inserts text at cursor position into codemirror (xml editor only)
                   2150:     function insertText(text){
                   2151:         cm.focus();
                   2152:         var curPos = cm.getCursor();
                   2153:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2154:     }
                   2155: // ]]>
                   2156: </script>
                   2157: XMLEDIT
                   2158: }
                   2159: 
                   2160: sub insert_folding_button {
                   2161:     my $curDepth = $Apache::lonxml::curdepth;
                   2162:     my $lastresource = $env{'request.ambiguous'};
                   2163: 
                   2164:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2165:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2166: }
                   2167: 
1.1248    raeburn  2168: sub crsauthor_url {
                   2169:     my ($url) = @_;
                   2170:     if ($url eq '') {
                   2171:         $url = $ENV{'REQUEST_URI'};
                   2172:     }
                   2173:     my ($cnum,$cdom);
                   2174:     if ($env{'request.course.id'}) {
                   2175:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2176:         if ($audom ne '' && $auname ne '') {
                   2177:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2178:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2179:                 $cnum = $auname;
                   2180:                 $cdom = $audom;
                   2181:             }
                   2182:         }
                   2183:     }
                   2184:     return ($cnum,$cdom);
                   2185: }
                   2186: 
                   2187: sub import_crsauthor_form {
1.1265    raeburn  2188:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2189:     return (0) unless ($env{'request.course.id'});
                   2190:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2191:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2192:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2193:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2194:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2195:     my @ids=&Apache::lonnet::current_machine_ids();
                   2196:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
                   2197:     
                   2198:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2199:         $is_home = 1;
                   2200:     }
                   2201:     $relpath = "/priv/$cdom/$cnum";
                   2202:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
                   2203:     my %lt = &Apache::lonlocal::texthash (
                   2204:         fnam => 'Filename',
                   2205:         dire => 'Directory',
                   2206:     );
                   2207:     my $numdirs = scalar(keys(%files));
                   2208:     my (%possexts,$singledir,@singledirfiles);
                   2209:     if ($only) {
                   2210:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
                   2211:     }
                   2212:     my (%nonemptydirs,$possdirs);
                   2213:     if ($numdirs > 1) {
                   2214:         my @order;
                   2215:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
                   2216:             if (ref($files{$key}) eq 'HASH') {
                   2217:                 my $shown = $key;
                   2218:                 if ($key eq '') {
                   2219:                     $shown = '/';
                   2220:                 }
                   2221:                 my @ordered = ();
                   2222:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
                   2223:                     if ($only) {
                   2224:                         my ($ext) = ($file =~ /\.([^.]+)$/);
                   2225:                         unless ($possexts{lc($ext)}) {
                   2226:                             next;
                   2227:                         }
                   2228:                     }
                   2229:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
                   2230:                     push(@ordered,$file);
                   2231:                 }
                   2232:                 if (@ordered) {
                   2233:                     push(@order,$key);
                   2234:                     $nonemptydirs{$key} = 1;
                   2235:                     $selimport_menus{$key}->{'text'} = $shown;
                   2236:                     $selimport_menus{$key}->{'default'} = '';
                   2237:                     $selimport_menus{$key}->{'select2'}->{''} = '';
                   2238:                     $selimport_menus{$key}->{'order'} = \@ordered;
                   2239:                 }
                   2240:             }
                   2241:         }
                   2242:         $possdirs = scalar(keys(%nonemptydirs));
                   2243:         if ($possdirs > 1) {
                   2244:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
                   2245:             $output = $lt{'dire'}.
                   2246:                       &linked_select_forms($form,'<br />'.
                   2247:                                            $lt{'fnam'},'',
                   2248:                                            $firstselectname,$secondselectname,
                   2249:                                            \%selimport_menus,\@order,
                   2250:                                            $onchangefirst,'',$suffix).'<br />';
                   2251:         } elsif ($possdirs == 1) {
                   2252:             $singledir = (keys(%nonemptydirs))[0];
                   2253:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
                   2254:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
                   2255:             }
                   2256:             delete($selimport_menus{$singledir});
                   2257:         }
                   2258:     } elsif ($numdirs == 1) {
                   2259:         $singledir = (keys(%files))[0];
                   2260:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
                   2261:             if ($only) {
                   2262:                 my ($ext) = ($file =~ /\.([^.]+)$/);
                   2263:                 unless ($possexts{lc($ext)}) {
                   2264:                     next;
                   2265:                 }
                   2266:             }
                   2267:             push(@singledirfiles,$file);
                   2268:         }
                   2269:         if (@singledirfiles) {
                   2270:             $possdirs == 1;
                   2271:         }
                   2272:     }
                   2273:     if (($possdirs == 1) && (@singledirfiles)) {
                   2274:         my $showdir = $singledir;
                   2275:         if ($singledir eq '') {
                   2276:             $showdir = '/';
                   2277:         }
                   2278:         $output = $lt{'dire'}.
                   2279:                   '<select name="'.$firstselectname.'">'.
                   2280:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
                   2281:                   '</select><br />'.
                   2282:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
                   2283:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
                   2284:         foreach my $file (@singledirfiles) {
                   2285:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
                   2286:         }
                   2287:         $output .= '</select><br />'."\n";
                   2288:     }
                   2289:     return ($possdirs,$output);
                   2290: }
                   2291: 
1.565     albertel 2292: =pod
                   2293: 
1.256     matthew  2294: =head1 Excel and CSV file utility routines
                   2295: 
                   2296: =cut
                   2297: 
                   2298: ###############################################################
                   2299: ###############################################################
                   2300: 
                   2301: =pod
                   2302: 
1.1162    raeburn  2303: =over 4
                   2304: 
1.648     raeburn  2305: =item * &csv_translate($text) 
1.37      matthew  2306: 
1.185     www      2307: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2308: format.
                   2309: 
                   2310: =cut
                   2311: 
1.180     matthew  2312: ###############################################################
                   2313: ###############################################################
1.37      matthew  2314: sub csv_translate {
                   2315:     my $text = shift;
                   2316:     $text =~ s/\"/\"\"/g;
1.209     albertel 2317:     $text =~ s/\n/ /g;
1.37      matthew  2318:     return $text;
                   2319: }
1.180     matthew  2320: 
                   2321: ###############################################################
                   2322: ###############################################################
                   2323: 
                   2324: =pod
                   2325: 
1.648     raeburn  2326: =item * &define_excel_formats()
1.180     matthew  2327: 
                   2328: Define some commonly used Excel cell formats.
                   2329: 
                   2330: Currently supported formats:
                   2331: 
                   2332: =over 4
                   2333: 
                   2334: =item header
                   2335: 
                   2336: =item bold
                   2337: 
                   2338: =item h1
                   2339: 
                   2340: =item h2
                   2341: 
                   2342: =item h3
                   2343: 
1.256     matthew  2344: =item h4
                   2345: 
                   2346: =item i
                   2347: 
1.180     matthew  2348: =item date
                   2349: 
                   2350: =back
                   2351: 
                   2352: Inputs: $workbook
                   2353: 
                   2354: Returns: $format, a hash reference.
                   2355: 
1.1057    foxr     2356: 
1.180     matthew  2357: =cut
                   2358: 
                   2359: ###############################################################
                   2360: ###############################################################
                   2361: sub define_excel_formats {
                   2362:     my ($workbook) = @_;
                   2363:     my $format;
                   2364:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2365:                                                 bottom    => 1,
                   2366:                                                 align     => 'center');
                   2367:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2368:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2369:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2370:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2371:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2372:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2373:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2374:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2375:     return $format;
                   2376: }
                   2377: 
                   2378: ###############################################################
                   2379: ###############################################################
1.113     bowersj2 2380: 
                   2381: =pod
                   2382: 
1.648     raeburn  2383: =item * &create_workbook()
1.255     matthew  2384: 
                   2385: Create an Excel worksheet.  If it fails, output message on the
                   2386: request object and return undefs.
                   2387: 
                   2388: Inputs: Apache request object
                   2389: 
                   2390: Returns (undef) on failure, 
                   2391:     Excel worksheet object, scalar with filename, and formats 
                   2392:     from &Apache::loncommon::define_excel_formats on success
                   2393: 
                   2394: =cut
                   2395: 
                   2396: ###############################################################
                   2397: ###############################################################
                   2398: sub create_workbook {
                   2399:     my ($r) = @_;
                   2400:         #
                   2401:     # Create the excel spreadsheet
                   2402:     my $filename = '/prtspool/'.
1.258     albertel 2403:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2404:         time.'_'.rand(1000000000).'.xls';
                   2405:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2406:     if (! defined($workbook)) {
                   2407:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2408:         $r->print(
                   2409:             '<p class="LC_error">'
                   2410:            .&mt('Problems occurred in creating the new Excel file.')
                   2411:            .' '.&mt('This error has been logged.')
                   2412:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2413:            .'</p>'
                   2414:         );
1.255     matthew  2415:         return (undef);
                   2416:     }
                   2417:     #
1.1014    foxr     2418:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2419:     #
                   2420:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2421:     return ($workbook,$filename,$format);
                   2422: }
                   2423: 
                   2424: ###############################################################
                   2425: ###############################################################
                   2426: 
                   2427: =pod
                   2428: 
1.648     raeburn  2429: =item * &create_text_file()
1.113     bowersj2 2430: 
1.542     raeburn  2431: Create a file to write to and eventually make available to the user.
1.256     matthew  2432: If file creation fails, outputs an error message on the request object and 
                   2433: return undefs.
1.113     bowersj2 2434: 
1.256     matthew  2435: Inputs: Apache request object, and file suffix
1.113     bowersj2 2436: 
1.256     matthew  2437: Returns (undef) on failure, 
                   2438:     Filehandle and filename on success.
1.113     bowersj2 2439: 
                   2440: =cut
                   2441: 
1.256     matthew  2442: ###############################################################
                   2443: ###############################################################
                   2444: sub create_text_file {
                   2445:     my ($r,$suffix) = @_;
                   2446:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2447:     my $fh;
                   2448:     my $filename = '/prtspool/'.
1.258     albertel 2449:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2450:         time.'_'.rand(1000000000).'.'.$suffix;
                   2451:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2452:     if (! defined($fh)) {
                   2453:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2454:         $r->print(
                   2455:             '<p class="LC_error">'
                   2456:            .&mt('Problems occurred in creating the output file.')
                   2457:            .' '.&mt('This error has been logged.')
                   2458:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2459:            .'</p>'
                   2460:         );
1.113     bowersj2 2461:     }
1.256     matthew  2462:     return ($fh,$filename)
1.113     bowersj2 2463: }
                   2464: 
                   2465: 
1.256     matthew  2466: =pod 
1.113     bowersj2 2467: 
                   2468: =back
                   2469: 
                   2470: =cut
1.37      matthew  2471: 
                   2472: ###############################################################
1.33      matthew  2473: ##        Home server <option> list generating code          ##
                   2474: ###############################################################
1.35      matthew  2475: 
1.169     www      2476: # ------------------------------------------
                   2477: 
                   2478: sub domain_select {
                   2479:     my ($name,$value,$multiple)=@_;
                   2480:     my %domains=map { 
1.514     albertel 2481: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2482:     } &Apache::lonnet::all_domains();
1.169     www      2483:     if ($multiple) {
                   2484: 	$domains{''}=&mt('Any domain');
1.550     albertel 2485: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2486: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2487:     } else {
1.550     albertel 2488: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2489: 	return &select_form($name,$value,\%domains);
1.169     www      2490:     }
                   2491: }
                   2492: 
1.282     albertel 2493: #-------------------------------------------
                   2494: 
                   2495: =pod
                   2496: 
1.519     raeburn  2497: =head1 Routines for form select boxes
                   2498: 
                   2499: =over 4
                   2500: 
1.648     raeburn  2501: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2502: 
                   2503: Returns a string containing a <select> element int multiple mode
                   2504: 
                   2505: 
                   2506: Args:
                   2507:   $name - name of the <select> element
1.506     raeburn  2508:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2509:   $size - number of rows long the select element is
1.283     albertel 2510:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2511:           (shown text should already have been &mt())
1.506     raeburn  2512:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2513: 
1.282     albertel 2514: =cut
                   2515: 
                   2516: #-------------------------------------------
1.169     www      2517: sub multiple_select_form {
1.284     albertel 2518:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2519:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2520:     my $output='';
1.191     matthew  2521:     if (! defined($size)) {
                   2522:         $size = 4;
1.283     albertel 2523:         if (scalar(keys(%$hash))<4) {
                   2524:             $size = scalar(keys(%$hash));
1.191     matthew  2525:         }
                   2526:     }
1.734     bisitz   2527:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2528:     my @order;
1.506     raeburn  2529:     if (ref($order) eq 'ARRAY')  {
                   2530:         @order = @{$order};
                   2531:     } else {
                   2532:         @order = sort(keys(%$hash));
1.501     banghart 2533:     }
                   2534:     if (exists($$hash{'select_form_order'})) {
                   2535:         @order = @{$$hash{'select_form_order'}};
                   2536:     }
                   2537:         
1.284     albertel 2538:     foreach my $key (@order) {
1.356     albertel 2539:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2540:         $output.='selected="selected" ' if ($selected{$key});
                   2541:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2542:     }
                   2543:     $output.="</select>\n";
                   2544:     return $output;
                   2545: }
                   2546: 
1.88      www      2547: #-------------------------------------------
                   2548: 
                   2549: =pod
                   2550: 
1.1254    raeburn  2551: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2552: 
                   2553: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2554: allow a user to select options from a ref to a hash containing:
                   2555: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2556: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2557: An optional arg -- $readonly -- if true will cause the select form
                   2558: to be disabled, e.g., for the case where an instructor has a section-
                   2559: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2560: 
1.88      www      2561: See lonrights.pm for an example invocation and use.
                   2562: 
                   2563: =cut
                   2564: 
                   2565: #-------------------------------------------
                   2566: sub select_form {
1.1228    raeburn  2567:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2568:     return unless (ref($hashref) eq 'HASH');
                   2569:     if ($onchange) {
                   2570:         $onchange = ' onchange="'.$onchange.'"';
                   2571:     }
1.1228    raeburn  2572:     my $disabled;
                   2573:     if ($readonly) {
                   2574:         $disabled = ' disabled="disabled"';
                   2575:     }
                   2576:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2577:     my @keys;
1.970     raeburn  2578:     if (exists($hashref->{'select_form_order'})) {
                   2579: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2580:     } else {
1.970     raeburn  2581: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2582:     }
1.356     albertel 2583:     foreach my $key (@keys) {
                   2584:         $selectform.=
                   2585: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2586:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2587:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2588:     }
                   2589:     $selectform.="</select>";
                   2590:     return $selectform;
                   2591: }
                   2592: 
1.475     www      2593: # For display filters
                   2594: 
                   2595: sub display_filter {
1.1074    raeburn  2596:     my ($context) = @_;
1.475     www      2597:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2598:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2599:     my $phraseinput = 'hidden';
                   2600:     my $includeinput = 'hidden';
                   2601:     my ($checked,$includetypestext);
                   2602:     if ($env{'form.displayfilter'} eq 'containing') {
                   2603:         $phraseinput = 'text'; 
                   2604:         if ($context eq 'parmslog') {
                   2605:             $includeinput = 'checkbox';
                   2606:             if ($env{'form.includetypes'}) {
                   2607:                 $checked = ' checked="checked"';
                   2608:             }
                   2609:             $includetypestext = &mt('Include parameter types');
                   2610:         }
                   2611:     } else {
                   2612:         $includetypestext = '&nbsp;';
                   2613:     }
                   2614:     my ($additional,$secondid,$thirdid);
                   2615:     if ($context eq 'parmslog') {
                   2616:         $additional = 
                   2617:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2618:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2619:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2620:             '</label>';
                   2621:         $secondid = 'includetypes';
                   2622:         $thirdid = 'includetypestext';
                   2623:     }
                   2624:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2625:                                                     '$secondid','$thirdid')";
                   2626:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2627: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2628: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2629: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2630:            &mt('Filter: [_1]',
1.477     www      2631: 	   &select_form($env{'form.displayfilter'},
                   2632: 			'displayfilter',
1.970     raeburn  2633: 			{'currentfolder' => 'Current folder/page',
1.477     www      2634: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2635: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2636: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2637:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2638:                          '" />'.$additional;
                   2639: }
                   2640: 
                   2641: sub display_filter_js {
                   2642:     my $includetext = &mt('Include parameter types');
                   2643:     return <<"ENDJS";
                   2644:   
                   2645: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2646:     var firstType = 'hidden';
                   2647:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2648:         firstType = 'text';
                   2649:     }
                   2650:     firstObject = document.getElementById(firstid);
                   2651:     if (typeof(firstObject) == 'object') {
                   2652:         if (firstObject.type != firstType) {
                   2653:             changeInputType(firstObject,firstType);
                   2654:         }
                   2655:     }
                   2656:     if (context == 'parmslog') {
                   2657:         var secondType = 'hidden';
                   2658:         if (firstType == 'text') {
                   2659:             secondType = 'checkbox';
                   2660:         }
                   2661:         secondObject = document.getElementById(secondid);  
                   2662:         if (typeof(secondObject) == 'object') {
                   2663:             if (secondObject.type != secondType) {
                   2664:                 changeInputType(secondObject,secondType);
                   2665:             }
                   2666:         }
                   2667:         var textItem = document.getElementById(thirdid);
                   2668:         var currtext = textItem.innerHTML;
                   2669:         var newtext;
                   2670:         if (firstType == 'text') {
                   2671:             newtext = '$includetext';
                   2672:         } else {
                   2673:             newtext = '&nbsp;';
                   2674:         }
                   2675:         if (currtext != newtext) {
                   2676:             textItem.innerHTML = newtext;
                   2677:         }
                   2678:     }
                   2679:     return;
                   2680: }
                   2681: 
                   2682: function changeInputType(oldObject,newType) {
                   2683:     var newObject = document.createElement('input');
                   2684:     newObject.type = newType;
                   2685:     if (oldObject.size) {
                   2686:         newObject.size = oldObject.size;
                   2687:     }
                   2688:     if (oldObject.value) {
                   2689:         newObject.value = oldObject.value;
                   2690:     }
                   2691:     if (oldObject.name) {
                   2692:         newObject.name = oldObject.name;
                   2693:     }
                   2694:     if (oldObject.id) {
                   2695:         newObject.id = oldObject.id;
                   2696:     }
                   2697:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2698:     return;
                   2699: }
                   2700: 
                   2701: ENDJS
1.475     www      2702: }
                   2703: 
1.167     www      2704: sub gradeleveldescription {
                   2705:     my $gradelevel=shift;
                   2706:     my %gradelevels=(0 => 'Not specified',
                   2707: 		     1 => 'Grade 1',
                   2708: 		     2 => 'Grade 2',
                   2709: 		     3 => 'Grade 3',
                   2710: 		     4 => 'Grade 4',
                   2711: 		     5 => 'Grade 5',
                   2712: 		     6 => 'Grade 6',
                   2713: 		     7 => 'Grade 7',
                   2714: 		     8 => 'Grade 8',
                   2715: 		     9 => 'Grade 9',
                   2716: 		     10 => 'Grade 10',
                   2717: 		     11 => 'Grade 11',
                   2718: 		     12 => 'Grade 12',
                   2719: 		     13 => 'Grade 13',
                   2720: 		     14 => '100 Level',
                   2721: 		     15 => '200 Level',
                   2722: 		     16 => '300 Level',
                   2723: 		     17 => '400 Level',
                   2724: 		     18 => 'Graduate Level');
                   2725:     return &mt($gradelevels{$gradelevel});
                   2726: }
                   2727: 
1.163     www      2728: sub select_level_form {
                   2729:     my ($deflevel,$name)=@_;
                   2730:     unless ($deflevel) { $deflevel=0; }
1.167     www      2731:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2732:     for (my $i=0; $i<=18; $i++) {
                   2733:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2734:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2735:                 ">".&gradeleveldescription($i)."</option>\n";
                   2736:     }
                   2737:     $selectform.="</select>";
                   2738:     return $selectform;
1.163     www      2739: }
1.167     www      2740: 
1.35      matthew  2741: #-------------------------------------------
                   2742: 
1.45      matthew  2743: =pod
                   2744: 
1.1256    raeburn  2745: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2746: 
                   2747: Returns a string containing a <select name='$name' size='1'> form to 
                   2748: allow a user to select the domain to preform an operation in.  
                   2749: See loncreateuser.pm for an example invocation and use.
                   2750: 
1.90      www      2751: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2752: selected");
                   2753: 
1.743     raeburn  2754: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2755: 
1.910     raeburn  2756: 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.
                   2757: 
1.1121    raeburn  2758: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2759: 
                   2760: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2761: 
1.1256    raeburn  2762: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2763: 
1.35      matthew  2764: =cut
                   2765: 
                   2766: #-------------------------------------------
1.34      matthew  2767: sub select_dom_form {
1.1256    raeburn  2768:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2769:     if ($onchange) {
1.874     raeburn  2770:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2771:     }
1.1256    raeburn  2772:     if ($disabled) {
                   2773:         $disabled = ' disabled="disabled"';
                   2774:     }
1.1121    raeburn  2775:     my (@domains,%exclude);
1.910     raeburn  2776:     if (ref($incdoms) eq 'ARRAY') {
                   2777:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2778:     } else {
                   2779:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2780:     }
1.90      www      2781:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2782:     if (ref($excdoms) eq 'ARRAY') {
                   2783:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2784:     }
1.1256    raeburn  2785:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2786:     foreach my $dom (@domains) {
1.1121    raeburn  2787:         next if ($exclude{$dom});
1.356     albertel 2788:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2789:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2790:         if ($showdomdesc) {
                   2791:             if ($dom ne '') {
                   2792:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2793:                 if ($domdesc ne '') {
                   2794:                     $selectdomain .= ' ('.$domdesc.')';
                   2795:                 }
                   2796:             } 
                   2797:         }
                   2798:         $selectdomain .= "</option>\n";
1.34      matthew  2799:     }
                   2800:     $selectdomain.="</select>";
                   2801:     return $selectdomain;
                   2802: }
                   2803: 
1.35      matthew  2804: #-------------------------------------------
                   2805: 
1.45      matthew  2806: =pod
                   2807: 
1.648     raeburn  2808: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2809: 
1.586     raeburn  2810: input: 4 arguments (two required, two optional) - 
                   2811:     $domain - domain of new user
                   2812:     $name - name of form element
                   2813:     $default - Value of 'default' causes a default item to be first 
                   2814:                             option, and selected by default. 
                   2815:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2816:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2817: output: returns 2 items: 
1.586     raeburn  2818: (a) form element which contains either:
                   2819:    (i) <select name="$name">
                   2820:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2821:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2822:        </select>
                   2823:        form item if there are multiple library servers in $domain, or
                   2824:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2825:        if there is only one library server in $domain.
                   2826: 
                   2827: (b) number of library servers found.
                   2828: 
                   2829: See loncreateuser.pm for example of use.
1.35      matthew  2830: 
                   2831: =cut
                   2832: 
                   2833: #-------------------------------------------
1.586     raeburn  2834: sub home_server_form_item {
                   2835:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2836:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2837:     my $result;
                   2838:     my $numlib = keys(%servers);
                   2839:     if ($numlib > 1) {
                   2840:         $result .= '<select name="'.$name.'" />'."\n";
                   2841:         if ($default) {
1.804     bisitz   2842:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2843:                        '</option>'."\n";
                   2844:         }
                   2845:         foreach my $hostid (sort(keys(%servers))) {
                   2846:             $result.= '<option value="'.$hostid.'">'.
                   2847: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2848:         }
                   2849:         $result .= '</select>'."\n";
                   2850:     } elsif ($numlib == 1) {
                   2851:         my $hostid;
                   2852:         foreach my $item (keys(%servers)) {
                   2853:             $hostid = $item;
                   2854:         }
                   2855:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2856:                    $hostid.'" />';
                   2857:                    if (!$hide) {
                   2858:                        $result .= $hostid.' '.$servers{$hostid};
                   2859:                    }
                   2860:                    $result .= "\n";
                   2861:     } elsif ($default) {
                   2862:         $result .= '<input type="hidden" name="'.$name.
                   2863:                    '" value="default" />';
                   2864:                    if (!$hide) {
                   2865:                        $result .= &mt('default');
                   2866:                    }
                   2867:                    $result .= "\n";
1.33      matthew  2868:     }
1.586     raeburn  2869:     return ($result,$numlib);
1.33      matthew  2870: }
1.112     bowersj2 2871: 
                   2872: =pod
                   2873: 
1.534     albertel 2874: =back 
                   2875: 
1.112     bowersj2 2876: =cut
1.87      matthew  2877: 
                   2878: ###############################################################
1.112     bowersj2 2879: ##                  Decoding User Agent                      ##
1.87      matthew  2880: ###############################################################
                   2881: 
                   2882: =pod
                   2883: 
1.112     bowersj2 2884: =head1 Decoding the User Agent
                   2885: 
                   2886: =over 4
                   2887: 
                   2888: =item * &decode_user_agent()
1.87      matthew  2889: 
                   2890: Inputs: $r
                   2891: 
                   2892: Outputs:
                   2893: 
                   2894: =over 4
                   2895: 
1.112     bowersj2 2896: =item * $httpbrowser
1.87      matthew  2897: 
1.112     bowersj2 2898: =item * $clientbrowser
1.87      matthew  2899: 
1.112     bowersj2 2900: =item * $clientversion
1.87      matthew  2901: 
1.112     bowersj2 2902: =item * $clientmathml
1.87      matthew  2903: 
1.112     bowersj2 2904: =item * $clientunicode
1.87      matthew  2905: 
1.112     bowersj2 2906: =item * $clientos
1.87      matthew  2907: 
1.1137    raeburn  2908: =item * $clientmobile
                   2909: 
1.1141    raeburn  2910: =item * $clientinfo
                   2911: 
1.1194    raeburn  2912: =item * $clientosversion
                   2913: 
1.87      matthew  2914: =back
                   2915: 
1.157     matthew  2916: =back 
                   2917: 
1.87      matthew  2918: =cut
                   2919: 
                   2920: ###############################################################
                   2921: ###############################################################
                   2922: sub decode_user_agent {
1.247     albertel 2923:     my ($r)=@_;
1.87      matthew  2924:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2925:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2926:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2927:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2928:     my $clientbrowser='unknown';
                   2929:     my $clientversion='0';
                   2930:     my $clientmathml='';
                   2931:     my $clientunicode='0';
1.1137    raeburn  2932:     my $clientmobile=0;
1.1194    raeburn  2933:     my $clientosversion='';
1.87      matthew  2934:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2935:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2936: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2937: 	    $clientbrowser=$bname;
                   2938:             $httpbrowser=~/$vreg/i;
                   2939: 	    $clientversion=$1;
                   2940:             $clientmathml=($clientversion>=$minv);
                   2941:             $clientunicode=($clientversion>=$univ);
                   2942: 	}
                   2943:     }
                   2944:     my $clientos='unknown';
1.1141    raeburn  2945:     my $clientinfo;
1.87      matthew  2946:     if (($httpbrowser=~/linux/i) ||
                   2947:         ($httpbrowser=~/unix/i) ||
                   2948:         ($httpbrowser=~/ux/i) ||
                   2949:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2950:     if (($httpbrowser=~/vax/i) ||
                   2951:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2952:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2953:     if (($httpbrowser=~/mac/i) ||
                   2954:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2955:     if ($httpbrowser=~/win/i) {
                   2956:         $clientos='win';
                   2957:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2958:             $clientosversion = $1;
                   2959:         }
                   2960:     }
1.87      matthew  2961:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  2962:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2963:         $clientmobile=lc($1);
                   2964:     }
1.1141    raeburn  2965:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2966:         $clientinfo = 'firefox-'.$1;
                   2967:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2968:         $clientinfo = 'chromeframe-'.$1;
                   2969:     }
1.87      matthew  2970:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  2971:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2972:             $clientosversion);
1.87      matthew  2973: }
                   2974: 
1.32      matthew  2975: ###############################################################
                   2976: ##    Authentication changing form generation subroutines    ##
                   2977: ###############################################################
                   2978: ##
                   2979: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2980: ## hash, and have reasonable default values.
                   2981: ##
                   2982: ##    formname = the name given in the <form> tag.
1.35      matthew  2983: #-------------------------------------------
                   2984: 
1.45      matthew  2985: =pod
                   2986: 
1.112     bowersj2 2987: =head1 Authentication Routines
                   2988: 
                   2989: =over 4
                   2990: 
1.648     raeburn  2991: =item * &authform_xxxxxx()
1.35      matthew  2992: 
                   2993: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2994: handle some of the conveniences required for authentication forms.  
                   2995: This is not an optimal method, but it works.  
                   2996: 
                   2997: =over 4
                   2998: 
1.112     bowersj2 2999: =item * authform_header
1.35      matthew  3000: 
1.112     bowersj2 3001: =item * authform_authorwarning
1.35      matthew  3002: 
1.112     bowersj2 3003: =item * authform_nochange
1.35      matthew  3004: 
1.112     bowersj2 3005: =item * authform_kerberos
1.35      matthew  3006: 
1.112     bowersj2 3007: =item * authform_internal
1.35      matthew  3008: 
1.112     bowersj2 3009: =item * authform_filesystem
1.35      matthew  3010: 
                   3011: =back
                   3012: 
1.648     raeburn  3013: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3014: 
1.35      matthew  3015: =cut
                   3016: 
                   3017: #-------------------------------------------
1.32      matthew  3018: sub authform_header{  
                   3019:     my %in = (
                   3020:         formname => 'cu',
1.80      albertel 3021:         kerb_def_dom => '',
1.32      matthew  3022:         @_,
                   3023:     );
                   3024:     $in{'formname'} = 'document.' . $in{'formname'};
                   3025:     my $result='';
1.80      albertel 3026: 
                   3027: #---------------------------------------------- Code for upper case translation
                   3028:     my $Javascript_toUpperCase;
                   3029:     unless ($in{kerb_def_dom}) {
                   3030:         $Javascript_toUpperCase =<<"END";
                   3031:         switch (choice) {
                   3032:            case 'krb': currentform.elements[choicearg].value =
                   3033:                currentform.elements[choicearg].value.toUpperCase();
                   3034:                break;
                   3035:            default:
                   3036:         }
                   3037: END
                   3038:     } else {
                   3039:         $Javascript_toUpperCase = "";
                   3040:     }
                   3041: 
1.165     raeburn  3042:     my $radioval = "'nochange'";
1.591     raeburn  3043:     if (defined($in{'curr_authtype'})) {
                   3044:         if ($in{'curr_authtype'} ne '') {
                   3045:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3046:         }
1.174     matthew  3047:     }
1.165     raeburn  3048:     my $argfield = 'null';
1.591     raeburn  3049:     if (defined($in{'mode'})) {
1.165     raeburn  3050:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3051:             if (defined($in{'curr_autharg'})) {
                   3052:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3053:                     $argfield = "'$in{'curr_autharg'}'";
                   3054:                 }
                   3055:             }
                   3056:         }
                   3057:     }
                   3058: 
1.32      matthew  3059:     $result.=<<"END";
                   3060: var current = new Object();
1.165     raeburn  3061: current.radiovalue = $radioval;
                   3062: current.argfield = $argfield;
1.32      matthew  3063: 
                   3064: function changed_radio(choice,currentform) {
                   3065:     var choicearg = choice + 'arg';
                   3066:     // If a radio button in changed, we need to change the argfield
                   3067:     if (current.radiovalue != choice) {
                   3068:         current.radiovalue = choice;
                   3069:         if (current.argfield != null) {
                   3070:             currentform.elements[current.argfield].value = '';
                   3071:         }
                   3072:         if (choice == 'nochange') {
                   3073:             current.argfield = null;
                   3074:         } else {
                   3075:             current.argfield = choicearg;
                   3076:             switch(choice) {
                   3077:                 case 'krb': 
                   3078:                     currentform.elements[current.argfield].value = 
                   3079:                         "$in{'kerb_def_dom'}";
                   3080:                 break;
                   3081:               default:
                   3082:                 break;
                   3083:             }
                   3084:         }
                   3085:     }
                   3086:     return;
                   3087: }
1.22      www      3088: 
1.32      matthew  3089: function changed_text(choice,currentform) {
                   3090:     var choicearg = choice + 'arg';
                   3091:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3092:         $Javascript_toUpperCase
1.32      matthew  3093:         // clear old field
                   3094:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3095:             currentform.elements[current.argfield].value = '';
                   3096:         }
                   3097:         current.argfield = choicearg;
                   3098:     }
                   3099:     set_auth_radio_buttons(choice,currentform);
                   3100:     return;
1.20      www      3101: }
1.32      matthew  3102: 
                   3103: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3104:     var numauthchoices = currentform.login.length;
                   3105:     if (typeof numauthchoices  == "undefined") {
                   3106:         return;
                   3107:     } 
1.32      matthew  3108:     var i=0;
1.986     raeburn  3109:     while (i < numauthchoices) {
1.32      matthew  3110:         if (currentform.login[i].value == newvalue) { break; }
                   3111:         i++;
                   3112:     }
1.986     raeburn  3113:     if (i == numauthchoices) {
1.32      matthew  3114:         return;
                   3115:     }
                   3116:     current.radiovalue = newvalue;
                   3117:     currentform.login[i].checked = true;
                   3118:     return;
                   3119: }
                   3120: END
                   3121:     return $result;
                   3122: }
                   3123: 
1.1106    raeburn  3124: sub authform_authorwarning {
1.32      matthew  3125:     my $result='';
1.144     matthew  3126:     $result='<i>'.
                   3127:         &mt('As a general rule, only authors or co-authors should be '.
                   3128:             'filesystem authenticated '.
                   3129:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3130:     return $result;
                   3131: }
                   3132: 
1.1106    raeburn  3133: sub authform_nochange {
1.32      matthew  3134:     my %in = (
                   3135:               formname => 'document.cu',
                   3136:               kerb_def_dom => 'MSU.EDU',
                   3137:               @_,
                   3138:           );
1.1106    raeburn  3139:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3140:     my $result;
1.1104    raeburn  3141:     if (!$authnum) {
1.1105    raeburn  3142:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3143:     } else {
                   3144:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3145:                   '<input type="radio" name="login" value="nochange" '.
                   3146:                   'checked="checked" onclick="'.
1.281     albertel 3147:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3148: 	    '</label>';
1.586     raeburn  3149:     }
1.32      matthew  3150:     return $result;
                   3151: }
                   3152: 
1.591     raeburn  3153: sub authform_kerberos {
1.32      matthew  3154:     my %in = (
                   3155:               formname => 'document.cu',
                   3156:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3157:               kerb_def_auth => 'krb4',
1.32      matthew  3158:               @_,
                   3159:               );
1.586     raeburn  3160:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3161:         $autharg,$jscall,$disabled);
1.1106    raeburn  3162:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3163:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3164:        $check5 = ' checked="checked"';
1.80      albertel 3165:     } else {
1.772     bisitz   3166:        $check4 = ' checked="checked"';
1.80      albertel 3167:     }
1.1259    raeburn  3168:     if ($in{'readonly'}) {
                   3169:         $disabled = ' disabled="disabled"';
                   3170:     }
1.165     raeburn  3171:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3172:     if (defined($in{'curr_authtype'})) {
                   3173:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3174:             $krbcheck = ' checked="checked"';
1.623     raeburn  3175:             if (defined($in{'mode'})) {
                   3176:                 if ($in{'mode'} eq 'modifyuser') {
                   3177:                     $krbcheck = '';
                   3178:                 }
                   3179:             }
1.591     raeburn  3180:             if (defined($in{'curr_kerb_ver'})) {
                   3181:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3182:                     $check5 = ' checked="checked"';
1.591     raeburn  3183:                     $check4 = '';
                   3184:                 } else {
1.772     bisitz   3185:                     $check4 = ' checked="checked"';
1.591     raeburn  3186:                     $check5 = '';
                   3187:                 }
1.586     raeburn  3188:             }
1.591     raeburn  3189:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3190:                 $krbarg = $in{'curr_autharg'};
                   3191:             }
1.586     raeburn  3192:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3193:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3194:                     $result = 
                   3195:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3196:         $in{'curr_autharg'},$krbver);
                   3197:                 } else {
                   3198:                     $result =
                   3199:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3200:                 }
                   3201:                 return $result; 
                   3202:             }
                   3203:         }
                   3204:     } else {
                   3205:         if ($authnum == 1) {
1.784     bisitz   3206:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3207:         }
                   3208:     }
1.586     raeburn  3209:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3210:         return;
1.587     raeburn  3211:     } elsif ($authtype eq '') {
1.591     raeburn  3212:         if (defined($in{'mode'})) {
1.587     raeburn  3213:             if ($in{'mode'} eq 'modifycourse') {
                   3214:                 if ($authnum == 1) {
1.1259    raeburn  3215:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3216:                 }
                   3217:             }
                   3218:         }
1.586     raeburn  3219:     }
                   3220:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3221:     if ($authtype eq '') {
                   3222:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3223:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3224:                     $krbcheck.$disabled.' />';
1.586     raeburn  3225:     }
                   3226:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3227:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3228:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3229:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3230:          $in{'curr_authtype'} eq 'krb4')) {
                   3231:         $result .= &mt
1.144     matthew  3232:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3233:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3234:          '<label>'.$authtype,
1.281     albertel 3235:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3236:              'value="'.$krbarg.'" '.
1.1259    raeburn  3237:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3238:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3239:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3240: 	 '</label>');
1.586     raeburn  3241:     } elsif ($can_assign{'krb4'}) {
                   3242:         $result .= &mt
                   3243:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3244:          '[_3] Version 4 [_4]',
                   3245:          '<label>'.$authtype,
                   3246:          '</label><input type="text" size="10" name="krbarg" '.
                   3247:              'value="'.$krbarg.'" '.
1.1259    raeburn  3248:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3249:          '<label><input type="hidden" name="krbver" value="4" />',
                   3250:          '</label>');
                   3251:     } elsif ($can_assign{'krb5'}) {
                   3252:         $result .= &mt
                   3253:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3254:          '[_3] Version 5 [_4]',
                   3255:          '<label>'.$authtype,
                   3256:          '</label><input type="text" size="10" name="krbarg" '.
                   3257:              'value="'.$krbarg.'" '.
1.1259    raeburn  3258:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3259:          '<label><input type="hidden" name="krbver" value="5" />',
                   3260:          '</label>');
                   3261:     }
1.32      matthew  3262:     return $result;
                   3263: }
                   3264: 
1.1106    raeburn  3265: sub authform_internal {
1.586     raeburn  3266:     my %in = (
1.32      matthew  3267:                 formname => 'document.cu',
                   3268:                 kerb_def_dom => 'MSU.EDU',
                   3269:                 @_,
                   3270:                 );
1.1259    raeburn  3271:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3272:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3273:     if ($in{'readonly'}) {
                   3274:         $disabled = ' disabled="disabled"';
                   3275:     }
1.591     raeburn  3276:     if (defined($in{'curr_authtype'})) {
                   3277:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3278:             if ($can_assign{'int'}) {
1.772     bisitz   3279:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3280:                 if (defined($in{'mode'})) {
                   3281:                     if ($in{'mode'} eq 'modifyuser') {
                   3282:                         $intcheck = '';
                   3283:                     }
                   3284:                 }
1.591     raeburn  3285:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3286:                     $intarg = $in{'curr_autharg'};
                   3287:                 }
                   3288:             } else {
                   3289:                 $result = &mt('Currently internally authenticated.');
                   3290:                 return $result;
1.165     raeburn  3291:             }
                   3292:         }
1.586     raeburn  3293:     } else {
                   3294:         if ($authnum == 1) {
1.784     bisitz   3295:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3296:         }
                   3297:     }
                   3298:     if (!$can_assign{'int'}) {
                   3299:         return;
1.587     raeburn  3300:     } elsif ($authtype eq '') {
1.591     raeburn  3301:         if (defined($in{'mode'})) {
1.587     raeburn  3302:             if ($in{'mode'} eq 'modifycourse') {
                   3303:                 if ($authnum == 1) {
1.1259    raeburn  3304:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3305:                 }
                   3306:             }
                   3307:         }
1.165     raeburn  3308:     }
1.586     raeburn  3309:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3310:     if ($authtype eq '') {
                   3311:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3312:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3313:     }
1.605     bisitz   3314:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3315:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3316:     $result = &mt
1.144     matthew  3317:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3318:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3319:     $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  3320:     return $result;
                   3321: }
                   3322: 
1.1104    raeburn  3323: sub authform_local {
1.32      matthew  3324:     my %in = (
                   3325:               formname => 'document.cu',
                   3326:               kerb_def_dom => 'MSU.EDU',
                   3327:               @_,
                   3328:               );
1.1259    raeburn  3329:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3330:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3331:     if ($in{'readonly'}) {
                   3332:         $disabled = ' disabled="disabled"';
                   3333:     } 
1.591     raeburn  3334:     if (defined($in{'curr_authtype'})) {
                   3335:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3336:             if ($can_assign{'loc'}) {
1.772     bisitz   3337:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3338:                 if (defined($in{'mode'})) {
                   3339:                     if ($in{'mode'} eq 'modifyuser') {
                   3340:                         $loccheck = '';
                   3341:                     }
                   3342:                 }
1.591     raeburn  3343:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3344:                     $locarg = $in{'curr_autharg'};
                   3345:                 }
                   3346:             } else {
                   3347:                 $result = &mt('Currently using local (institutional) authentication.');
                   3348:                 return $result;
1.165     raeburn  3349:             }
                   3350:         }
1.586     raeburn  3351:     } else {
                   3352:         if ($authnum == 1) {
1.784     bisitz   3353:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3354:         }
                   3355:     }
                   3356:     if (!$can_assign{'loc'}) {
                   3357:         return;
1.587     raeburn  3358:     } elsif ($authtype eq '') {
1.591     raeburn  3359:         if (defined($in{'mode'})) {
1.587     raeburn  3360:             if ($in{'mode'} eq 'modifycourse') {
                   3361:                 if ($authnum == 1) {
1.1259    raeburn  3362:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3363:                 }
                   3364:             }
                   3365:         }
1.165     raeburn  3366:     }
1.586     raeburn  3367:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3368:     if ($authtype eq '') {
                   3369:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3370:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3371:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3372:     }
                   3373:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3374:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3375:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3376:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3377:     return $result;
                   3378: }
                   3379: 
1.1106    raeburn  3380: sub authform_filesystem {
1.32      matthew  3381:     my %in = (
                   3382:               formname => 'document.cu',
                   3383:               kerb_def_dom => 'MSU.EDU',
                   3384:               @_,
                   3385:               );
1.1259    raeburn  3386:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3387:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3388:     if ($in{'readonly'}) {
                   3389:         $disabled = ' disabled="disabled"';
                   3390:     }
1.591     raeburn  3391:     if (defined($in{'curr_authtype'})) {
                   3392:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3393:             if ($can_assign{'fsys'}) {
1.772     bisitz   3394:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3395:                 if (defined($in{'mode'})) {
                   3396:                     if ($in{'mode'} eq 'modifyuser') {
                   3397:                         $fsyscheck = '';
                   3398:                     }
                   3399:                 }
1.586     raeburn  3400:             } else {
                   3401:                 $result = &mt('Currently Filesystem Authenticated.');
                   3402:                 return $result;
1.1259    raeburn  3403:             }
1.586     raeburn  3404:         }
                   3405:     } else {
                   3406:         if ($authnum == 1) {
1.784     bisitz   3407:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3408:         }
                   3409:     }
                   3410:     if (!$can_assign{'fsys'}) {
                   3411:         return;
1.587     raeburn  3412:     } elsif ($authtype eq '') {
1.591     raeburn  3413:         if (defined($in{'mode'})) {
1.587     raeburn  3414:             if ($in{'mode'} eq 'modifycourse') {
                   3415:                 if ($authnum == 1) {
1.1259    raeburn  3416:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3417:                 }
                   3418:             }
                   3419:         }
1.586     raeburn  3420:     }
                   3421:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3422:     if ($authtype eq '') {
                   3423:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3424:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3425:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3426:     }
                   3427:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3428:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3429:     $result = &mt
1.144     matthew  3430:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3431:          '<label><input type="radio" name="login" value="fsys" '.
1.1259    raeburn  3432:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
1.605     bisitz   3433:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.1259    raeburn  3434:                   'onchange="'.$jscall.'"'.$disabled.' />');
1.32      matthew  3435:     return $result;
                   3436: }
                   3437: 
1.586     raeburn  3438: sub get_assignable_auth {
                   3439:     my ($dom) = @_;
                   3440:     if ($dom eq '') {
                   3441:         $dom = $env{'request.role.domain'};
                   3442:     }
                   3443:     my %can_assign = (
                   3444:                           krb4 => 1,
                   3445:                           krb5 => 1,
                   3446:                           int  => 1,
                   3447:                           loc  => 1,
                   3448:                      );
                   3449:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3450:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3451:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3452:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3453:             my $context;
                   3454:             if ($env{'request.role'} =~ /^au/) {
                   3455:                 $context = 'author';
1.1259    raeburn  3456:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3457:                 $context = 'domain';
                   3458:             } elsif ($env{'request.course.id'}) {
                   3459:                 $context = 'course';
                   3460:             }
                   3461:             if ($context) {
                   3462:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3463:                    %can_assign = %{$authhash->{$context}}; 
                   3464:                 }
                   3465:             }
                   3466:         }
                   3467:     }
                   3468:     my $authnum = 0;
                   3469:     foreach my $key (keys(%can_assign)) {
                   3470:         if ($can_assign{$key}) {
                   3471:             $authnum ++;
                   3472:         }
                   3473:     }
                   3474:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3475:         $authnum --;
                   3476:     }
                   3477:     return ($authnum,%can_assign);
                   3478: }
                   3479: 
1.80      albertel 3480: ###############################################################
                   3481: ##    Get Kerberos Defaults for Domain                 ##
                   3482: ###############################################################
                   3483: ##
                   3484: ## Returns default kerberos version and an associated argument
                   3485: ## as listed in file domain.tab. If not listed, provides
                   3486: ## appropriate default domain and kerberos version.
                   3487: ##
                   3488: #-------------------------------------------
                   3489: 
                   3490: =pod
                   3491: 
1.648     raeburn  3492: =item * &get_kerberos_defaults()
1.80      albertel 3493: 
                   3494: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3495: version and domain. If not found, it defaults to version 4 and the 
                   3496: domain of the server.
1.80      albertel 3497: 
1.648     raeburn  3498: =over 4
                   3499: 
1.80      albertel 3500: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3501: 
1.648     raeburn  3502: =back
                   3503: 
                   3504: =back
                   3505: 
1.80      albertel 3506: =cut
                   3507: 
                   3508: #-------------------------------------------
                   3509: sub get_kerberos_defaults {
                   3510:     my $domain=shift;
1.641     raeburn  3511:     my ($krbdef,$krbdefdom);
                   3512:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3513:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3514:         $krbdef = $domdefaults{'auth_def'};
                   3515:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3516:     } else {
1.80      albertel 3517:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3518:         my $krbdefdom=$1;
                   3519:         $krbdefdom=~tr/a-z/A-Z/;
                   3520:         $krbdef = "krb4";
                   3521:     }
                   3522:     return ($krbdef,$krbdefdom);
                   3523: }
1.112     bowersj2 3524: 
1.32      matthew  3525: 
1.46      matthew  3526: ###############################################################
                   3527: ##                Thesaurus Functions                        ##
                   3528: ###############################################################
1.20      www      3529: 
1.46      matthew  3530: =pod
1.20      www      3531: 
1.112     bowersj2 3532: =head1 Thesaurus Functions
                   3533: 
                   3534: =over 4
                   3535: 
1.648     raeburn  3536: =item * &initialize_keywords()
1.46      matthew  3537: 
                   3538: Initializes the package variable %Keywords if it is empty.  Uses the
                   3539: package variable $thesaurus_db_file.
                   3540: 
                   3541: =cut
                   3542: 
                   3543: ###################################################
                   3544: 
                   3545: sub initialize_keywords {
                   3546:     return 1 if (scalar keys(%Keywords));
                   3547:     # If we are here, %Keywords is empty, so fill it up
                   3548:     #   Make sure the file we need exists...
                   3549:     if (! -e $thesaurus_db_file) {
                   3550:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3551:                                  " failed because it does not exist");
                   3552:         return 0;
                   3553:     }
                   3554:     #   Set up the hash as a database
                   3555:     my %thesaurus_db;
                   3556:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3557:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3558:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3559:                                  $thesaurus_db_file);
                   3560:         return 0;
                   3561:     } 
                   3562:     #  Get the average number of appearances of a word.
                   3563:     my $avecount = $thesaurus_db{'average.count'};
                   3564:     #  Put keywords (those that appear > average) into %Keywords
                   3565:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3566:         my ($count,undef) = split /:/,$data;
                   3567:         $Keywords{$word}++ if ($count > $avecount);
                   3568:     }
                   3569:     untie %thesaurus_db;
                   3570:     # Remove special values from %Keywords.
1.356     albertel 3571:     foreach my $value ('total.count','average.count') {
                   3572:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3573:   }
1.46      matthew  3574:     return 1;
                   3575: }
                   3576: 
                   3577: ###################################################
                   3578: 
                   3579: =pod
                   3580: 
1.648     raeburn  3581: =item * &keyword($word)
1.46      matthew  3582: 
                   3583: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3584: than the average number of times in the thesaurus database.  Calls 
                   3585: &initialize_keywords
                   3586: 
                   3587: =cut
                   3588: 
                   3589: ###################################################
1.20      www      3590: 
                   3591: sub keyword {
1.46      matthew  3592:     return if (!&initialize_keywords());
                   3593:     my $word=lc(shift());
                   3594:     $word=~s/\W//g;
                   3595:     return exists($Keywords{$word});
1.20      www      3596: }
1.46      matthew  3597: 
                   3598: ###############################################################
                   3599: 
                   3600: =pod 
1.20      www      3601: 
1.648     raeburn  3602: =item * &get_related_words()
1.46      matthew  3603: 
1.160     matthew  3604: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3605: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3606: will be returned.  The order of the words returned is determined by the
                   3607: database which holds them.
                   3608: 
                   3609: Uses global $thesaurus_db_file.
                   3610: 
1.1057    foxr     3611: 
1.46      matthew  3612: =cut
                   3613: 
                   3614: ###############################################################
                   3615: sub get_related_words {
                   3616:     my $keyword = shift;
                   3617:     my %thesaurus_db;
                   3618:     if (! -e $thesaurus_db_file) {
                   3619:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3620:                                  "failed because the file does not exist");
                   3621:         return ();
                   3622:     }
                   3623:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3624:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3625:         return ();
                   3626:     } 
                   3627:     my @Words=();
1.429     www      3628:     my $count=0;
1.46      matthew  3629:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3630: 	# The first element is the number of times
                   3631: 	# the word appears.  We do not need it now.
1.429     www      3632: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3633: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3634: 	my $threshold=$mostfrequentcount/10;
                   3635:         foreach my $possibleword (@RelatedWords) {
                   3636:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3637:             if ($wordcount>$threshold) {
                   3638: 		push(@Words,$word);
                   3639:                 $count++;
                   3640:                 if ($count>10) { last; }
                   3641: 	    }
1.20      www      3642:         }
                   3643:     }
1.46      matthew  3644:     untie %thesaurus_db;
                   3645:     return @Words;
1.14      harris41 3646: }
1.1090    foxr     3647: ###############################################################
                   3648: #
                   3649: #  Spell checking
                   3650: #
                   3651: 
                   3652: =pod
                   3653: 
1.1142    raeburn  3654: =back
                   3655: 
1.1090    foxr     3656: =head1 Spell checking
                   3657: 
                   3658: =over 4
                   3659: 
                   3660: =item * &check_spelling($wordlist $language)
                   3661: 
                   3662: Takes a string containing words and feeds it to an external
                   3663: spellcheck program via a pipeline. Returns a string containing
                   3664: them mis-spelled words.
                   3665: 
                   3666: Parameters:
                   3667: 
                   3668: =over 4
                   3669: 
                   3670: =item - $wordlist
                   3671: 
                   3672: String that will be fed into the spellcheck program.
                   3673: 
                   3674: =item - $language
                   3675: 
                   3676: Language string that specifies the language for which the spell
                   3677: check will be performed.
                   3678: 
                   3679: =back
                   3680: 
                   3681: =back
                   3682: 
                   3683: Note: This sub assumes that aspell is installed.
                   3684: 
                   3685: 
                   3686: =cut
                   3687: 
1.46      matthew  3688: 
1.1090    foxr     3689: sub check_spelling {
                   3690:     my ($wordlist, $language) = @_;
1.1091    foxr     3691:     my @misspellings;
                   3692:     
                   3693:     # Generate the speller and set the langauge.
                   3694:     # if explicitly selected:
1.1090    foxr     3695: 
1.1091    foxr     3696:     my $speller = Text::Aspell->new;
1.1090    foxr     3697:     if ($language) {
1.1091    foxr     3698: 	$speller->set_option('lang', $language);
1.1090    foxr     3699:     }
                   3700: 
1.1091    foxr     3701:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3702: 
1.1091    foxr     3703:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3704: 
1.1091    foxr     3705:     foreach my $word (@words) {
                   3706: 	if(! $speller->check($word)) {
                   3707: 	    push(@misspellings, $word);
1.1090    foxr     3708: 	}
                   3709:     }
1.1091    foxr     3710:     return join(' ', @misspellings);
                   3711:     
1.1090    foxr     3712: }
                   3713: 
1.61      www      3714: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3715: =pod
                   3716: 
1.112     bowersj2 3717: =head1 User Name Functions
                   3718: 
                   3719: =over 4
                   3720: 
1.648     raeburn  3721: =item * &plainname($uname,$udom,$first)
1.81      albertel 3722: 
1.112     bowersj2 3723: Takes a users logon name and returns it as a string in
1.226     albertel 3724: "first middle last generation" form 
                   3725: if $first is set to 'lastname' then it returns it as
                   3726: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3727: 
                   3728: =cut
1.61      www      3729: 
1.295     www      3730: 
1.81      albertel 3731: ###############################################################
1.61      www      3732: sub plainname {
1.226     albertel 3733:     my ($uname,$udom,$first)=@_;
1.537     albertel 3734:     return if (!defined($uname) || !defined($udom));
1.295     www      3735:     my %names=&getnames($uname,$udom);
1.226     albertel 3736:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3737: 					  $names{'middlename'},
                   3738: 					  $names{'lastname'},
                   3739: 					  $names{'generation'},$first);
                   3740:     $name=~s/^\s+//;
1.62      www      3741:     $name=~s/\s+$//;
                   3742:     $name=~s/\s+/ /g;
1.353     albertel 3743:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3744:     return $name;
1.61      www      3745: }
1.66      www      3746: 
                   3747: # -------------------------------------------------------------------- Nickname
1.81      albertel 3748: =pod
                   3749: 
1.648     raeburn  3750: =item * &nickname($uname,$udom)
1.81      albertel 3751: 
                   3752: Gets a users name and returns it as a string as
                   3753: 
                   3754: "&quot;nickname&quot;"
1.66      www      3755: 
1.81      albertel 3756: if the user has a nickname or
                   3757: 
                   3758: "first middle last generation"
                   3759: 
                   3760: if the user does not
                   3761: 
                   3762: =cut
1.66      www      3763: 
                   3764: sub nickname {
                   3765:     my ($uname,$udom)=@_;
1.537     albertel 3766:     return if (!defined($uname) || !defined($udom));
1.295     www      3767:     my %names=&getnames($uname,$udom);
1.68      albertel 3768:     my $name=$names{'nickname'};
1.66      www      3769:     if ($name) {
                   3770:        $name='&quot;'.$name.'&quot;'; 
                   3771:     } else {
                   3772:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3773: 	     $names{'lastname'}.' '.$names{'generation'};
                   3774:        $name=~s/\s+$//;
                   3775:        $name=~s/\s+/ /g;
                   3776:     }
                   3777:     return $name;
                   3778: }
                   3779: 
1.295     www      3780: sub getnames {
                   3781:     my ($uname,$udom)=@_;
1.537     albertel 3782:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3783:     if ($udom eq 'public' && $uname eq 'public') {
                   3784: 	return ('lastname' => &mt('Public'));
                   3785:     }
1.295     www      3786:     my $id=$uname.':'.$udom;
                   3787:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3788:     if ($cached) {
                   3789: 	return %{$names};
                   3790:     } else {
                   3791: 	my %loadnames=&Apache::lonnet::get('environment',
                   3792:                     ['firstname','middlename','lastname','generation','nickname'],
                   3793: 					 $udom,$uname);
                   3794: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3795: 	return %loadnames;
                   3796:     }
                   3797: }
1.61      www      3798: 
1.542     raeburn  3799: # -------------------------------------------------------------------- getemails
1.648     raeburn  3800: 
1.542     raeburn  3801: =pod
                   3802: 
1.648     raeburn  3803: =item * &getemails($uname,$udom)
1.542     raeburn  3804: 
                   3805: Gets a user's email information and returns it as a hash with keys:
                   3806: notification, critnotification, permanentemail
                   3807: 
                   3808: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3809: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3810:  
1.648     raeburn  3811: 
1.542     raeburn  3812: =cut
                   3813: 
1.648     raeburn  3814: 
1.466     albertel 3815: sub getemails {
                   3816:     my ($uname,$udom)=@_;
                   3817:     if ($udom eq 'public' && $uname eq 'public') {
                   3818: 	return;
                   3819:     }
1.467     www      3820:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3821:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3822:     my $id=$uname.':'.$udom;
                   3823:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3824:     if ($cached) {
                   3825: 	return %{$names};
                   3826:     } else {
                   3827: 	my %loadnames=&Apache::lonnet::get('environment',
                   3828:                     			   ['notification','critnotification',
                   3829: 					    'permanentemail'],
                   3830: 					   $udom,$uname);
                   3831: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3832: 	return %loadnames;
                   3833:     }
                   3834: }
                   3835: 
1.551     albertel 3836: sub flush_email_cache {
                   3837:     my ($uname,$udom)=@_;
                   3838:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3839:     if (!$uname) { $uname=$env{'user.name'};   }
                   3840:     return if ($udom eq 'public' && $uname eq 'public');
                   3841:     my $id=$uname.':'.$udom;
                   3842:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3843: }
                   3844: 
1.728     raeburn  3845: # -------------------------------------------------------------------- getlangs
                   3846: 
                   3847: =pod
                   3848: 
                   3849: =item * &getlangs($uname,$udom)
                   3850: 
                   3851: Gets a user's language preference and returns it as a hash with key:
                   3852: language.
                   3853: 
                   3854: =cut
                   3855: 
                   3856: 
                   3857: sub getlangs {
                   3858:     my ($uname,$udom) = @_;
                   3859:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3860:     if (!$uname) { $uname=$env{'user.name'};   }
                   3861:     my $id=$uname.':'.$udom;
                   3862:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3863:     if ($cached) {
                   3864:         return %{$langs};
                   3865:     } else {
                   3866:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3867:                                            $udom,$uname);
                   3868:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3869:         return %loadlangs;
                   3870:     }
                   3871: }
                   3872: 
                   3873: sub flush_langs_cache {
                   3874:     my ($uname,$udom)=@_;
                   3875:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3876:     if (!$uname) { $uname=$env{'user.name'};   }
                   3877:     return if ($udom eq 'public' && $uname eq 'public');
                   3878:     my $id=$uname.':'.$udom;
                   3879:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3880: }
                   3881: 
1.61      www      3882: # ------------------------------------------------------------------ Screenname
1.81      albertel 3883: 
                   3884: =pod
                   3885: 
1.648     raeburn  3886: =item * &screenname($uname,$udom)
1.81      albertel 3887: 
                   3888: Gets a users screenname and returns it as a string
                   3889: 
                   3890: =cut
1.61      www      3891: 
                   3892: sub screenname {
                   3893:     my ($uname,$udom)=@_;
1.258     albertel 3894:     if ($uname eq $env{'user.name'} &&
                   3895: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3896:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3897:     return $names{'screenname'};
1.62      www      3898: }
                   3899: 
1.212     albertel 3900: 
1.802     bisitz   3901: # ------------------------------------------------------------- Confirm Wrapper
                   3902: =pod
                   3903: 
1.1142    raeburn  3904: =item * &confirmwrapper($message)
1.802     bisitz   3905: 
                   3906: Wrap messages about completion of operation in box
                   3907: 
                   3908: =cut
                   3909: 
                   3910: sub confirmwrapper {
                   3911:     my ($message)=@_;
                   3912:     if ($message) {
                   3913:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3914:                .$message."\n"
                   3915:                .'</div>'."\n";
                   3916:     } else {
                   3917:         return $message;
                   3918:     }
                   3919: }
                   3920: 
1.62      www      3921: # ------------------------------------------------------------- Message Wrapper
                   3922: 
                   3923: sub messagewrapper {
1.369     www      3924:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3925:     return 
1.441     albertel 3926:         '<a href="/adm/email?compose=individual&amp;'.
                   3927:         'recname='.$username.'&amp;recdom='.$domain.
                   3928: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3929:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3930: }
1.802     bisitz   3931: 
1.74      www      3932: # --------------------------------------------------------------- Notes Wrapper
                   3933: 
                   3934: sub noteswrapper {
                   3935:     my ($link,$un,$do)=@_;
                   3936:     return 
1.896     amueller 3937: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3938: }
1.802     bisitz   3939: 
1.62      www      3940: # ------------------------------------------------------------- Aboutme Wrapper
                   3941: 
                   3942: sub aboutmewrapper {
1.1070    raeburn  3943:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3944:     if (!defined($username)  && !defined($domain)) {
                   3945:         return;
                   3946:     }
1.1096    raeburn  3947:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3948: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3949: }
                   3950: 
                   3951: # ------------------------------------------------------------ Syllabus Wrapper
                   3952: 
                   3953: sub syllabuswrapper {
1.707     bisitz   3954:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3955:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3956: }
1.14      harris41 3957: 
1.802     bisitz   3958: # -----------------------------------------------------------------------------
                   3959: 
1.208     matthew  3960: sub track_student_link {
1.887     raeburn  3961:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3962:     my $link ="/adm/trackstudent?";
1.208     matthew  3963:     my $title = 'View recent activity';
                   3964:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3965:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3966:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3967:         $title .= ' of this student';
1.268     albertel 3968:     } 
1.208     matthew  3969:     if (defined($target) && $target !~ /^\s*$/) {
                   3970:         $target = qq{target="$target"};
                   3971:     } else {
                   3972:         $target = '';
                   3973:     }
1.268     albertel 3974:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3975:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3976:     $title = &mt($title);
                   3977:     $linktext = &mt($linktext);
1.448     albertel 3978:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3979: 	&help_open_topic('View_recent_activity');
1.208     matthew  3980: }
                   3981: 
1.781     raeburn  3982: sub slot_reservations_link {
                   3983:     my ($linktext,$sname,$sdom,$target) = @_;
                   3984:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3985:     my $title = 'View slot reservation history';
                   3986:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3987:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3988:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3989:         $title .= ' of this student';
                   3990:     }
                   3991:     if (defined($target) && $target !~ /^\s*$/) {
                   3992:         $target = qq{target="$target"};
                   3993:     } else {
                   3994:         $target = '';
                   3995:     }
                   3996:     $title = &mt($title);
                   3997:     $linktext = &mt($linktext);
                   3998:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3999: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4000: 
                   4001: }
                   4002: 
1.508     www      4003: # ===================================================== Display a student photo
                   4004: 
                   4005: 
1.509     albertel 4006: sub student_image_tag {
1.508     www      4007:     my ($domain,$user)=@_;
                   4008:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4009:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4010: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4011:     } else {
                   4012: 	return '';
                   4013:     }
                   4014: }
                   4015: 
1.112     bowersj2 4016: =pod
                   4017: 
                   4018: =back
                   4019: 
                   4020: =head1 Access .tab File Data
                   4021: 
                   4022: =over 4
                   4023: 
1.648     raeburn  4024: =item * &languageids() 
1.112     bowersj2 4025: 
                   4026: returns list of all language ids
                   4027: 
                   4028: =cut
                   4029: 
1.14      harris41 4030: sub languageids {
1.16      harris41 4031:     return sort(keys(%language));
1.14      harris41 4032: }
                   4033: 
1.112     bowersj2 4034: =pod
                   4035: 
1.648     raeburn  4036: =item * &languagedescription() 
1.112     bowersj2 4037: 
                   4038: returns description of a specified language id
                   4039: 
                   4040: =cut
                   4041: 
1.14      harris41 4042: sub languagedescription {
1.125     www      4043:     my $code=shift;
                   4044:     return  ($supported_language{$code}?'* ':'').
                   4045:             $language{$code}.
1.126     www      4046: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4047: }
                   4048: 
1.1048    foxr     4049: =pod
                   4050: 
                   4051: =item * &plainlanguagedescription
                   4052: 
                   4053: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4054: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4055: 
                   4056: =cut
                   4057: 
1.145     www      4058: sub plainlanguagedescription {
                   4059:     my $code=shift;
                   4060:     return $language{$code};
                   4061: }
                   4062: 
1.1048    foxr     4063: =pod
                   4064: 
                   4065: =item * &supportedlanguagecode
                   4066: 
                   4067: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4068: code.
                   4069: 
                   4070: =cut
                   4071: 
1.145     www      4072: sub supportedlanguagecode {
                   4073:     my $code=shift;
                   4074:     return $supported_language{$code};
1.97      www      4075: }
                   4076: 
1.112     bowersj2 4077: =pod
                   4078: 
1.1048    foxr     4079: =item * &latexlanguage()
                   4080: 
                   4081: Given a language key code returns the correspondnig language to use
                   4082: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4083: is no supported hyphenation for the language code.
                   4084: 
                   4085: =cut
                   4086: 
                   4087: sub latexlanguage {
                   4088:     my $code = shift;
                   4089:     return $latex_language{$code};
                   4090: }
                   4091: 
                   4092: =pod
                   4093: 
                   4094: =item * &latexhyphenation()
                   4095: 
                   4096: Same as above but what's supplied is the language as it might be stored
                   4097: in the metadata.
                   4098: 
                   4099: =cut
                   4100: 
                   4101: sub latexhyphenation {
                   4102:     my $key = shift;
                   4103:     return $latex_language_bykey{$key};
                   4104: }
                   4105: 
                   4106: =pod
                   4107: 
1.648     raeburn  4108: =item * &copyrightids() 
1.112     bowersj2 4109: 
                   4110: returns list of all copyrights
                   4111: 
                   4112: =cut
                   4113: 
                   4114: sub copyrightids {
                   4115:     return sort(keys(%cprtag));
                   4116: }
                   4117: 
                   4118: =pod
                   4119: 
1.648     raeburn  4120: =item * &copyrightdescription() 
1.112     bowersj2 4121: 
                   4122: returns description of a specified copyright id
                   4123: 
                   4124: =cut
                   4125: 
                   4126: sub copyrightdescription {
1.166     www      4127:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4128: }
1.197     matthew  4129: 
                   4130: =pod
                   4131: 
1.648     raeburn  4132: =item * &source_copyrightids() 
1.192     taceyjo1 4133: 
                   4134: returns list of all source copyrights
                   4135: 
                   4136: =cut
                   4137: 
                   4138: sub source_copyrightids {
                   4139:     return sort(keys(%scprtag));
                   4140: }
                   4141: 
                   4142: =pod
                   4143: 
1.648     raeburn  4144: =item * &source_copyrightdescription() 
1.192     taceyjo1 4145: 
                   4146: returns description of a specified source copyright id
                   4147: 
                   4148: =cut
                   4149: 
                   4150: sub source_copyrightdescription {
                   4151:     return &mt($scprtag{shift(@_)});
                   4152: }
1.112     bowersj2 4153: 
                   4154: =pod
                   4155: 
1.648     raeburn  4156: =item * &filecategories() 
1.112     bowersj2 4157: 
                   4158: returns list of all file categories
                   4159: 
                   4160: =cut
                   4161: 
                   4162: sub filecategories {
                   4163:     return sort(keys(%category_extensions));
                   4164: }
                   4165: 
                   4166: =pod
                   4167: 
1.648     raeburn  4168: =item * &filecategorytypes() 
1.112     bowersj2 4169: 
                   4170: returns list of file types belonging to a given file
                   4171: category
                   4172: 
                   4173: =cut
                   4174: 
                   4175: sub filecategorytypes {
1.356     albertel 4176:     my ($cat) = @_;
1.1248    raeburn  4177:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4178:         return @{$category_extensions{lc($cat)}};
                   4179:     } else {
                   4180:         return ();
                   4181:     }
1.112     bowersj2 4182: }
                   4183: 
                   4184: =pod
                   4185: 
1.648     raeburn  4186: =item * &fileembstyle() 
1.112     bowersj2 4187: 
                   4188: returns embedding style for a specified file type
                   4189: 
                   4190: =cut
                   4191: 
                   4192: sub fileembstyle {
                   4193:     return $fe{lc(shift(@_))};
1.169     www      4194: }
                   4195: 
1.351     www      4196: sub filemimetype {
                   4197:     return $fm{lc(shift(@_))};
                   4198: }
                   4199: 
1.169     www      4200: 
                   4201: sub filecategoryselect {
                   4202:     my ($name,$value)=@_;
1.189     matthew  4203:     return &select_form($value,$name,
1.970     raeburn  4204:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4205: }
                   4206: 
                   4207: =pod
                   4208: 
1.648     raeburn  4209: =item * &filedescription() 
1.112     bowersj2 4210: 
                   4211: returns description for a specified file type
                   4212: 
                   4213: =cut
                   4214: 
                   4215: sub filedescription {
1.188     matthew  4216:     my $file_description = $fd{lc(shift())};
                   4217:     $file_description =~ s:([\[\]]):~$1:g;
                   4218:     return &mt($file_description);
1.112     bowersj2 4219: }
                   4220: 
                   4221: =pod
                   4222: 
1.648     raeburn  4223: =item * &filedescriptionex() 
1.112     bowersj2 4224: 
                   4225: returns description for a specified file type with
                   4226: extra formatting
                   4227: 
                   4228: =cut
                   4229: 
                   4230: sub filedescriptionex {
                   4231:     my $ex=shift;
1.188     matthew  4232:     my $file_description = $fd{lc($ex)};
                   4233:     $file_description =~ s:([\[\]]):~$1:g;
                   4234:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4235: }
                   4236: 
                   4237: # End of .tab access
                   4238: =pod
                   4239: 
                   4240: =back
                   4241: 
                   4242: =cut
                   4243: 
                   4244: # ------------------------------------------------------------------ File Types
                   4245: sub fileextensions {
                   4246:     return sort(keys(%fe));
                   4247: }
                   4248: 
1.97      www      4249: # ----------------------------------------------------------- Display Languages
                   4250: # returns a hash with all desired display languages
                   4251: #
                   4252: 
                   4253: sub display_languages {
                   4254:     my %languages=();
1.695     raeburn  4255:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4256: 	$languages{$lang}=1;
1.97      www      4257:     }
                   4258:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4259:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4260: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4261: 	    $languages{$lang}=1;
1.97      www      4262:         }
                   4263:     }
                   4264:     return %languages;
1.14      harris41 4265: }
                   4266: 
1.582     albertel 4267: sub languages {
                   4268:     my ($possible_langs) = @_;
1.695     raeburn  4269:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4270:     if (!ref($possible_langs)) {
                   4271: 	if( wantarray ) {
                   4272: 	    return @preferred_langs;
                   4273: 	} else {
                   4274: 	    return $preferred_langs[0];
                   4275: 	}
                   4276:     }
                   4277:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4278:     my @preferred_possibilities;
                   4279:     foreach my $preferred_lang (@preferred_langs) {
                   4280: 	if (exists($possibilities{$preferred_lang})) {
                   4281: 	    push(@preferred_possibilities, $preferred_lang);
                   4282: 	}
                   4283:     }
                   4284:     if( wantarray ) {
                   4285: 	return @preferred_possibilities;
                   4286:     }
                   4287:     return $preferred_possibilities[0];
                   4288: }
                   4289: 
1.742     raeburn  4290: sub user_lang {
                   4291:     my ($touname,$toudom,$fromcid) = @_;
                   4292:     my @userlangs;
                   4293:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4294:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4295:                     $env{'course.'.$fromcid.'.languages'}));
                   4296:     } else {
                   4297:         my %langhash = &getlangs($touname,$toudom);
                   4298:         if ($langhash{'languages'} ne '') {
                   4299:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4300:         } else {
                   4301:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4302:             if ($domdefs{'lang_def'} ne '') {
                   4303:                 @userlangs = ($domdefs{'lang_def'});
                   4304:             }
                   4305:         }
                   4306:     }
                   4307:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4308:     my $user_lh = Apache::localize->get_handle(@languages);
                   4309:     return $user_lh;
                   4310: }
                   4311: 
                   4312: 
1.112     bowersj2 4313: ###############################################################
                   4314: ##               Student Answer Attempts                     ##
                   4315: ###############################################################
                   4316: 
                   4317: =pod
                   4318: 
                   4319: =head1 Alternate Problem Views
                   4320: 
                   4321: =over 4
                   4322: 
1.648     raeburn  4323: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4324:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4325: 
                   4326: Return string with previous attempt on problem. Arguments:
                   4327: 
                   4328: =over 4
                   4329: 
                   4330: =item * $symb: Problem, including path
                   4331: 
                   4332: =item * $username: username of the desired student
                   4333: 
                   4334: =item * $domain: domain of the desired student
1.14      harris41 4335: 
1.112     bowersj2 4336: =item * $course: Course ID
1.14      harris41 4337: 
1.112     bowersj2 4338: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4339:     something
1.14      harris41 4340: 
1.112     bowersj2 4341: =item * $regexp: if string matches this regexp, the string will be
                   4342:     sent to $gradesub
1.14      harris41 4343: 
1.112     bowersj2 4344: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4345: 
1.1199    raeburn  4346: =item * $usec: section of the desired student
                   4347: 
                   4348: =item * $identifier: counter for student (multiple students one problem) or 
                   4349:     problem (one student; whole sequence).
                   4350: 
1.112     bowersj2 4351: =back
1.14      harris41 4352: 
1.112     bowersj2 4353: The output string is a table containing all desired attempts, if any.
1.16      harris41 4354: 
1.112     bowersj2 4355: =cut
1.1       albertel 4356: 
                   4357: sub get_previous_attempt {
1.1199    raeburn  4358:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4359:   my $prevattempts='';
1.43      ng       4360:   no strict 'refs';
1.1       albertel 4361:   if ($symb) {
1.3       albertel 4362:     my (%returnhash)=
                   4363:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4364:     if ($returnhash{'version'}) {
                   4365:       my %lasthash=();
                   4366:       my $version;
                   4367:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4368:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4369:             if ($key =~ /\.rawrndseed$/) {
                   4370:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4371:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4372:             } else {
                   4373:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4374:             }
1.19      harris41 4375:         }
1.1       albertel 4376:       }
1.596     albertel 4377:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4378:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4379:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4380:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4381:       foreach my $key (sort(keys(%lasthash))) {
                   4382: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4383: 	if ($#parts > 0) {
1.31      albertel 4384: 	  my $data=$parts[-1];
1.989     raeburn  4385:           next if ($data eq 'foilorder');
1.31      albertel 4386: 	  pop(@parts);
1.1010    www      4387:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4388:           if ($data eq 'type') {
                   4389:               unless ($showsurv) {
                   4390:                   my $id = join(',',@parts);
                   4391:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4392:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4393:                       $lasthidden{$ign.'.'.$id} = 1;
                   4394:                   }
1.945     raeburn  4395:               }
1.1199    raeburn  4396:               if ($identifier ne '') {
                   4397:                   my $id = join(',',@parts);
                   4398:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4399:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4400:                       $hidestatus{$ign.'.'.$id} = 1;
                   4401:                   }
                   4402:               }
                   4403:           } elsif ($data eq 'regrader') {
                   4404:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4405:                   my $id = join(',',@parts);
                   4406:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4407:               }
1.1010    www      4408:           } 
1.31      albertel 4409: 	} else {
1.41      ng       4410: 	  if ($#parts == 0) {
                   4411: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4412: 	  } else {
                   4413: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4414: 	  }
1.31      albertel 4415: 	}
1.16      harris41 4416:       }
1.596     albertel 4417:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4418:       if ($getattempt eq '') {
1.1199    raeburn  4419:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4420:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4421:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4422:                 foreach my $id (keys(%regraded)) {
                   4423:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4424:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4425:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4426:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4427:                     }
                   4428:                 }
                   4429:             }
1.1200    raeburn  4430:         }
                   4431: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4432:             my (@hidden,@unsolved);
1.945     raeburn  4433:             if (%typeparts) {
                   4434:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4435:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4436:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4437:                         push(@hidden,$id);
1.1199    raeburn  4438:                     } elsif ($identifier ne '') {
                   4439:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4440:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4441:                                 ($hidestatus{$id})) {
1.1200    raeburn  4442:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4443:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4444:                                 push(@{$solved{$id}},$version);
                   4445:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4446:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4447:                                 my $skip;
                   4448:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4449:                                     foreach my $reset (@{$resets{$id}}) {
                   4450:                                         if ($reset > $solved{$id}[-1]) {
                   4451:                                             $skip=1;
                   4452:                                             last;
                   4453:                                         }
                   4454:                                     }
                   4455:                                 }
                   4456:                                 unless ($skip) {
                   4457:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4458:                                     push(@unsolved,$partslist);
                   4459:                                 }
                   4460:                             }
                   4461:                         }
1.945     raeburn  4462:                     }
                   4463:                 }
                   4464:             }
                   4465:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4466:                            '<td>'.&mt('Transaction [_1]',$version);
                   4467:             if (@unsolved) {
                   4468:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4469:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4470:                                  &mt('Hide').'</label></span>';
                   4471:             }
                   4472:             $prevattempts .= '</td>';
1.945     raeburn  4473:             if (@hidden) {
                   4474:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4475:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4476:                     my $hide;
                   4477:                     foreach my $id (@hidden) {
                   4478:                         if ($key =~ /^\Q$id\E/) {
                   4479:                             $hide = 1;
                   4480:                             last;
                   4481:                         }
                   4482:                     }
                   4483:                     if ($hide) {
                   4484:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4485:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4486:                             my $value = &format_previous_attempt_value($key,
                   4487:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4488:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4489:                         } else {
                   4490:                             $prevattempts.='<td>&nbsp;</td>';
                   4491:                         }
                   4492:                     } else {
                   4493:                         if ($key =~ /\./) {
1.1212    raeburn  4494:                             my $value = $returnhash{$version.':'.$key};
                   4495:                             if ($key =~ /\.rndseed$/) {
                   4496:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4497:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4498:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4499:                                 }
                   4500:                             }
                   4501:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4502:                                            '&nbsp;</td>';
1.945     raeburn  4503:                         } else {
                   4504:                             $prevattempts.='<td>&nbsp;</td>';
                   4505:                         }
                   4506:                     }
                   4507:                 }
                   4508:             } else {
                   4509: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4510:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4511:                     my $value = $returnhash{$version.':'.$key};
                   4512:                     if ($key =~ /\.rndseed$/) {
                   4513:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4514:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4515:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4516:                         }
                   4517:                     }
                   4518:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4519:                                    '&nbsp;</td>';
1.945     raeburn  4520: 	        }
                   4521:             }
                   4522: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4523: 	 }
1.1       albertel 4524:       }
1.945     raeburn  4525:       my @currhidden = keys(%lasthidden);
1.596     albertel 4526:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4527:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4528:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4529:           if (%typeparts) {
                   4530:               my $hidden;
                   4531:               foreach my $id (@currhidden) {
                   4532:                   if ($key =~ /^\Q$id\E/) {
                   4533:                       $hidden = 1;
                   4534:                       last;
                   4535:                   }
                   4536:               }
                   4537:               if ($hidden) {
                   4538:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4539:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4540:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4541:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4542:                           $value = &$gradesub($value);
                   4543:                       }
1.1173    kruse    4544:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4545:                   } else {
                   4546:                       $prevattempts.='<td>&nbsp;</td>';
                   4547:                   }
                   4548:               } else {
                   4549:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4550:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4551:                       $value = &$gradesub($value);
                   4552:                   }
1.1173    kruse    4553:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4554:               }
                   4555:           } else {
                   4556: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4557: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4558:                   $value = &$gradesub($value);
                   4559:               }
1.1173    kruse    4560: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4561:           }
1.16      harris41 4562:       }
1.596     albertel 4563:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4564:     } else {
1.596     albertel 4565:       $prevattempts=
                   4566: 	  &start_data_table().&start_data_table_row().
                   4567: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4568: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4569:     }
                   4570:   } else {
1.596     albertel 4571:     $prevattempts=
                   4572: 	  &start_data_table().&start_data_table_row().
                   4573: 	  '<td>'.&mt('No data.').'</td>'.
                   4574: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4575:   }
1.10      albertel 4576: }
                   4577: 
1.581     albertel 4578: sub format_previous_attempt_value {
                   4579:     my ($key,$value) = @_;
1.1011    www      4580:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4581:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4582:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4583:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4584:     } elsif ($key =~ /answerstring$/) {
                   4585:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4586:         my @answer = %answers;
                   4587:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4588:         my @anskeys = sort(keys(%answers));
                   4589:         if (@anskeys == 1) {
                   4590:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4591:             if ($answer =~ m{\0}) {
                   4592:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4593:             }
                   4594:             my $tag_internal_answer_name = 'INTERNAL';
                   4595:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4596:                 $value = $answer; 
                   4597:             } else {
                   4598:                 $value = $anskeys[0].'='.$answer;
                   4599:             }
                   4600:         } else {
                   4601:             foreach my $ans (@anskeys) {
                   4602:                 my $answer = $answers{$ans};
1.1001    raeburn  4603:                 if ($answer =~ m{\0}) {
                   4604:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4605:                 }
                   4606:                 $value .=  $ans.'='.$answer.'<br />';;
                   4607:             } 
                   4608:         }
1.581     albertel 4609:     } else {
1.1173    kruse    4610:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4611:     }
                   4612:     return $value;
                   4613: }
                   4614: 
                   4615: 
1.107     albertel 4616: sub relative_to_absolute {
                   4617:     my ($url,$output)=@_;
                   4618:     my $parser=HTML::TokeParser->new(\$output);
                   4619:     my $token;
                   4620:     my $thisdir=$url;
                   4621:     my @rlinks=();
                   4622:     while ($token=$parser->get_token) {
                   4623: 	if ($token->[0] eq 'S') {
                   4624: 	    if ($token->[1] eq 'a') {
                   4625: 		if ($token->[2]->{'href'}) {
                   4626: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4627: 		}
                   4628: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4629: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4630: 	    } elsif ($token->[1] eq 'base') {
                   4631: 		$thisdir=$token->[2]->{'href'};
                   4632: 	    }
                   4633: 	}
                   4634:     }
                   4635:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4636:     foreach my $link (@rlinks) {
1.726     raeburn  4637: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4638: 		($link=~/^\//) ||
                   4639: 		($link=~/^javascript:/i) ||
                   4640: 		($link=~/^mailto:/i) ||
                   4641: 		($link=~/^\#/)) {
                   4642: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4643: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4644: 	}
                   4645:     }
                   4646: # -------------------------------------------------- Deal with Applet codebases
                   4647:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4648:     return $output;
                   4649: }
                   4650: 
1.112     bowersj2 4651: =pod
                   4652: 
1.648     raeburn  4653: =item * &get_student_view()
1.112     bowersj2 4654: 
                   4655: show a snapshot of what student was looking at
                   4656: 
                   4657: =cut
                   4658: 
1.10      albertel 4659: sub get_student_view {
1.186     albertel 4660:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4661:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4662:   my (%form);
1.10      albertel 4663:   my @elements=('symb','courseid','domain','username');
                   4664:   foreach my $element (@elements) {
1.186     albertel 4665:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4666:   }
1.186     albertel 4667:   if (defined($moreenv)) {
                   4668:       %form=(%form,%{$moreenv});
                   4669:   }
1.236     albertel 4670:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4671:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4672:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4673:   $userview=~s/\<body[^\>]*\>//gi;
                   4674:   $userview=~s/\<\/body\>//gi;
                   4675:   $userview=~s/\<html\>//gi;
                   4676:   $userview=~s/\<\/html\>//gi;
                   4677:   $userview=~s/\<head\>//gi;
                   4678:   $userview=~s/\<\/head\>//gi;
                   4679:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4680:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4681:   if (wantarray) {
                   4682:      return ($userview,$response);
                   4683:   } else {
                   4684:      return $userview;
                   4685:   }
                   4686: }
                   4687: 
                   4688: sub get_student_view_with_retries {
                   4689:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4690: 
                   4691:     my $ok = 0;                 # True if we got a good response.
                   4692:     my $content;
                   4693:     my $response;
                   4694: 
                   4695:     # Try to get the student_view done. within the retries count:
                   4696:     
                   4697:     do {
                   4698:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4699:          $ok      = $response->is_success;
                   4700:          if (!$ok) {
                   4701:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4702:          }
                   4703:          $retries--;
                   4704:     } while (!$ok && ($retries > 0));
                   4705:     
                   4706:     if (!$ok) {
                   4707:        $content = '';          # On error return an empty content.
                   4708:     }
1.651     www      4709:     if (wantarray) {
                   4710:        return ($content, $response);
                   4711:     } else {
                   4712:        return $content;
                   4713:     }
1.11      albertel 4714: }
                   4715: 
1.112     bowersj2 4716: =pod
                   4717: 
1.648     raeburn  4718: =item * &get_student_answers() 
1.112     bowersj2 4719: 
                   4720: show a snapshot of how student was answering problem
                   4721: 
                   4722: =cut
                   4723: 
1.11      albertel 4724: sub get_student_answers {
1.100     sakharuk 4725:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4726:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4727:   my (%moreenv);
1.11      albertel 4728:   my @elements=('symb','courseid','domain','username');
                   4729:   foreach my $element (@elements) {
1.186     albertel 4730:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4731:   }
1.186     albertel 4732:   $moreenv{'grade_target'}='answer';
                   4733:   %moreenv=(%form,%moreenv);
1.497     raeburn  4734:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4735:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4736:   return $userview;
1.1       albertel 4737: }
1.116     albertel 4738: 
                   4739: =pod
                   4740: 
                   4741: =item * &submlink()
                   4742: 
1.242     albertel 4743: Inputs: $text $uname $udom $symb $target
1.116     albertel 4744: 
                   4745: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4746: 
                   4747: =cut
                   4748: 
                   4749: ###############################################
                   4750: sub submlink {
1.242     albertel 4751:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4752:     if (!($uname && $udom)) {
                   4753: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4754: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4755: 	if (!$symb) { $symb=$cursymb; }
                   4756:     }
1.254     matthew  4757:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4758:     $symb=&escape($symb);
1.960     bisitz   4759:     if ($target) { $target=" target=\"$target\""; }
                   4760:     return
                   4761:         '<a href="/adm/grades?command=submission'.
                   4762:         '&amp;symb='.$symb.
                   4763:         '&amp;student='.$uname.
                   4764:         '&amp;userdom='.$udom.'"'.
                   4765:         $target.'>'.$text.'</a>';
1.242     albertel 4766: }
                   4767: ##############################################
                   4768: 
                   4769: =pod
                   4770: 
                   4771: =item * &pgrdlink()
                   4772: 
                   4773: Inputs: $text $uname $udom $symb $target
                   4774: 
                   4775: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4776: 
                   4777: =cut
                   4778: 
                   4779: ###############################################
                   4780: sub pgrdlink {
                   4781:     my $link=&submlink(@_);
                   4782:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4783:     return $link;
                   4784: }
                   4785: ##############################################
                   4786: 
                   4787: =pod
                   4788: 
                   4789: =item * &pprmlink()
                   4790: 
                   4791: Inputs: $text $uname $udom $symb $target
                   4792: 
                   4793: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4794: student and a specific resource
1.242     albertel 4795: 
                   4796: =cut
                   4797: 
                   4798: ###############################################
                   4799: sub pprmlink {
                   4800:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4801:     if (!($uname && $udom)) {
                   4802: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4803: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4804: 	if (!$symb) { $symb=$cursymb; }
                   4805:     }
1.254     matthew  4806:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4807:     $symb=&escape($symb);
1.242     albertel 4808:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4809:     return '<a href="/adm/parmset?command=set&amp;'.
                   4810: 	'symb='.$symb.'&amp;uname='.$uname.
                   4811: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4812: }
                   4813: ##############################################
1.37      matthew  4814: 
1.112     bowersj2 4815: =pod
                   4816: 
                   4817: =back
                   4818: 
                   4819: =cut
                   4820: 
1.37      matthew  4821: ###############################################
1.51      www      4822: 
                   4823: 
                   4824: sub timehash {
1.687     raeburn  4825:     my ($thistime) = @_;
                   4826:     my $timezone = &Apache::lonlocal::gettimezone();
                   4827:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4828:                      ->set_time_zone($timezone);
                   4829:     my $wday = $dt->day_of_week();
                   4830:     if ($wday == 7) { $wday = 0; }
                   4831:     return ( 'second' => $dt->second(),
                   4832:              'minute' => $dt->minute(),
                   4833:              'hour'   => $dt->hour(),
                   4834:              'day'     => $dt->day_of_month(),
                   4835:              'month'   => $dt->month(),
                   4836:              'year'    => $dt->year(),
                   4837:              'weekday' => $wday,
                   4838:              'dayyear' => $dt->day_of_year(),
                   4839:              'dlsav'   => $dt->is_dst() );
1.51      www      4840: }
                   4841: 
1.370     www      4842: sub utc_string {
                   4843:     my ($date)=@_;
1.371     www      4844:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4845: }
                   4846: 
1.51      www      4847: sub maketime {
                   4848:     my %th=@_;
1.687     raeburn  4849:     my ($epoch_time,$timezone,$dt);
                   4850:     $timezone = &Apache::lonlocal::gettimezone();
                   4851:     eval {
                   4852:         $dt = DateTime->new( year   => $th{'year'},
                   4853:                              month  => $th{'month'},
                   4854:                              day    => $th{'day'},
                   4855:                              hour   => $th{'hour'},
                   4856:                              minute => $th{'minute'},
                   4857:                              second => $th{'second'},
                   4858:                              time_zone => $timezone,
                   4859:                          );
                   4860:     };
                   4861:     if (!$@) {
                   4862:         $epoch_time = $dt->epoch;
                   4863:         if ($epoch_time) {
                   4864:             return $epoch_time;
                   4865:         }
                   4866:     }
1.51      www      4867:     return POSIX::mktime(
                   4868:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4869:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4870: }
                   4871: 
                   4872: #########################################
1.51      www      4873: 
                   4874: sub findallcourses {
1.482     raeburn  4875:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4876:     my %roles;
                   4877:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4878:     my %courses;
1.51      www      4879:     my $now=time;
1.482     raeburn  4880:     if (!defined($uname)) {
                   4881:         $uname = $env{'user.name'};
                   4882:     }
                   4883:     if (!defined($udom)) {
                   4884:         $udom = $env{'user.domain'};
                   4885:     }
                   4886:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4887:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4888:         if (!%roles) {
                   4889:             %roles = (
                   4890:                        cc => 1,
1.907     raeburn  4891:                        co => 1,
1.482     raeburn  4892:                        in => 1,
                   4893:                        ep => 1,
                   4894:                        ta => 1,
                   4895:                        cr => 1,
                   4896:                        st => 1,
                   4897:              );
                   4898:         }
                   4899:         foreach my $entry (keys(%roleshash)) {
                   4900:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4901:             if ($trole =~ /^cr/) { 
                   4902:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4903:             } else {
                   4904:                 next if (!exists($roles{$trole}));
                   4905:             }
                   4906:             if ($tend) {
                   4907:                 next if ($tend < $now);
                   4908:             }
                   4909:             if ($tstart) {
                   4910:                 next if ($tstart > $now);
                   4911:             }
1.1058    raeburn  4912:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4913:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4914:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4915:             if ($secpart eq '') {
                   4916:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4917:                 $sec = 'none';
1.1058    raeburn  4918:                 $value .= $cnum.'/';
1.482     raeburn  4919:             } else {
                   4920:                 $cnum = $cnumpart;
                   4921:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4922:                 $value .= $cnum.'/'.$sec;
                   4923:             }
                   4924:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4925:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4926:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4927:                 }
                   4928:             } else {
                   4929:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4930:             }
1.482     raeburn  4931:         }
                   4932:     } else {
                   4933:         foreach my $key (keys(%env)) {
1.483     albertel 4934: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4935:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4936: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4937: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4938: 	        next if (%roles && !exists($roles{$role}));
                   4939: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4940:                 my $active=1;
                   4941:                 if ($starttime) {
                   4942: 		    if ($now<$starttime) { $active=0; }
                   4943:                 }
                   4944:                 if ($endtime) {
                   4945:                     if ($now>$endtime) { $active=0; }
                   4946:                 }
                   4947:                 if ($active) {
1.1058    raeburn  4948:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4949:                     if ($sec eq '') {
                   4950:                         $sec = 'none';
1.1058    raeburn  4951:                     } else {
                   4952:                         $value .= $sec;
                   4953:                     }
                   4954:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4955:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4956:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4957:                         }
                   4958:                     } else {
                   4959:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4960:                     }
1.474     raeburn  4961:                 }
                   4962:             }
1.51      www      4963:         }
                   4964:     }
1.474     raeburn  4965:     return %courses;
1.51      www      4966: }
1.37      matthew  4967: 
1.54      www      4968: ###############################################
1.474     raeburn  4969: 
                   4970: sub blockcheck {
1.1189    raeburn  4971:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4972: 
1.1189    raeburn  4973:     if (defined($udom) && defined($uname)) {
                   4974:         # If uname and udom are for a course, check for blocks in the course.
                   4975:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4976:             my ($startblock,$endblock,$triggerblock) =
                   4977:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4978:             return ($startblock,$endblock,$triggerblock);
                   4979:         }
                   4980:     } else {
1.490     raeburn  4981:         $udom = $env{'user.domain'};
                   4982:         $uname = $env{'user.name'};
                   4983:     }
                   4984: 
1.502     raeburn  4985:     my $startblock = 0;
                   4986:     my $endblock = 0;
1.1062    raeburn  4987:     my $triggerblock = '';
1.482     raeburn  4988:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4989: 
1.490     raeburn  4990:     # If uname is for a user, and activity is course-specific, i.e.,
                   4991:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4992: 
1.490     raeburn  4993:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1189    raeburn  4994:          $activity eq 'groups' || $activity eq 'printout') &&
                   4995:         ($env{'request.course.id'})) {
1.490     raeburn  4996:         foreach my $key (keys(%live_courses)) {
                   4997:             if ($key ne $env{'request.course.id'}) {
                   4998:                 delete($live_courses{$key});
                   4999:             }
                   5000:         }
                   5001:     }
                   5002: 
                   5003:     my $otheruser = 0;
                   5004:     my %own_courses;
                   5005:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5006:         # Resource belongs to user other than current user.
                   5007:         $otheruser = 1;
                   5008:         # Gather courses for current user
                   5009:         %own_courses = 
                   5010:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5011:     }
                   5012: 
                   5013:     # Gather active course roles - course coordinator, instructor, 
                   5014:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5015: 
                   5016:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5017:         my ($cdom,$cnum);
                   5018:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5019:             $cdom = $env{'course.'.$course.'.domain'};
                   5020:             $cnum = $env{'course.'.$course.'.num'};
                   5021:         } else {
1.490     raeburn  5022:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5023:         }
                   5024:         my $no_ownblock = 0;
                   5025:         my $no_userblock = 0;
1.533     raeburn  5026:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5027:             # Check if current user has 'evb' priv for this
                   5028:             if (defined($own_courses{$course})) {
                   5029:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5030:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5031:                     if ($sec ne 'none') {
                   5032:                         $checkrole .= '/'.$sec;
                   5033:                     }
                   5034:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5035:                         $no_ownblock = 1;
                   5036:                         last;
                   5037:                     }
                   5038:                 }
                   5039:             }
                   5040:             # if they have 'evb' priv and are currently not playing student
                   5041:             next if (($no_ownblock) &&
                   5042:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5043:         }
1.474     raeburn  5044:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5045:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5046:             if ($sec ne 'none') {
1.482     raeburn  5047:                 $checkrole .= '/'.$sec;
1.474     raeburn  5048:             }
1.490     raeburn  5049:             if ($otheruser) {
                   5050:                 # Resource belongs to user other than current user.
                   5051:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5052:                 my (%allroles,%userroles);
                   5053:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5054:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5055:                         my ($trole,$tdom,$tnum,$tsec);
                   5056:                         if ($entry =~ /^cr/) {
                   5057:                             ($trole,$tdom,$tnum,$tsec) = 
                   5058:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5059:                         } else {
                   5060:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5061:                         }
                   5062:                         my ($spec,$area,$trest);
                   5063:                         $area = '/'.$tdom.'/'.$tnum;
                   5064:                         $trest = $tnum;
                   5065:                         if ($tsec ne '') {
                   5066:                             $area .= '/'.$tsec;
                   5067:                             $trest .= '/'.$tsec;
                   5068:                         }
                   5069:                         $spec = $trole.'.'.$area;
                   5070:                         if ($trole =~ /^cr/) {
                   5071:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5072:                                                               $tdom,$spec,$trest,$area);
                   5073:                         } else {
                   5074:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5075:                                                                 $tdom,$spec,$trest,$area);
                   5076:                         }
                   5077:                     }
1.1276    raeburn  5078:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5079:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5080:                         if ($1) {
                   5081:                             $no_userblock = 1;
                   5082:                             last;
                   5083:                         }
1.486     raeburn  5084:                     }
                   5085:                 }
1.490     raeburn  5086:             } else {
                   5087:                 # Resource belongs to current user
                   5088:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5089:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5090:                     $no_ownblock = 1;
                   5091:                     last;
                   5092:                 }
1.474     raeburn  5093:             }
                   5094:         }
                   5095:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5096:         next if (($no_ownblock) &&
1.491     albertel 5097:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5098:         next if ($no_userblock);
1.474     raeburn  5099: 
1.866     kalberla 5100:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  5101:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  5102:         
1.1062    raeburn  5103:         my ($start,$end,$trigger) = 
                   5104:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  5105:         if (($start != 0) && 
                   5106:             (($startblock == 0) || ($startblock > $start))) {
                   5107:             $startblock = $start;
1.1062    raeburn  5108:             if ($trigger ne '') {
                   5109:                 $triggerblock = $trigger;
                   5110:             }
1.502     raeburn  5111:         }
                   5112:         if (($end != 0)  &&
                   5113:             (($endblock == 0) || ($endblock < $end))) {
                   5114:             $endblock = $end;
1.1062    raeburn  5115:             if ($trigger ne '') {
                   5116:                 $triggerblock = $trigger;
                   5117:             }
1.502     raeburn  5118:         }
1.490     raeburn  5119:     }
1.1062    raeburn  5120:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5121: }
                   5122: 
                   5123: sub get_blocks {
1.1062    raeburn  5124:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  5125:     my $startblock = 0;
                   5126:     my $endblock = 0;
1.1062    raeburn  5127:     my $triggerblock = '';
1.490     raeburn  5128:     my $course = $cdom.'_'.$cnum;
                   5129:     $setters->{$course} = {};
                   5130:     $setters->{$course}{'staff'} = [];
                   5131:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5132:     $setters->{$course}{'triggers'} = [];
                   5133:     my (@blockers,%triggered);
                   5134:     my $now = time;
                   5135:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5136:     if ($activity eq 'docs') {
                   5137:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   5138:         foreach my $block (@blockers) {
                   5139:             if ($block =~ /^firstaccess____(.+)$/) {
                   5140:                 my $item = $1;
                   5141:                 my $type = 'map';
                   5142:                 my $timersymb = $item;
                   5143:                 if ($item eq 'course') {
                   5144:                     $type = 'course';
                   5145:                 } elsif ($item =~ /___\d+___/) {
                   5146:                     $type = 'resource';
                   5147:                 } else {
                   5148:                     $timersymb = &Apache::lonnet::symbread($item);
                   5149:                 }
                   5150:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5151:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5152:                 $triggered{$block} = {
                   5153:                                        start => $start,
                   5154:                                        end   => $end,
                   5155:                                        type  => $type,
                   5156:                                      };
                   5157:             }
                   5158:         }
                   5159:     } else {
                   5160:         foreach my $block (keys(%commblocks)) {
                   5161:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5162:                 my ($start,$end) = ($1,$2);
                   5163:                 if ($start <= time && $end >= time) {
                   5164:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5165:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5166:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5167:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5168:                                     push(@blockers,$block);
                   5169:                                 }
                   5170:                             }
                   5171:                         }
                   5172:                     }
                   5173:                 }
                   5174:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5175:                 my $item = $1;
                   5176:                 my $timersymb = $item; 
                   5177:                 my $type = 'map';
                   5178:                 if ($item eq 'course') {
                   5179:                     $type = 'course';
                   5180:                 } elsif ($item =~ /___\d+___/) {
                   5181:                     $type = 'resource';
                   5182:                 } else {
                   5183:                     $timersymb = &Apache::lonnet::symbread($item);
                   5184:                 }
                   5185:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5186:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5187:                 if ($start && $end) {
                   5188:                     if (($start <= time) && ($end >= time)) {
                   5189:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   5190:                             push(@blockers,$block);
                   5191:                             $triggered{$block} = {
                   5192:                                                    start => $start,
                   5193:                                                    end   => $end,
                   5194:                                                    type  => $type,
                   5195:                                                  };
                   5196:                         }
                   5197:                     }
1.490     raeburn  5198:                 }
1.1062    raeburn  5199:             }
                   5200:         }
                   5201:     }
                   5202:     foreach my $blocker (@blockers) {
                   5203:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5204:             &parse_block_record($commblocks{$blocker});
                   5205:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5206:         my ($start,$end,$triggertype);
                   5207:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5208:             ($start,$end) = ($1,$2);
                   5209:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5210:             $start = $triggered{$blocker}{'start'};
                   5211:             $end = $triggered{$blocker}{'end'};
                   5212:             $triggertype = $triggered{$blocker}{'type'};
                   5213:         }
                   5214:         if ($start) {
                   5215:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5216:             if ($triggertype) {
                   5217:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5218:             } else {
                   5219:                 push(@{$$setters{$course}{'triggers'}},0);
                   5220:             }
                   5221:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5222:                 $startblock = $start;
                   5223:                 if ($triggertype) {
                   5224:                     $triggerblock = $blocker;
1.474     raeburn  5225:                 }
                   5226:             }
1.1062    raeburn  5227:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5228:                $endblock = $end;
                   5229:                if ($triggertype) {
                   5230:                    $triggerblock = $blocker;
                   5231:                }
                   5232:             }
1.474     raeburn  5233:         }
                   5234:     }
1.1062    raeburn  5235:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5236: }
                   5237: 
                   5238: sub parse_block_record {
                   5239:     my ($record) = @_;
                   5240:     my ($setuname,$setudom,$title,$blocks);
                   5241:     if (ref($record) eq 'HASH') {
                   5242:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5243:         $title = &unescape($record->{'event'});
                   5244:         $blocks = $record->{'blocks'};
                   5245:     } else {
                   5246:         my @data = split(/:/,$record,3);
                   5247:         if (scalar(@data) eq 2) {
                   5248:             $title = $data[1];
                   5249:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5250:         } else {
                   5251:             ($setuname,$setudom,$title) = @data;
                   5252:         }
                   5253:         $blocks = { 'com' => 'on' };
                   5254:     }
                   5255:     return ($setuname,$setudom,$title,$blocks);
                   5256: }
                   5257: 
1.854     kalberla 5258: sub blocking_status {
1.1189    raeburn  5259:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  5260:     my %setters;
1.890     droeschl 5261: 
1.1061    raeburn  5262: # check for active blocking
1.1062    raeburn  5263:     my ($startblock,$endblock,$triggerblock) = 
1.1189    raeburn  5264:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  5265:     my $blocked = 0;
                   5266:     if ($startblock && $endblock) {
                   5267:         $blocked = 1;
                   5268:     }
1.890     droeschl 5269: 
1.1061    raeburn  5270: # caller just wants to know whether a block is active
                   5271:     if (!wantarray) { return $blocked; }
                   5272: 
                   5273: # build a link to a popup window containing the details
                   5274:     my $querystring  = "?activity=$activity";
                   5275: # $uname and $udom decide whose portfolio the user is trying to look at
1.1232    raeburn  5276:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   5277:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5278:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5279:     } elsif ($activity eq 'docs') {
                   5280:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   5281:     }
1.1061    raeburn  5282: 
                   5283:     my $output .= <<'END_MYBLOCK';
                   5284: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5285:     var options = "width=" + w + ",height=" + h + ",";
                   5286:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5287:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5288:     var newWin = window.open(url, wdwName, options);
                   5289:     newWin.focus();
                   5290: }
1.890     droeschl 5291: END_MYBLOCK
1.854     kalberla 5292: 
1.1061    raeburn  5293:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5294:   
1.1061    raeburn  5295:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5296:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5297:     my $class = 'LC_comblock';
1.1062    raeburn  5298:     if ($activity eq 'docs') {
                   5299:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5300:         $class = '';
1.1063    raeburn  5301:     } elsif ($activity eq 'printout') {
                   5302:         $text = &mt('Printing Blocked');
1.1232    raeburn  5303:     } elsif ($activity eq 'passwd') {
                   5304:         $text = &mt('Password Changing Blocked');
1.1062    raeburn  5305:     }
1.1061    raeburn  5306:     $output .= <<"END_BLOCK";
1.1217    raeburn  5307: <div class='$class'>
1.869     kalberla 5308:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5309:   title='$text'>
                   5310:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5311:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5312:   title='$text'>$text</a>
1.867     kalberla 5313: </div>
                   5314: 
                   5315: END_BLOCK
1.474     raeburn  5316: 
1.1061    raeburn  5317:     return ($blocked, $output);
1.854     kalberla 5318: }
1.490     raeburn  5319: 
1.60      matthew  5320: ###############################################
                   5321: 
1.682     raeburn  5322: sub check_ip_acc {
1.1201    raeburn  5323:     my ($acc,$clientip)=@_;
1.682     raeburn  5324:     &Apache::lonxml::debug("acc is $acc");
                   5325:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5326:         return 1;
                   5327:     }
1.1219    raeburn  5328:     my $allowed;
1.1252    raeburn  5329:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
1.682     raeburn  5330: 
                   5331:     my $name;
1.1219    raeburn  5332:     my %access = (
                   5333:                      allowfrom => 1,
                   5334:                      denyfrom  => 0,
                   5335:                  );
                   5336:     my @allows;
                   5337:     my @denies;
                   5338:     foreach my $item (split(',',$acc)) {
                   5339:         $item =~ s/^\s*//;
                   5340:         $item =~ s/\s*$//;
                   5341:         my $pattern;
                   5342:         if ($item =~ /^\!(.+)$/) {
                   5343:             push(@denies,$1);
                   5344:         } else {
                   5345:             push(@allows,$item);
                   5346:         }
                   5347:    }
                   5348:    my $numdenies = scalar(@denies);
                   5349:    my $numallows = scalar(@allows);
                   5350:    my $count = 0;
                   5351:    foreach my $pattern (@denies,@allows) {
                   5352:         $count ++; 
                   5353:         my $acctype = 'allowfrom';
                   5354:         if ($count <= $numdenies) {
                   5355:             $acctype = 'denyfrom';
                   5356:         }
1.682     raeburn  5357:         if ($pattern =~ /\*$/) {
                   5358:             #35.8.*
                   5359:             $pattern=~s/\*//;
1.1219    raeburn  5360:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5361:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5362:             #35.8.3.[34-56]
                   5363:             my $low=$2;
                   5364:             my $high=$3;
                   5365:             $pattern=$1;
                   5366:             if ($ip =~ /^\Q$pattern\E/) {
                   5367:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5368:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5369:             }
                   5370:         } elsif ($pattern =~ /^\*/) {
                   5371:             #*.msu.edu
                   5372:             $pattern=~s/\*//;
                   5373:             if (!defined($name)) {
                   5374:                 use Socket;
                   5375:                 my $netaddr=inet_aton($ip);
                   5376:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5377:             }
1.1219    raeburn  5378:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5379:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5380:             #127.0.0.1
1.1219    raeburn  5381:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5382:         } else {
                   5383:             #some.name.com
                   5384:             if (!defined($name)) {
                   5385:                 use Socket;
                   5386:                 my $netaddr=inet_aton($ip);
                   5387:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5388:             }
1.1219    raeburn  5389:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5390:         }
                   5391:         if ($allowed =~ /^(0|1)$/) { last; }
                   5392:     }
                   5393:     if ($allowed eq '') {
                   5394:         if ($numdenies && !$numallows) {
                   5395:             $allowed = 1;
                   5396:         } else {
                   5397:             $allowed = 0;
1.682     raeburn  5398:         }
                   5399:     }
                   5400:     return $allowed;
                   5401: }
                   5402: 
                   5403: ###############################################
                   5404: 
1.60      matthew  5405: =pod
                   5406: 
1.112     bowersj2 5407: =head1 Domain Template Functions
                   5408: 
                   5409: =over 4
                   5410: 
                   5411: =item * &determinedomain()
1.60      matthew  5412: 
                   5413: Inputs: $domain (usually will be undef)
                   5414: 
1.63      www      5415: Returns: Determines which domain should be used for designs
1.60      matthew  5416: 
                   5417: =cut
1.54      www      5418: 
1.60      matthew  5419: ###############################################
1.63      www      5420: sub determinedomain {
                   5421:     my $domain=shift;
1.531     albertel 5422:     if (! $domain) {
1.60      matthew  5423:         # Determine domain if we have not been given one
1.893     raeburn  5424:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5425:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5426:         if ($env{'request.role.domain'}) { 
                   5427:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5428:         }
                   5429:     }
1.63      www      5430:     return $domain;
                   5431: }
                   5432: ###############################################
1.517     raeburn  5433: 
1.518     albertel 5434: sub devalidate_domconfig_cache {
                   5435:     my ($udom)=@_;
                   5436:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5437: }
                   5438: 
                   5439: # ---------------------- Get domain configuration for a domain
                   5440: sub get_domainconf {
                   5441:     my ($udom) = @_;
                   5442:     my $cachetime=1800;
                   5443:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5444:     if (defined($cached)) { return %{$result}; }
                   5445: 
                   5446:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5447: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5448:     my (%designhash,%legacy);
1.518     albertel 5449:     if (keys(%domconfig) > 0) {
                   5450:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5451:             if (keys(%{$domconfig{'login'}})) {
                   5452:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5453:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5454:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5455:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5456:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5457:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5458:                                         if ($key eq 'loginvia') {
                   5459:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5460:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5461:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5462:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5463: 
                   5464:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5465:                                                 } else {
                   5466:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5467:                                                 }
1.948     raeburn  5468:                                             }
1.1208    raeburn  5469:                                         } elsif ($key eq 'headtag') {
                   5470:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5471:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5472:                                             }
1.946     raeburn  5473:                                         }
1.1208    raeburn  5474:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5475:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5476:                                         }
1.946     raeburn  5477:                                     }
                   5478:                                 }
                   5479:                             }
                   5480:                         } else {
                   5481:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5482:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5483:                                     $domconfig{'login'}{$key}{$img};
                   5484:                             }
1.699     raeburn  5485:                         }
                   5486:                     } else {
                   5487:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5488:                     }
1.632     raeburn  5489:                 }
                   5490:             } else {
                   5491:                 $legacy{'login'} = 1;
1.518     albertel 5492:             }
1.632     raeburn  5493:         } else {
                   5494:             $legacy{'login'} = 1;
1.518     albertel 5495:         }
                   5496:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5497:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5498:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5499:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5500:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5501:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5502:                         }
1.518     albertel 5503:                     }
                   5504:                 }
1.632     raeburn  5505:             } else {
                   5506:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5507:             }
1.632     raeburn  5508:         } else {
                   5509:             $legacy{'rolecolors'} = 1;
1.518     albertel 5510:         }
1.948     raeburn  5511:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5512:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5513:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5514:             }
                   5515:         }
1.632     raeburn  5516:         if (keys(%legacy) > 0) {
                   5517:             my %legacyhash = &get_legacy_domconf($udom);
                   5518:             foreach my $item (keys(%legacyhash)) {
                   5519:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5520:                     if ($legacy{'login'}) { 
                   5521:                         $designhash{$item} = $legacyhash{$item};
                   5522:                     }
                   5523:                 } else {
                   5524:                     if ($legacy{'rolecolors'}) {
                   5525:                         $designhash{$item} = $legacyhash{$item};
                   5526:                     }
1.518     albertel 5527:                 }
                   5528:             }
                   5529:         }
1.632     raeburn  5530:     } else {
                   5531:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5532:     }
                   5533:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5534: 				  $cachetime);
                   5535:     return %designhash;
                   5536: }
                   5537: 
1.632     raeburn  5538: sub get_legacy_domconf {
                   5539:     my ($udom) = @_;
                   5540:     my %legacyhash;
                   5541:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5542:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5543:     if (-e $designfile) {
                   5544:         if ( open (my $fh,"<$designfile") ) {
                   5545:             while (my $line = <$fh>) {
                   5546:                 next if ($line =~ /^\#/);
                   5547:                 chomp($line);
                   5548:                 my ($key,$val)=(split(/\=/,$line));
                   5549:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5550:             }
                   5551:             close($fh);
                   5552:         }
                   5553:     }
1.1026    raeburn  5554:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5555:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5556:     }
                   5557:     return %legacyhash;
                   5558: }
                   5559: 
1.63      www      5560: =pod
                   5561: 
1.112     bowersj2 5562: =item * &domainlogo()
1.63      www      5563: 
                   5564: Inputs: $domain (usually will be undef)
                   5565: 
                   5566: Returns: A link to a domain logo, if the domain logo exists.
                   5567: If the domain logo does not exist, a description of the domain.
                   5568: 
                   5569: =cut
1.112     bowersj2 5570: 
1.63      www      5571: ###############################################
                   5572: sub domainlogo {
1.517     raeburn  5573:     my $domain = &determinedomain(shift);
1.518     albertel 5574:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5575:     # See if there is a logo
                   5576:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5577:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5578:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5579: 	    if ($imgsrc =~ m{^/res/}) {
                   5580: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5581: 		&Apache::lonnet::repcopy($local_name);
                   5582: 	    }
                   5583: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5584:         } 
                   5585:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5586:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5587:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5588:     } else {
1.60      matthew  5589:         return '';
1.59      www      5590:     }
                   5591: }
1.63      www      5592: ##############################################
                   5593: 
                   5594: =pod
                   5595: 
1.112     bowersj2 5596: =item * &designparm()
1.63      www      5597: 
                   5598: Inputs: $which parameter; $domain (usually will be undef)
                   5599: 
                   5600: Returns: value of designparamter $which
                   5601: 
                   5602: =cut
1.112     bowersj2 5603: 
1.397     albertel 5604: 
1.400     albertel 5605: ##############################################
1.397     albertel 5606: sub designparm {
                   5607:     my ($which,$domain)=@_;
                   5608:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5609:         return $env{'environment.color.'.$which};
1.96      www      5610:     }
1.63      www      5611:     $domain=&determinedomain($domain);
1.1016    raeburn  5612:     my %domdesign;
                   5613:     unless ($domain eq 'public') {
                   5614:         %domdesign = &get_domainconf($domain);
                   5615:     }
1.520     raeburn  5616:     my $output;
1.517     raeburn  5617:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5618:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5619:     } else {
1.520     raeburn  5620:         $output = $defaultdesign{$which};
                   5621:     }
                   5622:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5623:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5624:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5625:             if ($output =~ m{^/res/}) {
                   5626:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5627:                 &Apache::lonnet::repcopy($local_name);
                   5628:             }
1.520     raeburn  5629:             $output = &lonhttpdurl($output);
                   5630:         }
1.63      www      5631:     }
1.520     raeburn  5632:     return $output;
1.63      www      5633: }
1.59      www      5634: 
1.822     bisitz   5635: ##############################################
                   5636: =pod
                   5637: 
1.832     bisitz   5638: =item * &authorspace()
                   5639: 
1.1028    raeburn  5640: Inputs: $url (usually will be undef).
1.832     bisitz   5641: 
1.1132    raeburn  5642: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5643:          directory being viewed (or for which action is being taken). 
                   5644:          If $url is provided, and begins /priv/<domain>/<uname>
                   5645:          the path will be that portion of the $context argument.
                   5646:          Otherwise the path will be for the author space of the current
                   5647:          user when the current role is author, or for that of the 
                   5648:          co-author/assistant co-author space when the current role 
                   5649:          is co-author or assistant co-author.
1.832     bisitz   5650: 
                   5651: =cut
                   5652: 
                   5653: sub authorspace {
1.1028    raeburn  5654:     my ($url) = @_;
                   5655:     if ($url ne '') {
                   5656:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5657:            return $1;
                   5658:         }
                   5659:     }
1.832     bisitz   5660:     my $caname = '';
1.1024    www      5661:     my $cadom = '';
1.1028    raeburn  5662:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5663:         ($cadom,$caname) =
1.832     bisitz   5664:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5665:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5666:         $caname = $env{'user.name'};
1.1024    www      5667:         $cadom = $env{'user.domain'};
1.832     bisitz   5668:     }
1.1028    raeburn  5669:     if (($caname ne '') && ($cadom ne '')) {
                   5670:         return "/priv/$cadom/$caname/";
                   5671:     }
                   5672:     return;
1.832     bisitz   5673: }
                   5674: 
                   5675: ##############################################
                   5676: =pod
                   5677: 
1.822     bisitz   5678: =item * &head_subbox()
                   5679: 
                   5680: Inputs: $content (contains HTML code with page functions, etc.)
                   5681: 
                   5682: Returns: HTML div with $content
                   5683:          To be included in page header
                   5684: 
                   5685: =cut
                   5686: 
                   5687: sub head_subbox {
                   5688:     my ($content)=@_;
                   5689:     my $output =
1.993     raeburn  5690:         '<div class="LC_head_subbox">'
1.822     bisitz   5691:        .$content
                   5692:        .'</div>'
                   5693: }
                   5694: 
                   5695: ##############################################
                   5696: =pod
                   5697: 
                   5698: =item * &CSTR_pageheader()
                   5699: 
1.1026    raeburn  5700: Input: (optional) filename from which breadcrumb trail is built.
                   5701:        In most cases no input as needed, as $env{'request.filename'}
                   5702:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5703: 
                   5704: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5705:          To be included on Authoring Space pages
1.822     bisitz   5706: 
                   5707: =cut
                   5708: 
                   5709: sub CSTR_pageheader {
1.1026    raeburn  5710:     my ($trailfile) = @_;
                   5711:     if ($trailfile eq '') {
                   5712:         $trailfile = $env{'request.filename'};
                   5713:     }
                   5714: 
                   5715: # this is for resources; directories have customtitle, and crumbs
                   5716: # and select recent are created in lonpubdir.pm
                   5717: 
                   5718:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5719:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5720:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5721:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5722:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5723: 
                   5724:     my $parentpath = '';
                   5725:     my $lastitem = '';
                   5726:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5727:         $parentpath = $1;
                   5728:         $lastitem = $2;
                   5729:     } else {
                   5730:         $lastitem = $thisdisfn;
                   5731:     }
1.921     bisitz   5732: 
1.1246    raeburn  5733:     my ($crsauthor,$title);
                   5734:     if (($env{'request.course.id'}) &&
                   5735:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  5736:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  5737:         $crsauthor = 1;
                   5738:         $title = &mt('Course Authoring Space');
                   5739:     } else {
                   5740:         $title = &mt('Authoring Space');
                   5741:     }
                   5742: 
1.921     bisitz   5743:     my $output =
1.822     bisitz   5744:          '<div>'
                   5745:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  5746:         .'<b>'.$title.'</b> '
1.822     bisitz   5747:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5748:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5749:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5750: 
                   5751:     if ($lastitem) {
                   5752:         $output .=
                   5753:              '<span class="LC_filename">'
                   5754:             .$lastitem
                   5755:             .'</span>';
                   5756:     }
1.1245    raeburn  5757: 
1.1246    raeburn  5758:     if ($crsauthor) {
                   5759:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
                   5760:     } else {
                   5761:         $output .=
                   5762:              '<br />'
                   5763:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5764:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5765:             .'</form>'
                   5766:             .&Apache::lonmenu::constspaceform();
                   5767:     }
                   5768:     $output .= '</div>';
1.921     bisitz   5769: 
                   5770:     return $output;
1.822     bisitz   5771: }
                   5772: 
1.60      matthew  5773: ###############################################
                   5774: ###############################################
                   5775: 
                   5776: =pod
                   5777: 
1.112     bowersj2 5778: =back
                   5779: 
1.549     albertel 5780: =head1 HTML Helpers
1.112     bowersj2 5781: 
                   5782: =over 4
                   5783: 
                   5784: =item * &bodytag()
1.60      matthew  5785: 
                   5786: Returns a uniform header for LON-CAPA web pages.
                   5787: 
                   5788: Inputs: 
                   5789: 
1.112     bowersj2 5790: =over 4
                   5791: 
                   5792: =item * $title, A title to be displayed on the page.
                   5793: 
                   5794: =item * $function, the current role (can be undef).
                   5795: 
                   5796: =item * $addentries, extra parameters for the <body> tag.
                   5797: 
                   5798: =item * $bodyonly, if defined, only return the <body> tag.
                   5799: 
                   5800: =item * $domain, if defined, force a given domain.
                   5801: 
                   5802: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5803:             text interface only)
1.60      matthew  5804: 
1.814     bisitz   5805: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5806:                      navigational links
1.317     albertel 5807: 
1.338     albertel 5808: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5809: 
1.460     albertel 5810: =item * $args, optional argument valid values are
                   5811:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  5812:             use_absolute     -> for external resource or syllabus, this will
                   5813:                                 contain https://<hostname> if server uses
                   5814:                                 https (as per hosts.tab), but request is for http
                   5815:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5816: 
1.1096    raeburn  5817: =item * $advtoolsref, optional argument, ref to an array containing
                   5818:             inlineremote items to be added in "Functions" menu below
                   5819:             breadcrumbs.
                   5820: 
1.112     bowersj2 5821: =back
                   5822: 
1.60      matthew  5823: Returns: A uniform header for LON-CAPA web pages.  
                   5824: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5825: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5826: other decorations will be returned.
                   5827: 
                   5828: =cut
                   5829: 
1.54      www      5830: sub bodytag {
1.831     bisitz   5831:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1096    raeburn  5832:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
1.339     albertel 5833: 
1.954     raeburn  5834:     my $public;
                   5835:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5836:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5837:         $public = 1;
                   5838:     }
1.460     albertel 5839:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  5840:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  5841:     my $hostname = $args->{'hostname'};
1.339     albertel 5842: 
1.183     matthew  5843:     $function = &get_users_function() if (!$function);
1.339     albertel 5844:     my $img =    &designparm($function.'.img',$domain);
                   5845:     my $font =   &designparm($function.'.font',$domain);
                   5846:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5847: 
1.803     bisitz   5848:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5849: 		   'bgcolor' => $pgbg,
1.339     albertel 5850: 		   'text'    => $font,
                   5851:                    'alink'   => &designparm($function.'.alink',$domain),
                   5852: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5853: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5854:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5855: 
1.63      www      5856:  # role and realm
1.1178    raeburn  5857:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5858:     if ($realm) {
                   5859:         $realm = '/'.$realm;
                   5860:     }
1.378     raeburn  5861:     if ($role  eq 'ca') {
1.479     albertel 5862:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5863:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5864:     } 
1.55      www      5865: # realm
1.258     albertel 5866:     if ($env{'request.course.id'}) {
1.378     raeburn  5867:         if ($env{'request.role'} !~ /^cr/) {
                   5868:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  5869:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  5870:             if ($env{'request.role.desc'}) {
                   5871:                 $role = $env{'request.role.desc'};
                   5872:             } else {
                   5873:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5874:             }
1.1257    raeburn  5875:         } else {
                   5876:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  5877:         }
1.898     raeburn  5878:         if ($env{'request.course.sec'}) {
                   5879:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5880:         }   
1.359     albertel 5881: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5882:     } else {
                   5883:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5884:     }
1.433     albertel 5885: 
1.359     albertel 5886:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5887: 
1.438     albertel 5888:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5889: 
1.101     www      5890: # construct main body tag
1.359     albertel 5891:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  5892: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5893: 
1.1131    raeburn  5894:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5895: 
1.1130    raeburn  5896:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5897:         return $bodytag;
1.1130    raeburn  5898:     }
1.359     albertel 5899: 
1.954     raeburn  5900:     if ($public) {
1.433     albertel 5901: 	undef($role);
                   5902:     }
1.359     albertel 5903:     
1.762     bisitz   5904:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5905:     #
                   5906:     # Extra info if you are the DC
                   5907:     my $dc_info = '';
                   5908:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5909:                         $env{'course.'.$env{'request.course.id'}.
                   5910:                                  '.domain'}.'/'})) {
                   5911:         my $cid = $env{'request.course.id'};
1.917     raeburn  5912:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5913:         $dc_info =~ s/\s+$//;
1.359     albertel 5914:     }
                   5915: 
1.1237    raeburn  5916:     my $crstype;
                   5917:     if ($env{'request.course.id'}) {
                   5918:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
                   5919:     } elsif ($args->{'crstype'}) {
                   5920:         $crstype = $args->{'crstype'};
                   5921:     }
                   5922:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   5923:         undef($role);
                   5924:     } else {
1.1242    raeburn  5925:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  5926:     }
1.853     droeschl 5927: 
1.903     droeschl 5928:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5929: 
                   5930:         #    if ($env{'request.state'} eq 'construct') {
                   5931:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5932:         #    }
                   5933: 
1.1130    raeburn  5934:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  5935:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5936: 
1.1237    raeburn  5937:         my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
1.359     albertel 5938: 
1.916     droeschl 5939:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5940:              if ($dc_info) {
                   5941:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5942:              }
1.1130    raeburn  5943:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.916     droeschl 5944:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5945:             return $bodytag;
                   5946:         }
1.894     droeschl 5947: 
1.927     raeburn  5948:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1130    raeburn  5949:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5950:         }
1.916     droeschl 5951: 
1.1130    raeburn  5952:         $bodytag .= $right;
1.852     droeschl 5953: 
1.917     raeburn  5954:         if ($dc_info) {
                   5955:             $dc_info = &dc_courseid_toggle($dc_info);
                   5956:         }
                   5957:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5958: 
1.1169    raeburn  5959:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  5960:         if ($args->{'no_secondary_menu'}) {
                   5961:             return $bodytag;
                   5962:         }
1.1169    raeburn  5963:         #don't show menus for public users
1.954     raeburn  5964:         if (!$public){
1.1154    raeburn  5965:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5966:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5967:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5968:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5969:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1274    raeburn  5970:                                 $args->{'bread_crumbs'},'','',$hostname);
1.1096    raeburn  5971:             } elsif ($forcereg) {
                   5972:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  5973:                                                             $args->{'group'},
1.1274    raeburn  5974:                                                             $args->{'hide_buttons'},
                   5975:                                                             $hostname);
1.1096    raeburn  5976:             } else {
                   5977:                 $bodytag .= 
                   5978:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5979:                                                         $forcereg,$args->{'group'},
                   5980:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  5981:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  5982:             }
1.903     droeschl 5983:         }else{
                   5984:             # this is to seperate menu from content when there's no secondary
                   5985:             # menu. Especially needed for public accessible ressources.
                   5986:             $bodytag .= '<hr style="clear:both" />';
                   5987:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5988:         }
1.903     droeschl 5989: 
1.235     raeburn  5990:         return $bodytag;
1.182     matthew  5991: }
                   5992: 
1.917     raeburn  5993: sub dc_courseid_toggle {
                   5994:     my ($dc_info) = @_;
1.980     raeburn  5995:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5996:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5997:            &mt('(More ...)').'</a></span>'.
                   5998:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5999: }
                   6000: 
1.330     albertel 6001: sub make_attr_string {
                   6002:     my ($register,$attr_ref) = @_;
                   6003: 
                   6004:     if ($attr_ref && !ref($attr_ref)) {
                   6005: 	die("addentries Must be a hash ref ".
                   6006: 	    join(':',caller(1))." ".
                   6007: 	    join(':',caller(0))." ");
                   6008:     }
                   6009: 
                   6010:     if ($register) {
1.339     albertel 6011: 	my ($on_load,$on_unload);
                   6012: 	foreach my $key (keys(%{$attr_ref})) {
                   6013: 	    if      (lc($key) eq 'onload') {
                   6014: 		$on_load.=$attr_ref->{$key}.';';
                   6015: 		delete($attr_ref->{$key});
                   6016: 
                   6017: 	    } elsif (lc($key) eq 'onunload') {
                   6018: 		$on_unload.=$attr_ref->{$key}.';';
                   6019: 		delete($attr_ref->{$key});
                   6020: 	    }
                   6021: 	}
1.953     droeschl 6022: 	$attr_ref->{'onload'}  = $on_load;
                   6023: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6024:     }
1.339     albertel 6025: 
1.330     albertel 6026:     my $attr_string;
1.1159    raeburn  6027:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6028: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6029:     }
                   6030:     return $attr_string;
                   6031: }
                   6032: 
                   6033: 
1.182     matthew  6034: ###############################################
1.251     albertel 6035: ###############################################
                   6036: 
                   6037: =pod
                   6038: 
                   6039: =item * &endbodytag()
                   6040: 
                   6041: Returns a uniform footer for LON-CAPA web pages.
                   6042: 
1.635     raeburn  6043: Inputs: 1 - optional reference to an args hash
                   6044: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6045: a 'Continue' link is not displayed if the page contains an
                   6046: internal redirect in the <head></head> section,
                   6047: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6048: 
                   6049: =cut
                   6050: 
                   6051: sub endbodytag {
1.635     raeburn  6052:     my ($args) = @_;
1.1080    raeburn  6053:     my $endbodytag;
                   6054:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6055:         $endbodytag='</body>';
                   6056:     }
1.315     albertel 6057:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6058:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6059: 	    $endbodytag=
                   6060: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6061: 	        &mt('Continue').'</a>'.
                   6062: 	        $endbodytag;
                   6063:         }
1.315     albertel 6064:     }
1.251     albertel 6065:     return $endbodytag;
                   6066: }
                   6067: 
1.352     albertel 6068: =pod
                   6069: 
                   6070: =item * &standard_css()
                   6071: 
                   6072: Returns a style sheet
                   6073: 
                   6074: Inputs: (all optional)
                   6075:             domain         -> force to color decorate a page for a specific
                   6076:                                domain
                   6077:             function       -> force usage of a specific rolish color scheme
                   6078:             bgcolor        -> override the default page bgcolor
                   6079: 
                   6080: =cut
                   6081: 
1.343     albertel 6082: sub standard_css {
1.345     albertel 6083:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6084:     $function  = &get_users_function() if (!$function);
                   6085:     my $img    = &designparm($function.'.img',   $domain);
                   6086:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6087:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6088:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6089: #second colour for later usage
1.345     albertel 6090:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6091:     my $pgbg_or_bgcolor =
                   6092: 	         $bgcolor ||
1.352     albertel 6093: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6094:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6095:     my $alink  = &designparm($function.'.alink', $domain);
                   6096:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6097:     my $link   = &designparm($function.'.link',  $domain);
                   6098: 
1.602     albertel 6099:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6100:     my $mono                 = 'monospace';
1.850     bisitz   6101:     my $data_table_head      = $sidebg;
                   6102:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6103:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6104:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6105:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6106:     my $mail_new             = '#FFBB77';
                   6107:     my $mail_new_hover       = '#DD9955';
                   6108:     my $mail_read            = '#BBBB77';
                   6109:     my $mail_read_hover      = '#999944';
                   6110:     my $mail_replied         = '#AAAA88';
                   6111:     my $mail_replied_hover   = '#888855';
                   6112:     my $mail_other           = '#99BBBB';
                   6113:     my $mail_other_hover     = '#669999';
1.391     albertel 6114:     my $table_header         = '#DDDDDD';
1.489     raeburn  6115:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6116:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6117:     my $button_hover         = '#BF2317';
1.392     albertel 6118: 
1.608     albertel 6119:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6120:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6121:                                              : '0 3px 0 4px';
1.448     albertel 6122: 
1.523     albertel 6123: 
1.343     albertel 6124:     return <<END;
1.947     droeschl 6125: 
                   6126: /* needed for iframe to allow 100% height in FF */
                   6127: body, html { 
                   6128:     margin: 0;
                   6129:     padding: 0 0.5%;
                   6130:     height: 99%; /* to avoid scrollbars */
                   6131: }
                   6132: 
1.795     www      6133: body {
1.911     bisitz   6134:   font-family: $sans;
                   6135:   line-height:130%;
                   6136:   font-size:0.83em;
                   6137:   color:$font;
1.795     www      6138: }
                   6139: 
1.959     onken    6140: a:focus,
                   6141: a:focus img {
1.795     www      6142:   color: red;
                   6143: }
1.698     harmsja  6144: 
1.911     bisitz   6145: form, .inline {
                   6146:   display: inline;
1.795     www      6147: }
1.721     harmsja  6148: 
1.795     www      6149: .LC_right {
1.911     bisitz   6150:   text-align:right;
1.795     www      6151: }
                   6152: 
                   6153: .LC_middle {
1.911     bisitz   6154:   vertical-align:middle;
1.795     www      6155: }
1.721     harmsja  6156: 
1.1130    raeburn  6157: .LC_floatleft {
                   6158:   float: left;
                   6159: }
                   6160: 
                   6161: .LC_floatright {
                   6162:   float: right;
                   6163: }
                   6164: 
1.911     bisitz   6165: .LC_400Box {
                   6166:   width:400px;
                   6167: }
1.721     harmsja  6168: 
1.947     droeschl 6169: .LC_iframecontainer {
                   6170:     width: 98%;
                   6171:     margin: 0;
                   6172:     position: fixed;
                   6173:     top: 8.5em;
                   6174:     bottom: 0;
                   6175: }
                   6176: 
                   6177: .LC_iframecontainer iframe{
                   6178:     border: none;
                   6179:     width: 100%;
                   6180:     height: 100%;
                   6181: }
                   6182: 
1.778     bisitz   6183: .LC_filename {
                   6184:   font-family: $mono;
                   6185:   white-space:pre;
1.921     bisitz   6186:   font-size: 120%;
1.778     bisitz   6187: }
                   6188: 
                   6189: .LC_fileicon {
                   6190:   border: none;
                   6191:   height: 1.3em;
                   6192:   vertical-align: text-bottom;
                   6193:   margin-right: 0.3em;
                   6194:   text-decoration:none;
                   6195: }
                   6196: 
1.1008    www      6197: .LC_setting {
                   6198:   text-decoration:underline;
                   6199: }
                   6200: 
1.350     albertel 6201: .LC_error {
                   6202:   color: red;
                   6203: }
1.795     www      6204: 
1.1097    bisitz   6205: .LC_warning {
                   6206:   color: darkorange;
                   6207: }
                   6208: 
1.457     albertel 6209: .LC_diff_removed {
1.733     bisitz   6210:   color: red;
1.394     albertel 6211: }
1.532     albertel 6212: 
                   6213: .LC_info,
1.457     albertel 6214: .LC_success,
                   6215: .LC_diff_added {
1.350     albertel 6216:   color: green;
                   6217: }
1.795     www      6218: 
1.802     bisitz   6219: div.LC_confirm_box {
                   6220:   background-color: #FAFAFA;
                   6221:   border: 1px solid $lg_border_color;
                   6222:   margin-right: 0;
                   6223:   padding: 5px;
                   6224: }
                   6225: 
                   6226: div.LC_confirm_box .LC_error img,
                   6227: div.LC_confirm_box .LC_success img {
                   6228:   vertical-align: middle;
                   6229: }
                   6230: 
1.1242    raeburn  6231: .LC_maxwidth {
                   6232:   max-width: 100%;
                   6233:   height: auto;
                   6234: }
                   6235: 
1.1243    raeburn  6236: .LC_textsize_mobile {
                   6237:   \@media only screen and (max-device-width: 480px) {
                   6238:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6239:   }
                   6240: }
                   6241: 
1.440     albertel 6242: .LC_icon {
1.771     droeschl 6243:   border: none;
1.790     droeschl 6244:   vertical-align: middle;
1.771     droeschl 6245: }
                   6246: 
1.543     albertel 6247: .LC_docs_spacer {
                   6248:   width: 25px;
                   6249:   height: 1px;
1.771     droeschl 6250:   border: none;
1.543     albertel 6251: }
1.346     albertel 6252: 
1.532     albertel 6253: .LC_internal_info {
1.735     bisitz   6254:   color: #999999;
1.532     albertel 6255: }
                   6256: 
1.794     www      6257: .LC_discussion {
1.1050    www      6258:   background: $data_table_dark;
1.911     bisitz   6259:   border: 1px solid black;
                   6260:   margin: 2px;
1.794     www      6261: }
                   6262: 
                   6263: .LC_disc_action_left {
1.1050    www      6264:   background: $sidebg;
1.911     bisitz   6265:   text-align: left;
1.1050    www      6266:   padding: 4px;
                   6267:   margin: 2px;
1.794     www      6268: }
                   6269: 
                   6270: .LC_disc_action_right {
1.1050    www      6271:   background: $sidebg;
1.911     bisitz   6272:   text-align: right;
1.1050    www      6273:   padding: 4px;
                   6274:   margin: 2px;
1.794     www      6275: }
                   6276: 
                   6277: .LC_disc_new_item {
1.911     bisitz   6278:   background: white;
                   6279:   border: 2px solid red;
1.1050    www      6280:   margin: 4px;
                   6281:   padding: 4px;
1.794     www      6282: }
                   6283: 
                   6284: .LC_disc_old_item {
1.911     bisitz   6285:   background: white;
1.1050    www      6286:   margin: 4px;
                   6287:   padding: 4px;
1.794     www      6288: }
                   6289: 
1.458     albertel 6290: table.LC_pastsubmission {
                   6291:   border: 1px solid black;
                   6292:   margin: 2px;
                   6293: }
                   6294: 
1.924     bisitz   6295: table#LC_menubuttons {
1.345     albertel 6296:   width: 100%;
                   6297:   background: $pgbg;
1.392     albertel 6298:   border: 2px;
1.402     albertel 6299:   border-collapse: separate;
1.803     bisitz   6300:   padding: 0;
1.345     albertel 6301: }
1.392     albertel 6302: 
1.801     tempelho 6303: table#LC_title_bar a {
                   6304:   color: $fontmenu;
                   6305: }
1.836     bisitz   6306: 
1.807     droeschl 6307: table#LC_title_bar {
1.819     tempelho 6308:   clear: both;
1.836     bisitz   6309:   display: none;
1.807     droeschl 6310: }
                   6311: 
1.795     www      6312: table#LC_title_bar,
1.933     droeschl 6313: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6314: table#LC_title_bar.LC_with_remote {
1.359     albertel 6315:   width: 100%;
1.392     albertel 6316:   border-color: $pgbg;
                   6317:   border-style: solid;
                   6318:   border-width: $border;
1.379     albertel 6319:   background: $pgbg;
1.801     tempelho 6320:   color: $fontmenu;
1.392     albertel 6321:   border-collapse: collapse;
1.803     bisitz   6322:   padding: 0;
1.819     tempelho 6323:   margin: 0;
1.359     albertel 6324: }
1.795     www      6325: 
1.933     droeschl 6326: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6327:     margin: 0;
                   6328:     padding: 0;
1.933     droeschl 6329:     position: relative;
                   6330:     list-style: none;
1.913     droeschl 6331: }
1.933     droeschl 6332: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6333:     display: inline;
                   6334: }
1.933     droeschl 6335: 
                   6336: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6337:     padding: 0;
1.933     droeschl 6338:     margin: 0;
                   6339:     float: left;
1.913     droeschl 6340: }
1.933     droeschl 6341: .LC_breadcrumb_tools_tools {
                   6342:     padding: 0;
                   6343:     margin: 0;
1.913     droeschl 6344:     float: right;
                   6345: }
                   6346: 
1.1240    raeburn  6347: .LC_placement_prog {
                   6348:     padding-right: 20px;
                   6349:     font-weight: bold;
                   6350:     font-size: 90%;
                   6351: }
                   6352: 
1.359     albertel 6353: table#LC_title_bar td {
                   6354:   background: $tabbg;
                   6355: }
1.795     www      6356: 
1.911     bisitz   6357: table#LC_menubuttons img {
1.803     bisitz   6358:   border: none;
1.346     albertel 6359: }
1.795     www      6360: 
1.842     droeschl 6361: .LC_breadcrumbs_component {
1.911     bisitz   6362:   float: right;
                   6363:   margin: 0 1em;
1.357     albertel 6364: }
1.842     droeschl 6365: .LC_breadcrumbs_component img {
1.911     bisitz   6366:   vertical-align: middle;
1.777     tempelho 6367: }
1.795     www      6368: 
1.1243    raeburn  6369: .LC_breadcrumbs_hoverable {
                   6370:   background: $sidebg;
                   6371: }
                   6372: 
1.383     albertel 6373: td.LC_table_cell_checkbox {
                   6374:   text-align: center;
                   6375: }
1.795     www      6376: 
                   6377: .LC_fontsize_small {
1.911     bisitz   6378:   font-size: 70%;
1.705     tempelho 6379: }
                   6380: 
1.844     bisitz   6381: #LC_breadcrumbs {
1.911     bisitz   6382:   clear:both;
                   6383:   background: $sidebg;
                   6384:   border-bottom: 1px solid $lg_border_color;
                   6385:   line-height: 2.5em;
1.933     droeschl 6386:   overflow: hidden;
1.911     bisitz   6387:   margin: 0;
                   6388:   padding: 0;
1.995     raeburn  6389:   text-align: left;
1.819     tempelho 6390: }
1.862     bisitz   6391: 
1.1098    bisitz   6392: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6393:   clear:both;
                   6394:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6395:   border: 1px solid $sidebg;
1.1098    bisitz   6396:   margin: 0 0 10px 0;
1.966     bisitz   6397:   padding: 3px;
1.995     raeburn  6398:   text-align: left;
1.822     bisitz   6399: }
                   6400: 
1.795     www      6401: .LC_fontsize_medium {
1.911     bisitz   6402:   font-size: 85%;
1.705     tempelho 6403: }
                   6404: 
1.795     www      6405: .LC_fontsize_large {
1.911     bisitz   6406:   font-size: 120%;
1.705     tempelho 6407: }
                   6408: 
1.346     albertel 6409: .LC_menubuttons_inline_text {
                   6410:   color: $font;
1.698     harmsja  6411:   font-size: 90%;
1.701     harmsja  6412:   padding-left:3px;
1.346     albertel 6413: }
                   6414: 
1.934     droeschl 6415: .LC_menubuttons_inline_text img{
                   6416:   vertical-align: middle;
                   6417: }
                   6418: 
1.1051    www      6419: li.LC_menubuttons_inline_text img {
1.951     onken    6420:   cursor:pointer;
1.1002    droeschl 6421:   text-decoration: none;
1.951     onken    6422: }
                   6423: 
1.526     www      6424: .LC_menubuttons_link {
                   6425:   text-decoration: none;
                   6426: }
1.795     www      6427: 
1.522     albertel 6428: .LC_menubuttons_category {
1.521     www      6429:   color: $font;
1.526     www      6430:   background: $pgbg;
1.521     www      6431:   font-size: larger;
                   6432:   font-weight: bold;
                   6433: }
                   6434: 
1.346     albertel 6435: td.LC_menubuttons_text {
1.911     bisitz   6436:   color: $font;
1.346     albertel 6437: }
1.706     harmsja  6438: 
1.346     albertel 6439: .LC_current_location {
                   6440:   background: $tabbg;
                   6441: }
1.795     www      6442: 
1.938     bisitz   6443: table.LC_data_table {
1.347     albertel 6444:   border: 1px solid #000000;
1.402     albertel 6445:   border-collapse: separate;
1.426     albertel 6446:   border-spacing: 1px;
1.610     albertel 6447:   background: $pgbg;
1.347     albertel 6448: }
1.795     www      6449: 
1.422     albertel 6450: .LC_data_table_dense {
                   6451:   font-size: small;
                   6452: }
1.795     www      6453: 
1.507     raeburn  6454: table.LC_nested_outer {
                   6455:   border: 1px solid #000000;
1.589     raeburn  6456:   border-collapse: collapse;
1.803     bisitz   6457:   border-spacing: 0;
1.507     raeburn  6458:   width: 100%;
                   6459: }
1.795     www      6460: 
1.879     raeburn  6461: table.LC_innerpickbox,
1.507     raeburn  6462: table.LC_nested {
1.803     bisitz   6463:   border: none;
1.589     raeburn  6464:   border-collapse: collapse;
1.803     bisitz   6465:   border-spacing: 0;
1.507     raeburn  6466:   width: 100%;
                   6467: }
1.795     www      6468: 
1.911     bisitz   6469: table.LC_data_table tr th,
                   6470: table.LC_calendar tr th,
1.879     raeburn  6471: table.LC_prior_tries tr th,
                   6472: table.LC_innerpickbox tr th {
1.349     albertel 6473:   font-weight: bold;
                   6474:   background-color: $data_table_head;
1.801     tempelho 6475:   color:$fontmenu;
1.701     harmsja  6476:   font-size:90%;
1.347     albertel 6477: }
1.795     www      6478: 
1.879     raeburn  6479: table.LC_innerpickbox tr th,
                   6480: table.LC_innerpickbox tr td {
                   6481:   vertical-align: top;
                   6482: }
                   6483: 
1.711     raeburn  6484: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6485:   background-color: #CCCCCC;
1.711     raeburn  6486:   font-weight: bold;
                   6487:   text-align: left;
                   6488: }
1.795     www      6489: 
1.912     bisitz   6490: table.LC_data_table tr.LC_odd_row > td {
                   6491:   background-color: $data_table_light;
                   6492:   padding: 2px;
                   6493:   vertical-align: top;
                   6494: }
                   6495: 
1.809     bisitz   6496: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6497:   background-color: $data_table_light;
1.912     bisitz   6498:   vertical-align: top;
                   6499: }
                   6500: 
                   6501: table.LC_data_table tr.LC_even_row > td {
                   6502:   background-color: $data_table_dark;
1.425     albertel 6503:   padding: 2px;
1.900     bisitz   6504:   vertical-align: top;
1.347     albertel 6505: }
1.795     www      6506: 
1.809     bisitz   6507: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6508:   background-color: $data_table_dark;
1.900     bisitz   6509:   vertical-align: top;
1.347     albertel 6510: }
1.795     www      6511: 
1.425     albertel 6512: table.LC_data_table tr.LC_data_table_highlight td {
                   6513:   background-color: $data_table_darker;
                   6514: }
1.795     www      6515: 
1.639     raeburn  6516: table.LC_data_table tr td.LC_leftcol_header {
                   6517:   background-color: $data_table_head;
                   6518:   font-weight: bold;
                   6519: }
1.795     www      6520: 
1.451     albertel 6521: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6522: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6523:   font-weight: bold;
                   6524:   font-style: italic;
                   6525:   text-align: center;
                   6526:   padding: 8px;
1.347     albertel 6527: }
1.795     www      6528: 
1.1114    raeburn  6529: table.LC_data_table tr.LC_empty_row td,
                   6530: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6531:   background-color: $sidebg;
                   6532: }
                   6533: 
                   6534: table.LC_nested tr.LC_empty_row td {
                   6535:   background-color: #FFFFFF;
                   6536: }
                   6537: 
1.890     droeschl 6538: table.LC_caption {
                   6539: }
                   6540: 
1.507     raeburn  6541: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6542:   padding: 4ex
                   6543: }
1.795     www      6544: 
1.507     raeburn  6545: table.LC_nested_outer tr th {
                   6546:   font-weight: bold;
1.801     tempelho 6547:   color:$fontmenu;
1.507     raeburn  6548:   background-color: $data_table_head;
1.701     harmsja  6549:   font-size: small;
1.507     raeburn  6550:   border-bottom: 1px solid #000000;
                   6551: }
1.795     www      6552: 
1.507     raeburn  6553: table.LC_nested_outer tr td.LC_subheader {
                   6554:   background-color: $data_table_head;
                   6555:   font-weight: bold;
                   6556:   font-size: small;
                   6557:   border-bottom: 1px solid #000000;
                   6558:   text-align: right;
1.451     albertel 6559: }
1.795     www      6560: 
1.507     raeburn  6561: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6562:   background-color: #CCCCCC;
1.451     albertel 6563:   font-weight: bold;
                   6564:   font-size: small;
1.507     raeburn  6565:   text-align: center;
                   6566: }
1.795     www      6567: 
1.589     raeburn  6568: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6569: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6570:   text-align: left;
1.451     albertel 6571: }
1.795     www      6572: 
1.507     raeburn  6573: table.LC_nested td {
1.735     bisitz   6574:   background-color: #FFFFFF;
1.451     albertel 6575:   font-size: small;
1.507     raeburn  6576: }
1.795     www      6577: 
1.507     raeburn  6578: table.LC_nested_outer tr th.LC_right_item,
                   6579: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6580: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6581: table.LC_nested tr td.LC_right_item {
1.451     albertel 6582:   text-align: right;
                   6583: }
                   6584: 
1.507     raeburn  6585: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6586:   background-color: #EEEEEE;
1.451     albertel 6587: }
                   6588: 
1.473     raeburn  6589: table.LC_createuser {
                   6590: }
                   6591: 
                   6592: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6593:   font-size: small;
1.473     raeburn  6594: }
                   6595: 
                   6596: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6597:   background-color: #CCCCCC;
1.473     raeburn  6598:   font-weight: bold;
                   6599:   text-align: center;
                   6600: }
                   6601: 
1.349     albertel 6602: table.LC_calendar {
                   6603:   border: 1px solid #000000;
                   6604:   border-collapse: collapse;
1.917     raeburn  6605:   width: 98%;
1.349     albertel 6606: }
1.795     www      6607: 
1.349     albertel 6608: table.LC_calendar_pickdate {
                   6609:   font-size: xx-small;
                   6610: }
1.795     www      6611: 
1.349     albertel 6612: table.LC_calendar tr td {
                   6613:   border: 1px solid #000000;
                   6614:   vertical-align: top;
1.917     raeburn  6615:   width: 14%;
1.349     albertel 6616: }
1.795     www      6617: 
1.349     albertel 6618: table.LC_calendar tr td.LC_calendar_day_empty {
                   6619:   background-color: $data_table_dark;
                   6620: }
1.795     www      6621: 
1.779     bisitz   6622: table.LC_calendar tr td.LC_calendar_day_current {
                   6623:   background-color: $data_table_highlight;
1.777     tempelho 6624: }
1.795     www      6625: 
1.938     bisitz   6626: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6627:   background-color: $mail_new;
                   6628: }
1.795     www      6629: 
1.938     bisitz   6630: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6631:   background-color: $mail_new_hover;
                   6632: }
1.795     www      6633: 
1.938     bisitz   6634: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6635:   background-color: $mail_read;
                   6636: }
1.795     www      6637: 
1.938     bisitz   6638: /*
                   6639: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6640:   background-color: $mail_read_hover;
                   6641: }
1.938     bisitz   6642: */
1.795     www      6643: 
1.938     bisitz   6644: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6645:   background-color: $mail_replied;
                   6646: }
1.795     www      6647: 
1.938     bisitz   6648: /*
                   6649: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6650:   background-color: $mail_replied_hover;
                   6651: }
1.938     bisitz   6652: */
1.795     www      6653: 
1.938     bisitz   6654: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6655:   background-color: $mail_other;
                   6656: }
1.795     www      6657: 
1.938     bisitz   6658: /*
                   6659: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6660:   background-color: $mail_other_hover;
                   6661: }
1.938     bisitz   6662: */
1.494     raeburn  6663: 
1.777     tempelho 6664: table.LC_data_table tr > td.LC_browser_file,
                   6665: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6666:   background: #AAEE77;
1.389     albertel 6667: }
1.795     www      6668: 
1.777     tempelho 6669: table.LC_data_table tr > td.LC_browser_file_locked,
                   6670: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6671:   background: #FFAA99;
1.387     albertel 6672: }
1.795     www      6673: 
1.777     tempelho 6674: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6675:   background: #888888;
1.779     bisitz   6676: }
1.795     www      6677: 
1.777     tempelho 6678: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6679: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6680:   background: #F8F866;
1.777     tempelho 6681: }
1.795     www      6682: 
1.696     bisitz   6683: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6684:   background: #E0E8FF;
1.387     albertel 6685: }
1.696     bisitz   6686: 
1.707     bisitz   6687: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6688:   /* background: #77FF77; */
1.707     bisitz   6689: }
1.795     www      6690: 
1.707     bisitz   6691: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6692:   border-right: 8px solid #FFFF77;
1.707     bisitz   6693: }
1.795     www      6694: 
1.707     bisitz   6695: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6696:   border-right: 8px solid #FFAA77;
1.707     bisitz   6697: }
1.795     www      6698: 
1.707     bisitz   6699: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6700:   border-right: 8px solid #FF7777;
1.707     bisitz   6701: }
1.795     www      6702: 
1.707     bisitz   6703: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6704:   border-right: 8px solid #AAFF77;
1.707     bisitz   6705: }
1.795     www      6706: 
1.707     bisitz   6707: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6708:   border-right: 8px solid #11CC55;
1.707     bisitz   6709: }
                   6710: 
1.388     albertel 6711: span.LC_current_location {
1.701     harmsja  6712:   font-size:larger;
1.388     albertel 6713:   background: $pgbg;
                   6714: }
1.387     albertel 6715: 
1.1029    www      6716: span.LC_current_nav_location {
                   6717:   font-weight:bold;
                   6718:   background: $sidebg;
                   6719: }
                   6720: 
1.395     albertel 6721: span.LC_parm_menu_item {
                   6722:   font-size: larger;
                   6723: }
1.795     www      6724: 
1.395     albertel 6725: span.LC_parm_scope_all {
                   6726:   color: red;
                   6727: }
1.795     www      6728: 
1.395     albertel 6729: span.LC_parm_scope_folder {
                   6730:   color: green;
                   6731: }
1.795     www      6732: 
1.395     albertel 6733: span.LC_parm_scope_resource {
                   6734:   color: orange;
                   6735: }
1.795     www      6736: 
1.395     albertel 6737: span.LC_parm_part {
                   6738:   color: blue;
                   6739: }
1.795     www      6740: 
1.911     bisitz   6741: span.LC_parm_folder,
                   6742: span.LC_parm_symb {
1.395     albertel 6743:   font-size: x-small;
                   6744:   font-family: $mono;
                   6745:   color: #AAAAAA;
                   6746: }
                   6747: 
1.977     bisitz   6748: ul.LC_parm_parmlist li {
                   6749:   display: inline-block;
                   6750:   padding: 0.3em 0.8em;
                   6751:   vertical-align: top;
                   6752:   width: 150px;
                   6753:   border-top:1px solid $lg_border_color;
                   6754: }
                   6755: 
1.795     www      6756: td.LC_parm_overview_level_menu,
                   6757: td.LC_parm_overview_map_menu,
                   6758: td.LC_parm_overview_parm_selectors,
                   6759: td.LC_parm_overview_restrictions  {
1.396     albertel 6760:   border: 1px solid black;
                   6761:   border-collapse: collapse;
                   6762: }
1.795     www      6763: 
1.396     albertel 6764: table.LC_parm_overview_restrictions td {
                   6765:   border-width: 1px 4px 1px 4px;
                   6766:   border-style: solid;
                   6767:   border-color: $pgbg;
                   6768:   text-align: center;
                   6769: }
1.795     www      6770: 
1.396     albertel 6771: table.LC_parm_overview_restrictions th {
                   6772:   background: $tabbg;
                   6773:   border-width: 1px 4px 1px 4px;
                   6774:   border-style: solid;
                   6775:   border-color: $pgbg;
                   6776: }
1.795     www      6777: 
1.398     albertel 6778: table#LC_helpmenu {
1.803     bisitz   6779:   border: none;
1.398     albertel 6780:   height: 55px;
1.803     bisitz   6781:   border-spacing: 0;
1.398     albertel 6782: }
                   6783: 
                   6784: table#LC_helpmenu fieldset legend {
                   6785:   font-size: larger;
                   6786: }
1.795     www      6787: 
1.397     albertel 6788: table#LC_helpmenu_links {
                   6789:   width: 100%;
                   6790:   border: 1px solid black;
                   6791:   background: $pgbg;
1.803     bisitz   6792:   padding: 0;
1.397     albertel 6793:   border-spacing: 1px;
                   6794: }
1.795     www      6795: 
1.397     albertel 6796: table#LC_helpmenu_links tr td {
                   6797:   padding: 1px;
                   6798:   background: $tabbg;
1.399     albertel 6799:   text-align: center;
                   6800:   font-weight: bold;
1.397     albertel 6801: }
1.396     albertel 6802: 
1.795     www      6803: table#LC_helpmenu_links a:link,
                   6804: table#LC_helpmenu_links a:visited,
1.397     albertel 6805: table#LC_helpmenu_links a:active {
                   6806:   text-decoration: none;
                   6807:   color: $font;
                   6808: }
1.795     www      6809: 
1.397     albertel 6810: table#LC_helpmenu_links a:hover {
                   6811:   text-decoration: underline;
                   6812:   color: $vlink;
                   6813: }
1.396     albertel 6814: 
1.417     albertel 6815: .LC_chrt_popup_exists {
                   6816:   border: 1px solid #339933;
                   6817:   margin: -1px;
                   6818: }
1.795     www      6819: 
1.417     albertel 6820: .LC_chrt_popup_up {
                   6821:   border: 1px solid yellow;
                   6822:   margin: -1px;
                   6823: }
1.795     www      6824: 
1.417     albertel 6825: .LC_chrt_popup {
                   6826:   border: 1px solid #8888FF;
                   6827:   background: #CCCCFF;
                   6828: }
1.795     www      6829: 
1.421     albertel 6830: table.LC_pick_box {
                   6831:   border-collapse: separate;
                   6832:   background: white;
                   6833:   border: 1px solid black;
                   6834:   border-spacing: 1px;
                   6835: }
1.795     www      6836: 
1.421     albertel 6837: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6838:   background: $sidebg;
1.421     albertel 6839:   font-weight: bold;
1.900     bisitz   6840:   text-align: left;
1.740     bisitz   6841:   vertical-align: top;
1.421     albertel 6842:   width: 184px;
                   6843:   padding: 8px;
                   6844: }
1.795     www      6845: 
1.579     raeburn  6846: table.LC_pick_box td.LC_pick_box_value {
                   6847:   text-align: left;
                   6848:   padding: 8px;
                   6849: }
1.795     www      6850: 
1.579     raeburn  6851: table.LC_pick_box td.LC_pick_box_select {
                   6852:   text-align: left;
                   6853:   padding: 8px;
                   6854: }
1.795     www      6855: 
1.424     albertel 6856: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6857:   padding: 0;
1.421     albertel 6858:   height: 1px;
                   6859:   background: black;
                   6860: }
1.795     www      6861: 
1.421     albertel 6862: table.LC_pick_box td.LC_pick_box_submit {
                   6863:   text-align: right;
                   6864: }
1.795     www      6865: 
1.579     raeburn  6866: table.LC_pick_box td.LC_evenrow_value {
                   6867:   text-align: left;
                   6868:   padding: 8px;
                   6869:   background-color: $data_table_light;
                   6870: }
1.795     www      6871: 
1.579     raeburn  6872: table.LC_pick_box td.LC_oddrow_value {
                   6873:   text-align: left;
                   6874:   padding: 8px;
                   6875:   background-color: $data_table_light;
                   6876: }
1.795     www      6877: 
1.579     raeburn  6878: span.LC_helpform_receipt_cat {
                   6879:   font-weight: bold;
                   6880: }
1.795     www      6881: 
1.424     albertel 6882: table.LC_group_priv_box {
                   6883:   background: white;
                   6884:   border: 1px solid black;
                   6885:   border-spacing: 1px;
                   6886: }
1.795     www      6887: 
1.424     albertel 6888: table.LC_group_priv_box td.LC_pick_box_title {
                   6889:   background: $tabbg;
                   6890:   font-weight: bold;
                   6891:   text-align: right;
                   6892:   width: 184px;
                   6893: }
1.795     www      6894: 
1.424     albertel 6895: table.LC_group_priv_box td.LC_groups_fixed {
                   6896:   background: $data_table_light;
                   6897:   text-align: center;
                   6898: }
1.795     www      6899: 
1.424     albertel 6900: table.LC_group_priv_box td.LC_groups_optional {
                   6901:   background: $data_table_dark;
                   6902:   text-align: center;
                   6903: }
1.795     www      6904: 
1.424     albertel 6905: table.LC_group_priv_box td.LC_groups_functionality {
                   6906:   background: $data_table_darker;
                   6907:   text-align: center;
                   6908:   font-weight: bold;
                   6909: }
1.795     www      6910: 
1.424     albertel 6911: table.LC_group_priv td {
                   6912:   text-align: left;
1.803     bisitz   6913:   padding: 0;
1.424     albertel 6914: }
                   6915: 
                   6916: .LC_navbuttons {
                   6917:   margin: 2ex 0ex 2ex 0ex;
                   6918: }
1.795     www      6919: 
1.423     albertel 6920: .LC_topic_bar {
                   6921:   font-weight: bold;
                   6922:   background: $tabbg;
1.918     wenzelju 6923:   margin: 1em 0em 1em 2em;
1.805     bisitz   6924:   padding: 3px;
1.918     wenzelju 6925:   font-size: 1.2em;
1.423     albertel 6926: }
1.795     www      6927: 
1.423     albertel 6928: .LC_topic_bar span {
1.918     wenzelju 6929:   left: 0.5em;
                   6930:   position: absolute;
1.423     albertel 6931:   vertical-align: middle;
1.918     wenzelju 6932:   font-size: 1.2em;
1.423     albertel 6933: }
1.795     www      6934: 
1.423     albertel 6935: table.LC_course_group_status {
                   6936:   margin: 20px;
                   6937: }
1.795     www      6938: 
1.423     albertel 6939: table.LC_status_selector td {
                   6940:   vertical-align: top;
                   6941:   text-align: center;
1.424     albertel 6942:   padding: 4px;
                   6943: }
1.795     www      6944: 
1.599     albertel 6945: div.LC_feedback_link {
1.616     albertel 6946:   clear: both;
1.829     kalberla 6947:   background: $sidebg;
1.779     bisitz   6948:   width: 100%;
1.829     kalberla 6949:   padding-bottom: 10px;
                   6950:   border: 1px $tabbg solid;
1.833     kalberla 6951:   height: 22px;
                   6952:   line-height: 22px;
                   6953:   padding-top: 5px;
                   6954: }
                   6955: 
                   6956: div.LC_feedback_link img {
                   6957:   height: 22px;
1.867     kalberla 6958:   vertical-align:middle;
1.829     kalberla 6959: }
                   6960: 
1.911     bisitz   6961: div.LC_feedback_link a {
1.829     kalberla 6962:   text-decoration: none;
1.489     raeburn  6963: }
1.795     www      6964: 
1.867     kalberla 6965: div.LC_comblock {
1.911     bisitz   6966:   display:inline;
1.867     kalberla 6967:   color:$font;
                   6968:   font-size:90%;
                   6969: }
                   6970: 
                   6971: div.LC_feedback_link div.LC_comblock {
                   6972:   padding-left:5px;
                   6973: }
                   6974: 
                   6975: div.LC_feedback_link div.LC_comblock a {
                   6976:   color:$font;
                   6977: }
                   6978: 
1.489     raeburn  6979: span.LC_feedback_link {
1.858     bisitz   6980:   /* background: $feedback_link_bg; */
1.599     albertel 6981:   font-size: larger;
                   6982: }
1.795     www      6983: 
1.599     albertel 6984: span.LC_message_link {
1.858     bisitz   6985:   /* background: $feedback_link_bg; */
1.599     albertel 6986:   font-size: larger;
                   6987:   position: absolute;
                   6988:   right: 1em;
1.489     raeburn  6989: }
1.421     albertel 6990: 
1.515     albertel 6991: table.LC_prior_tries {
1.524     albertel 6992:   border: 1px solid #000000;
                   6993:   border-collapse: separate;
                   6994:   border-spacing: 1px;
1.515     albertel 6995: }
1.523     albertel 6996: 
1.515     albertel 6997: table.LC_prior_tries td {
1.524     albertel 6998:   padding: 2px;
1.515     albertel 6999: }
1.523     albertel 7000: 
                   7001: .LC_answer_correct {
1.795     www      7002:   background: lightgreen;
                   7003:   color: darkgreen;
                   7004:   padding: 6px;
1.523     albertel 7005: }
1.795     www      7006: 
1.523     albertel 7007: .LC_answer_charged_try {
1.797     www      7008:   background: #FFAAAA;
1.795     www      7009:   color: darkred;
                   7010:   padding: 6px;
1.523     albertel 7011: }
1.795     www      7012: 
1.779     bisitz   7013: .LC_answer_not_charged_try,
1.523     albertel 7014: .LC_answer_no_grade,
                   7015: .LC_answer_late {
1.795     www      7016:   background: lightyellow;
1.523     albertel 7017:   color: black;
1.795     www      7018:   padding: 6px;
1.523     albertel 7019: }
1.795     www      7020: 
1.523     albertel 7021: .LC_answer_previous {
1.795     www      7022:   background: lightblue;
                   7023:   color: darkblue;
                   7024:   padding: 6px;
1.523     albertel 7025: }
1.795     www      7026: 
1.779     bisitz   7027: .LC_answer_no_message {
1.777     tempelho 7028:   background: #FFFFFF;
                   7029:   color: black;
1.795     www      7030:   padding: 6px;
1.779     bisitz   7031: }
1.795     www      7032: 
1.779     bisitz   7033: .LC_answer_unknown {
                   7034:   background: orange;
                   7035:   color: black;
1.795     www      7036:   padding: 6px;
1.777     tempelho 7037: }
1.795     www      7038: 
1.529     albertel 7039: span.LC_prior_numerical,
                   7040: span.LC_prior_string,
                   7041: span.LC_prior_custom,
                   7042: span.LC_prior_reaction,
                   7043: span.LC_prior_math {
1.925     bisitz   7044:   font-family: $mono;
1.523     albertel 7045:   white-space: pre;
                   7046: }
                   7047: 
1.525     albertel 7048: span.LC_prior_string {
1.925     bisitz   7049:   font-family: $mono;
1.525     albertel 7050:   white-space: pre;
                   7051: }
                   7052: 
1.523     albertel 7053: table.LC_prior_option {
                   7054:   width: 100%;
                   7055:   border-collapse: collapse;
                   7056: }
1.795     www      7057: 
1.911     bisitz   7058: table.LC_prior_rank,
1.795     www      7059: table.LC_prior_match {
1.528     albertel 7060:   border-collapse: collapse;
                   7061: }
1.795     www      7062: 
1.528     albertel 7063: table.LC_prior_option tr td,
                   7064: table.LC_prior_rank tr td,
                   7065: table.LC_prior_match tr td {
1.524     albertel 7066:   border: 1px solid #000000;
1.515     albertel 7067: }
                   7068: 
1.855     bisitz   7069: .LC_nobreak {
1.544     albertel 7070:   white-space: nowrap;
1.519     raeburn  7071: }
                   7072: 
1.576     raeburn  7073: span.LC_cusr_emph {
                   7074:   font-style: italic;
                   7075: }
                   7076: 
1.633     raeburn  7077: span.LC_cusr_subheading {
                   7078:   font-weight: normal;
                   7079:   font-size: 85%;
                   7080: }
                   7081: 
1.861     bisitz   7082: div.LC_docs_entry_move {
1.859     bisitz   7083:   border: 1px solid #BBBBBB;
1.545     albertel 7084:   background: #DDDDDD;
1.861     bisitz   7085:   width: 22px;
1.859     bisitz   7086:   padding: 1px;
                   7087:   margin: 0;
1.545     albertel 7088: }
                   7089: 
1.861     bisitz   7090: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7091: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7092:   font-size: x-small;
                   7093: }
1.795     www      7094: 
1.861     bisitz   7095: .LC_docs_entry_parameter {
                   7096:   white-space: nowrap;
                   7097: }
                   7098: 
1.544     albertel 7099: .LC_docs_copy {
1.545     albertel 7100:   color: #000099;
1.544     albertel 7101: }
1.795     www      7102: 
1.544     albertel 7103: .LC_docs_cut {
1.545     albertel 7104:   color: #550044;
1.544     albertel 7105: }
1.795     www      7106: 
1.544     albertel 7107: .LC_docs_rename {
1.545     albertel 7108:   color: #009900;
1.544     albertel 7109: }
1.795     www      7110: 
1.544     albertel 7111: .LC_docs_remove {
1.545     albertel 7112:   color: #990000;
                   7113: }
                   7114: 
1.547     albertel 7115: .LC_docs_reinit_warn,
                   7116: .LC_docs_ext_edit {
                   7117:   font-size: x-small;
                   7118: }
                   7119: 
1.545     albertel 7120: table.LC_docs_adddocs td,
                   7121: table.LC_docs_adddocs th {
                   7122:   border: 1px solid #BBBBBB;
                   7123:   padding: 4px;
                   7124:   background: #DDDDDD;
1.543     albertel 7125: }
                   7126: 
1.584     albertel 7127: table.LC_sty_begin {
                   7128:   background: #BBFFBB;
                   7129: }
1.795     www      7130: 
1.584     albertel 7131: table.LC_sty_end {
                   7132:   background: #FFBBBB;
                   7133: }
                   7134: 
1.589     raeburn  7135: table.LC_double_column {
1.803     bisitz   7136:   border-width: 0;
1.589     raeburn  7137:   border-collapse: collapse;
                   7138:   width: 100%;
                   7139:   padding: 2px;
                   7140: }
                   7141: 
                   7142: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7143:   top: 2px;
1.589     raeburn  7144:   left: 2px;
                   7145:   width: 47%;
                   7146:   vertical-align: top;
                   7147: }
                   7148: 
                   7149: table.LC_double_column tr td.LC_right_col {
                   7150:   top: 2px;
1.779     bisitz   7151:   right: 2px;
1.589     raeburn  7152:   width: 47%;
                   7153:   vertical-align: top;
                   7154: }
                   7155: 
1.591     raeburn  7156: div.LC_left_float {
                   7157:   float: left;
                   7158:   padding-right: 5%;
1.597     albertel 7159:   padding-bottom: 4px;
1.591     raeburn  7160: }
                   7161: 
                   7162: div.LC_clear_float_header {
1.597     albertel 7163:   padding-bottom: 2px;
1.591     raeburn  7164: }
                   7165: 
                   7166: div.LC_clear_float_footer {
1.597     albertel 7167:   padding-top: 10px;
1.591     raeburn  7168:   clear: both;
                   7169: }
                   7170: 
1.597     albertel 7171: div.LC_grade_show_user {
1.941     bisitz   7172: /*  border-left: 5px solid $sidebg; */
                   7173:   border-top: 5px solid #000000;
                   7174:   margin: 50px 0 0 0;
1.936     bisitz   7175:   padding: 15px 0 5px 10px;
1.597     albertel 7176: }
1.795     www      7177: 
1.936     bisitz   7178: div.LC_grade_show_user_odd_row {
1.941     bisitz   7179: /*  border-left: 5px solid #000000; */
                   7180: }
                   7181: 
                   7182: div.LC_grade_show_user div.LC_Box {
                   7183:   margin-right: 50px;
1.597     albertel 7184: }
                   7185: 
                   7186: div.LC_grade_submissions,
                   7187: div.LC_grade_message_center,
1.936     bisitz   7188: div.LC_grade_info_links {
1.597     albertel 7189:   margin: 5px;
                   7190:   width: 99%;
                   7191:   background: #FFFFFF;
                   7192: }
1.795     www      7193: 
1.597     albertel 7194: div.LC_grade_submissions_header,
1.936     bisitz   7195: div.LC_grade_message_center_header {
1.705     tempelho 7196:   font-weight: bold;
                   7197:   font-size: large;
1.597     albertel 7198: }
1.795     www      7199: 
1.597     albertel 7200: div.LC_grade_submissions_body,
1.936     bisitz   7201: div.LC_grade_message_center_body {
1.597     albertel 7202:   border: 1px solid black;
                   7203:   width: 99%;
                   7204:   background: #FFFFFF;
                   7205: }
1.795     www      7206: 
1.613     albertel 7207: table.LC_scantron_action {
                   7208:   width: 100%;
                   7209: }
1.795     www      7210: 
1.613     albertel 7211: table.LC_scantron_action tr th {
1.698     harmsja  7212:   font-weight:bold;
                   7213:   font-style:normal;
1.613     albertel 7214: }
1.795     www      7215: 
1.779     bisitz   7216: .LC_edit_problem_header,
1.614     albertel 7217: div.LC_edit_problem_footer {
1.705     tempelho 7218:   font-weight: normal;
                   7219:   font-size:  medium;
1.602     albertel 7220:   margin: 2px;
1.1060    bisitz   7221:   background-color: $sidebg;
1.600     albertel 7222: }
1.795     www      7223: 
1.600     albertel 7224: div.LC_edit_problem_header,
1.602     albertel 7225: div.LC_edit_problem_header div,
1.614     albertel 7226: div.LC_edit_problem_footer,
                   7227: div.LC_edit_problem_footer div,
1.602     albertel 7228: div.LC_edit_problem_editxml_header,
                   7229: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7230:   z-index: 100;
1.600     albertel 7231: }
1.795     www      7232: 
1.600     albertel 7233: div.LC_edit_problem_header_title {
1.705     tempelho 7234:   font-weight: bold;
                   7235:   font-size: larger;
1.602     albertel 7236:   background: $tabbg;
                   7237:   padding: 3px;
1.1060    bisitz   7238:   margin: 0 0 5px 0;
1.602     albertel 7239: }
1.795     www      7240: 
1.602     albertel 7241: table.LC_edit_problem_header_title {
                   7242:   width: 100%;
1.600     albertel 7243:   background: $tabbg;
1.602     albertel 7244: }
                   7245: 
1.1205    golterma 7246: div.LC_edit_actionbar {
                   7247:     background-color: $sidebg;
1.1218    droeschl 7248:     margin: 0;
                   7249:     padding: 0;
                   7250:     line-height: 200%;
1.602     albertel 7251: }
1.795     www      7252: 
1.1218    droeschl 7253: div.LC_edit_actionbar div{
                   7254:     padding: 0;
                   7255:     margin: 0;
                   7256:     display: inline-block;
1.600     albertel 7257: }
1.795     www      7258: 
1.1124    bisitz   7259: .LC_edit_opt {
                   7260:   padding-left: 1em;
                   7261:   white-space: nowrap;
                   7262: }
                   7263: 
1.1152    golterma 7264: .LC_edit_problem_latexhelper{
                   7265:     text-align: right;
                   7266: }
                   7267: 
                   7268: #LC_edit_problem_colorful div{
                   7269:     margin-left: 40px;
                   7270: }
                   7271: 
1.1205    golterma 7272: #LC_edit_problem_codemirror div{
                   7273:     margin-left: 0px;
                   7274: }
                   7275: 
1.911     bisitz   7276: img.stift {
1.803     bisitz   7277:   border-width: 0;
                   7278:   vertical-align: middle;
1.677     riegler  7279: }
1.680     riegler  7280: 
1.923     bisitz   7281: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7282:   vertical-align: top;
1.777     tempelho 7283: }
1.795     www      7284: 
1.716     raeburn  7285: div.LC_createcourse {
1.911     bisitz   7286:   margin: 10px 10px 10px 10px;
1.716     raeburn  7287: }
                   7288: 
1.917     raeburn  7289: .LC_dccid {
1.1130    raeburn  7290:   float: right;
1.917     raeburn  7291:   margin: 0.2em 0 0 0;
                   7292:   padding: 0;
                   7293:   font-size: 90%;
                   7294:   display:none;
                   7295: }
                   7296: 
1.897     wenzelju 7297: ol.LC_primary_menu a:hover,
1.721     harmsja  7298: ol#LC_MenuBreadcrumbs a:hover,
                   7299: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7300: ul#LC_secondary_menu a:hover,
1.721     harmsja  7301: .LC_FormSectionClearButton input:hover
1.795     www      7302: ul.LC_TabContent   li:hover a {
1.952     onken    7303:   color:$button_hover;
1.911     bisitz   7304:   text-decoration:none;
1.693     droeschl 7305: }
                   7306: 
1.779     bisitz   7307: h1 {
1.911     bisitz   7308:   padding: 0;
                   7309:   line-height:130%;
1.693     droeschl 7310: }
1.698     harmsja  7311: 
1.911     bisitz   7312: h2,
                   7313: h3,
                   7314: h4,
                   7315: h5,
                   7316: h6 {
                   7317:   margin: 5px 0 5px 0;
                   7318:   padding: 0;
                   7319:   line-height:130%;
1.693     droeschl 7320: }
1.795     www      7321: 
                   7322: .LC_hcell {
1.911     bisitz   7323:   padding:3px 15px 3px 15px;
                   7324:   margin: 0;
                   7325:   background-color:$tabbg;
                   7326:   color:$fontmenu;
                   7327:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7328: }
1.795     www      7329: 
1.840     bisitz   7330: .LC_Box > .LC_hcell {
1.911     bisitz   7331:   margin: 0 -10px 10px -10px;
1.835     bisitz   7332: }
                   7333: 
1.721     harmsja  7334: .LC_noBorder {
1.911     bisitz   7335:   border: 0;
1.698     harmsja  7336: }
1.693     droeschl 7337: 
1.721     harmsja  7338: .LC_FormSectionClearButton input {
1.911     bisitz   7339:   background-color:transparent;
                   7340:   border: none;
                   7341:   cursor:pointer;
                   7342:   text-decoration:underline;
1.693     droeschl 7343: }
1.763     bisitz   7344: 
                   7345: .LC_help_open_topic {
1.911     bisitz   7346:   color: #FFFFFF;
                   7347:   background-color: #EEEEFF;
                   7348:   margin: 1px;
                   7349:   padding: 4px;
                   7350:   border: 1px solid #000033;
                   7351:   white-space: nowrap;
                   7352:   /* vertical-align: middle; */
1.759     neumanie 7353: }
1.693     droeschl 7354: 
1.911     bisitz   7355: dl,
                   7356: ul,
                   7357: div,
                   7358: fieldset {
                   7359:   margin: 10px 10px 10px 0;
                   7360:   /* overflow: hidden; */
1.693     droeschl 7361: }
1.795     www      7362: 
1.1211    raeburn  7363: article.geogebraweb div {
                   7364:     margin: 0;
                   7365: }
                   7366: 
1.838     bisitz   7367: fieldset > legend {
1.911     bisitz   7368:   font-weight: bold;
                   7369:   padding: 0 5px 0 5px;
1.838     bisitz   7370: }
                   7371: 
1.813     bisitz   7372: #LC_nav_bar {
1.911     bisitz   7373:   float: left;
1.995     raeburn  7374:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7375:   margin: 0 0 2px 0;
1.807     droeschl 7376: }
                   7377: 
1.916     droeschl 7378: #LC_realm {
                   7379:   margin: 0.2em 0 0 0;
                   7380:   padding: 0;
                   7381:   font-weight: bold;
                   7382:   text-align: center;
1.995     raeburn  7383:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7384: }
                   7385: 
1.911     bisitz   7386: #LC_nav_bar em {
                   7387:   font-weight: bold;
                   7388:   font-style: normal;
1.807     droeschl 7389: }
                   7390: 
1.897     wenzelju 7391: ol.LC_primary_menu {
1.934     droeschl 7392:   margin: 0;
1.1076    raeburn  7393:   padding: 0;
1.807     droeschl 7394: }
                   7395: 
1.852     droeschl 7396: ol#LC_PathBreadcrumbs {
1.911     bisitz   7397:   margin: 0;
1.693     droeschl 7398: }
                   7399: 
1.897     wenzelju 7400: ol.LC_primary_menu li {
1.1076    raeburn  7401:   color: RGB(80, 80, 80);
                   7402:   vertical-align: middle;
                   7403:   text-align: left;
                   7404:   list-style: none;
1.1205    golterma 7405:   position: relative;
1.1076    raeburn  7406:   float: left;
1.1205    golterma 7407:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7408:   line-height: 1.5em;
1.1076    raeburn  7409: }
                   7410: 
1.1205    golterma 7411: ol.LC_primary_menu li a,
                   7412: ol.LC_primary_menu li p {
1.1076    raeburn  7413:   display: block;
                   7414:   margin: 0;
                   7415:   padding: 0 5px 0 10px;
                   7416:   text-decoration: none;
                   7417: }
                   7418: 
1.1205    golterma 7419: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7420:   display: inline-block;
                   7421:   width: 95%;
                   7422:   text-align: left;
                   7423: }
                   7424: 
                   7425: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7426:   display: inline-block;	
                   7427:   width: 5%;
                   7428:   float: right;
                   7429:   text-align: right;
                   7430:   font-size: 70%;
                   7431: }
                   7432: 
                   7433: ol.LC_primary_menu ul {
1.1076    raeburn  7434:   display: none;
1.1205    golterma 7435:   width: 15em;
1.1076    raeburn  7436:   background-color: $data_table_light;
1.1205    golterma 7437:   position: absolute;
                   7438:   top: 100%;
1.1076    raeburn  7439: }
                   7440: 
1.1205    golterma 7441: ol.LC_primary_menu ul ul {
                   7442:   left: 100%;
                   7443:   top: 0;
                   7444: }
                   7445: 
                   7446: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7447:   display: block;
                   7448:   position: absolute;
                   7449:   margin: 0;
                   7450:   padding: 0;
1.1078    raeburn  7451:   z-index: 2;
1.1076    raeburn  7452: }
                   7453: 
                   7454: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7455: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7456:   font-size: 90%;
1.911     bisitz   7457:   vertical-align: top;
1.1076    raeburn  7458:   float: none;
1.1079    raeburn  7459:   border-left: 1px solid black;
                   7460:   border-right: 1px solid black;
1.1205    golterma 7461: /* A dark bottom border to visualize different menu options; 
                   7462: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7463:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7464: }
                   7465: 
1.1205    golterma 7466: ol.LC_primary_menu li li p:hover {
                   7467:   color:$button_hover;
                   7468:   text-decoration:none;
                   7469:   background-color:$data_table_dark;
1.1076    raeburn  7470: }
                   7471: 
                   7472: ol.LC_primary_menu li li a:hover {
                   7473:    color:$button_hover;
                   7474:    background-color:$data_table_dark;
1.693     droeschl 7475: }
                   7476: 
1.1205    golterma 7477: /* Font-size equal to the size of the predecessors*/
                   7478: ol.LC_primary_menu li:hover li li {
                   7479:   font-size: 100%;
                   7480: }
                   7481: 
1.897     wenzelju 7482: ol.LC_primary_menu li img {
1.911     bisitz   7483:   vertical-align: bottom;
1.934     droeschl 7484:   height: 1.1em;
1.1077    raeburn  7485:   margin: 0.2em 0 0 0;
1.693     droeschl 7486: }
                   7487: 
1.897     wenzelju 7488: ol.LC_primary_menu a {
1.911     bisitz   7489:   color: RGB(80, 80, 80);
                   7490:   text-decoration: none;
1.693     droeschl 7491: }
1.795     www      7492: 
1.949     droeschl 7493: ol.LC_primary_menu a.LC_new_message {
                   7494:   font-weight:bold;
                   7495:   color: darkred;
                   7496: }
                   7497: 
1.975     raeburn  7498: ol.LC_docs_parameters {
                   7499:   margin-left: 0;
                   7500:   padding: 0;
                   7501:   list-style: none;
                   7502: }
                   7503: 
                   7504: ol.LC_docs_parameters li {
                   7505:   margin: 0;
                   7506:   padding-right: 20px;
                   7507:   display: inline;
                   7508: }
                   7509: 
1.976     raeburn  7510: ol.LC_docs_parameters li:before {
                   7511:   content: "\\002022 \\0020";
                   7512: }
                   7513: 
                   7514: li.LC_docs_parameters_title {
                   7515:   font-weight: bold;
                   7516: }
                   7517: 
                   7518: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7519:   content: "";
                   7520: }
                   7521: 
1.897     wenzelju 7522: ul#LC_secondary_menu {
1.1107    raeburn  7523:   clear: right;
1.911     bisitz   7524:   color: $fontmenu;
                   7525:   background: $tabbg;
                   7526:   list-style: none;
                   7527:   padding: 0;
                   7528:   margin: 0;
                   7529:   width: 100%;
1.995     raeburn  7530:   text-align: left;
1.1107    raeburn  7531:   float: left;
1.808     droeschl 7532: }
                   7533: 
1.897     wenzelju 7534: ul#LC_secondary_menu li {
1.911     bisitz   7535:   font-weight: bold;
                   7536:   line-height: 1.8em;
1.1107    raeburn  7537:   border-right: 1px solid black;
                   7538:   float: left;
                   7539: }
                   7540: 
                   7541: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7542:   background-color: $data_table_light;
                   7543: }
                   7544: 
                   7545: ul#LC_secondary_menu li a {
1.911     bisitz   7546:   padding: 0 0.8em;
1.1107    raeburn  7547: }
                   7548: 
                   7549: ul#LC_secondary_menu li ul {
                   7550:   display: none;
                   7551: }
                   7552: 
                   7553: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7554:   display: block;
                   7555:   position: absolute;
                   7556:   margin: 0;
                   7557:   padding: 0;
                   7558:   list-style:none;
                   7559:   float: none;
                   7560:   background-color: $data_table_light;
                   7561:   z-index: 2;
                   7562:   margin-left: -1px;
                   7563: }
                   7564: 
                   7565: ul#LC_secondary_menu li ul li {
                   7566:   font-size: 90%;
                   7567:   vertical-align: top;
                   7568:   border-left: 1px solid black;
1.911     bisitz   7569:   border-right: 1px solid black;
1.1119    raeburn  7570:   background-color: $data_table_light;
1.1107    raeburn  7571:   list-style:none;
                   7572:   float: none;
                   7573: }
                   7574: 
                   7575: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7576:   background-color: $data_table_dark;
1.807     droeschl 7577: }
                   7578: 
1.847     tempelho 7579: ul.LC_TabContent {
1.911     bisitz   7580:   display:block;
                   7581:   background: $sidebg;
                   7582:   border-bottom: solid 1px $lg_border_color;
                   7583:   list-style:none;
1.1020    raeburn  7584:   margin: -1px -10px 0 -10px;
1.911     bisitz   7585:   padding: 0;
1.693     droeschl 7586: }
                   7587: 
1.795     www      7588: ul.LC_TabContent li,
                   7589: ul.LC_TabContentBigger li {
1.911     bisitz   7590:   float:left;
1.741     harmsja  7591: }
1.795     www      7592: 
1.897     wenzelju 7593: ul#LC_secondary_menu li a {
1.911     bisitz   7594:   color: $fontmenu;
                   7595:   text-decoration: none;
1.693     droeschl 7596: }
1.795     www      7597: 
1.721     harmsja  7598: ul.LC_TabContent {
1.952     onken    7599:   min-height:20px;
1.721     harmsja  7600: }
1.795     www      7601: 
                   7602: ul.LC_TabContent li {
1.911     bisitz   7603:   vertical-align:middle;
1.959     onken    7604:   padding: 0 16px 0 10px;
1.911     bisitz   7605:   background-color:$tabbg;
                   7606:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7607:   border-left: solid 1px $font;
1.721     harmsja  7608: }
1.795     www      7609: 
1.847     tempelho 7610: ul.LC_TabContent .right {
1.911     bisitz   7611:   float:right;
1.847     tempelho 7612: }
                   7613: 
1.911     bisitz   7614: ul.LC_TabContent li a,
                   7615: ul.LC_TabContent li {
                   7616:   color:rgb(47,47,47);
                   7617:   text-decoration:none;
                   7618:   font-size:95%;
                   7619:   font-weight:bold;
1.952     onken    7620:   min-height:20px;
                   7621: }
                   7622: 
1.959     onken    7623: ul.LC_TabContent li a:hover,
                   7624: ul.LC_TabContent li a:focus {
1.952     onken    7625:   color: $button_hover;
1.959     onken    7626:   background:none;
                   7627:   outline:none;
1.952     onken    7628: }
                   7629: 
                   7630: ul.LC_TabContent li:hover {
                   7631:   color: $button_hover;
                   7632:   cursor:pointer;
1.721     harmsja  7633: }
1.795     www      7634: 
1.911     bisitz   7635: ul.LC_TabContent li.active {
1.952     onken    7636:   color: $font;
1.911     bisitz   7637:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7638:   border-bottom:solid 1px #FFFFFF;
                   7639:   cursor: default;
1.744     ehlerst  7640: }
1.795     www      7641: 
1.959     onken    7642: ul.LC_TabContent li.active a {
                   7643:   color:$font;
                   7644:   background:#FFFFFF;
                   7645:   outline: none;
                   7646: }
1.1047    raeburn  7647: 
                   7648: ul.LC_TabContent li.goback {
                   7649:   float: left;
                   7650:   border-left: none;
                   7651: }
                   7652: 
1.870     tempelho 7653: #maincoursedoc {
1.911     bisitz   7654:   clear:both;
1.870     tempelho 7655: }
                   7656: 
                   7657: ul.LC_TabContentBigger {
1.911     bisitz   7658:   display:block;
                   7659:   list-style:none;
                   7660:   padding: 0;
1.870     tempelho 7661: }
                   7662: 
1.795     www      7663: ul.LC_TabContentBigger li {
1.911     bisitz   7664:   vertical-align:bottom;
                   7665:   height: 30px;
                   7666:   font-size:110%;
                   7667:   font-weight:bold;
                   7668:   color: #737373;
1.841     tempelho 7669: }
                   7670: 
1.957     onken    7671: ul.LC_TabContentBigger li.active {
                   7672:   position: relative;
                   7673:   top: 1px;
                   7674: }
                   7675: 
1.870     tempelho 7676: ul.LC_TabContentBigger li a {
1.911     bisitz   7677:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7678:   height: 30px;
                   7679:   line-height: 30px;
                   7680:   text-align: center;
                   7681:   display: block;
                   7682:   text-decoration: none;
1.958     onken    7683:   outline: none;  
1.741     harmsja  7684: }
1.795     www      7685: 
1.870     tempelho 7686: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7687:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7688:   color:$font;
1.744     ehlerst  7689: }
1.795     www      7690: 
1.870     tempelho 7691: ul.LC_TabContentBigger li b {
1.911     bisitz   7692:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7693:   display: block;
                   7694:   float: left;
                   7695:   padding: 0 30px;
1.957     onken    7696:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7697: }
                   7698: 
1.956     onken    7699: ul.LC_TabContentBigger li:hover b {
                   7700:   color:$button_hover;
                   7701: }
                   7702: 
1.870     tempelho 7703: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7704:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7705:   color:$font;
1.957     onken    7706:   border: 0;
1.741     harmsja  7707: }
1.693     droeschl 7708: 
1.870     tempelho 7709: 
1.862     bisitz   7710: ul.LC_CourseBreadcrumbs {
                   7711:   background: $sidebg;
1.1020    raeburn  7712:   height: 2em;
1.862     bisitz   7713:   padding-left: 10px;
1.1020    raeburn  7714:   margin: 0;
1.862     bisitz   7715:   list-style-position: inside;
                   7716: }
                   7717: 
1.911     bisitz   7718: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7719: ol#LC_PathBreadcrumbs {
1.911     bisitz   7720:   padding-left: 10px;
                   7721:   margin: 0;
1.933     droeschl 7722:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7723: }
                   7724: 
1.911     bisitz   7725: ol#LC_MenuBreadcrumbs li,
                   7726: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7727: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7728:   display: inline;
1.933     droeschl 7729:   white-space: normal;  
1.693     droeschl 7730: }
                   7731: 
1.823     bisitz   7732: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7733: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7734:   text-decoration: none;
                   7735:   font-size:90%;
1.693     droeschl 7736: }
1.795     www      7737: 
1.969     droeschl 7738: ol#LC_MenuBreadcrumbs h1 {
                   7739:   display: inline;
                   7740:   font-size: 90%;
                   7741:   line-height: 2.5em;
                   7742:   margin: 0;
                   7743:   padding: 0;
                   7744: }
                   7745: 
1.795     www      7746: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7747:   text-decoration:none;
                   7748:   font-size:100%;
                   7749:   font-weight:bold;
1.693     droeschl 7750: }
1.795     www      7751: 
1.840     bisitz   7752: .LC_Box {
1.911     bisitz   7753:   border: solid 1px $lg_border_color;
                   7754:   padding: 0 10px 10px 10px;
1.746     neumanie 7755: }
1.795     www      7756: 
1.1020    raeburn  7757: .LC_DocsBox {
                   7758:   border: solid 1px $lg_border_color;
                   7759:   padding: 0 0 10px 10px;
                   7760: }
                   7761: 
1.795     www      7762: .LC_AboutMe_Image {
1.911     bisitz   7763:   float:left;
                   7764:   margin-right:10px;
1.747     neumanie 7765: }
1.795     www      7766: 
                   7767: .LC_Clear_AboutMe_Image {
1.911     bisitz   7768:   clear:left;
1.747     neumanie 7769: }
1.795     www      7770: 
1.721     harmsja  7771: dl.LC_ListStyleClean dt {
1.911     bisitz   7772:   padding-right: 5px;
                   7773:   display: table-header-group;
1.693     droeschl 7774: }
                   7775: 
1.721     harmsja  7776: dl.LC_ListStyleClean dd {
1.911     bisitz   7777:   display: table-row;
1.693     droeschl 7778: }
                   7779: 
1.721     harmsja  7780: .LC_ListStyleClean,
                   7781: .LC_ListStyleSimple,
                   7782: .LC_ListStyleNormal,
1.795     www      7783: .LC_ListStyleSpecial {
1.911     bisitz   7784:   /* display:block; */
                   7785:   list-style-position: inside;
                   7786:   list-style-type: none;
                   7787:   overflow: hidden;
                   7788:   padding: 0;
1.693     droeschl 7789: }
                   7790: 
1.721     harmsja  7791: .LC_ListStyleSimple li,
                   7792: .LC_ListStyleSimple dd,
                   7793: .LC_ListStyleNormal li,
                   7794: .LC_ListStyleNormal dd,
                   7795: .LC_ListStyleSpecial li,
1.795     www      7796: .LC_ListStyleSpecial dd {
1.911     bisitz   7797:   margin: 0;
                   7798:   padding: 5px 5px 5px 10px;
                   7799:   clear: both;
1.693     droeschl 7800: }
                   7801: 
1.721     harmsja  7802: .LC_ListStyleClean li,
                   7803: .LC_ListStyleClean dd {
1.911     bisitz   7804:   padding-top: 0;
                   7805:   padding-bottom: 0;
1.693     droeschl 7806: }
                   7807: 
1.721     harmsja  7808: .LC_ListStyleSimple dd,
1.795     www      7809: .LC_ListStyleSimple li {
1.911     bisitz   7810:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7811: }
                   7812: 
1.721     harmsja  7813: .LC_ListStyleSpecial li,
                   7814: .LC_ListStyleSpecial dd {
1.911     bisitz   7815:   list-style-type: none;
                   7816:   background-color: RGB(220, 220, 220);
                   7817:   margin-bottom: 4px;
1.693     droeschl 7818: }
                   7819: 
1.721     harmsja  7820: table.LC_SimpleTable {
1.911     bisitz   7821:   margin:5px;
                   7822:   border:solid 1px $lg_border_color;
1.795     www      7823: }
1.693     droeschl 7824: 
1.721     harmsja  7825: table.LC_SimpleTable tr {
1.911     bisitz   7826:   padding: 0;
                   7827:   border:solid 1px $lg_border_color;
1.693     droeschl 7828: }
1.795     www      7829: 
                   7830: table.LC_SimpleTable thead {
1.911     bisitz   7831:   background:rgb(220,220,220);
1.693     droeschl 7832: }
                   7833: 
1.721     harmsja  7834: div.LC_columnSection {
1.911     bisitz   7835:   display: block;
                   7836:   clear: both;
                   7837:   overflow: hidden;
                   7838:   margin: 0;
1.693     droeschl 7839: }
                   7840: 
1.721     harmsja  7841: div.LC_columnSection>* {
1.911     bisitz   7842:   float: left;
                   7843:   margin: 10px 20px 10px 0;
                   7844:   overflow:hidden;
1.693     droeschl 7845: }
1.721     harmsja  7846: 
1.795     www      7847: table em {
1.911     bisitz   7848:   font-weight: bold;
                   7849:   font-style: normal;
1.748     schulted 7850: }
1.795     www      7851: 
1.779     bisitz   7852: table.LC_tableBrowseRes,
1.795     www      7853: table.LC_tableOfContent {
1.911     bisitz   7854:   border:none;
                   7855:   border-spacing: 1px;
                   7856:   padding: 3px;
                   7857:   background-color: #FFFFFF;
                   7858:   font-size: 90%;
1.753     droeschl 7859: }
1.789     droeschl 7860: 
1.911     bisitz   7861: table.LC_tableOfContent {
                   7862:   border-collapse: collapse;
1.789     droeschl 7863: }
                   7864: 
1.771     droeschl 7865: table.LC_tableBrowseRes a,
1.768     schulted 7866: table.LC_tableOfContent a {
1.911     bisitz   7867:   background-color: transparent;
                   7868:   text-decoration: none;
1.753     droeschl 7869: }
                   7870: 
1.795     www      7871: table.LC_tableOfContent img {
1.911     bisitz   7872:   border: none;
                   7873:   height: 1.3em;
                   7874:   vertical-align: text-bottom;
                   7875:   margin-right: 0.3em;
1.753     droeschl 7876: }
1.757     schulted 7877: 
1.795     www      7878: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7879:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7880: }
                   7881: 
1.795     www      7882: a#LC_content_toolbar_everything {
1.911     bisitz   7883:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7884: }
                   7885: 
1.795     www      7886: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7887:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7888: }
                   7889: 
1.795     www      7890: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7891:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7892: }
                   7893: 
1.795     www      7894: a#LC_content_toolbar_changefolder {
1.911     bisitz   7895:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7896: }
                   7897: 
1.795     www      7898: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7899:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7900: }
                   7901: 
1.1043    raeburn  7902: a#LC_content_toolbar_edittoplevel {
                   7903:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7904: }
                   7905: 
1.795     www      7906: ul#LC_toolbar li a:hover {
1.911     bisitz   7907:   background-position: bottom center;
1.757     schulted 7908: }
                   7909: 
1.795     www      7910: ul#LC_toolbar {
1.911     bisitz   7911:   padding: 0;
                   7912:   margin: 2px;
                   7913:   list-style:none;
                   7914:   position:relative;
                   7915:   background-color:white;
1.1082    raeburn  7916:   overflow: auto;
1.757     schulted 7917: }
                   7918: 
1.795     www      7919: ul#LC_toolbar li {
1.911     bisitz   7920:   border:1px solid white;
                   7921:   padding: 0;
                   7922:   margin: 0;
                   7923:   float: left;
                   7924:   display:inline;
                   7925:   vertical-align:middle;
1.1082    raeburn  7926:   white-space: nowrap;
1.911     bisitz   7927: }
1.757     schulted 7928: 
1.783     amueller 7929: 
1.795     www      7930: a.LC_toolbarItem {
1.911     bisitz   7931:   display:block;
                   7932:   padding: 0;
                   7933:   margin: 0;
                   7934:   height: 32px;
                   7935:   width: 32px;
                   7936:   color:white;
                   7937:   border: none;
                   7938:   background-repeat:no-repeat;
                   7939:   background-color:transparent;
1.757     schulted 7940: }
                   7941: 
1.915     droeschl 7942: ul.LC_funclist {
                   7943:     margin: 0;
                   7944:     padding: 0.5em 1em 0.5em 0;
                   7945: }
                   7946: 
1.933     droeschl 7947: ul.LC_funclist > li:first-child {
                   7948:     font-weight:bold; 
                   7949:     margin-left:0.8em;
                   7950: }
                   7951: 
1.915     droeschl 7952: ul.LC_funclist + ul.LC_funclist {
                   7953:     /* 
                   7954:        left border as a seperator if we have more than
                   7955:        one list 
                   7956:     */
                   7957:     border-left: 1px solid $sidebg;
                   7958:     /* 
                   7959:        this hides the left border behind the border of the 
                   7960:        outer box if element is wrapped to the next 'line' 
                   7961:     */
                   7962:     margin-left: -1px;
                   7963: }
                   7964: 
1.843     bisitz   7965: ul.LC_funclist li {
1.915     droeschl 7966:   display: inline;
1.782     bisitz   7967:   white-space: nowrap;
1.915     droeschl 7968:   margin: 0 0 0 25px;
                   7969:   line-height: 150%;
1.782     bisitz   7970: }
                   7971: 
1.974     wenzelju 7972: .LC_hidden {
                   7973:   display: none;
                   7974: }
                   7975: 
1.1030    www      7976: .LCmodal-overlay {
                   7977: 		position:fixed;
                   7978: 		top:0;
                   7979: 		right:0;
                   7980: 		bottom:0;
                   7981: 		left:0;
                   7982: 		height:100%;
                   7983: 		width:100%;
                   7984: 		margin:0;
                   7985: 		padding:0;
                   7986: 		background:#999;
                   7987: 		opacity:.75;
                   7988: 		filter: alpha(opacity=75);
                   7989: 		-moz-opacity: 0.75;
                   7990: 		z-index:101;
                   7991: }
                   7992: 
                   7993: * html .LCmodal-overlay {   
                   7994: 		position: absolute;
                   7995: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7996: }
                   7997: 
                   7998: .LCmodal-window {
                   7999: 		position:fixed;
                   8000: 		top:50%;
                   8001: 		left:50%;
                   8002: 		margin:0;
                   8003: 		padding:0;
                   8004: 		z-index:102;
                   8005: 	}
                   8006: 
                   8007: * html .LCmodal-window {
                   8008: 		position:absolute;
                   8009: }
                   8010: 
                   8011: .LCclose-window {
                   8012: 		position:absolute;
                   8013: 		width:32px;
                   8014: 		height:32px;
                   8015: 		right:8px;
                   8016: 		top:8px;
                   8017: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8018: 		text-indent:-99999px;
                   8019: 		overflow:hidden;
                   8020: 		cursor:pointer;
                   8021: }
                   8022: 
1.1100    raeburn  8023: /*
1.1231    damieng  8024:   styles used for response display
                   8025: */
                   8026: div.LC_radiofoil, div.LC_rankfoil {
                   8027:   margin: .5em 0em .5em 0em;
                   8028: }
                   8029: table.LC_itemgroup {
                   8030:   margin-top: 1em;
                   8031: }
                   8032: 
                   8033: /*
1.1100    raeburn  8034:   styles used by TTH when "Default set of options to pass to tth/m
                   8035:   when converting TeX" in course settings has been set
                   8036: 
                   8037:   option passed: -t
                   8038: 
                   8039: */
                   8040: 
                   8041: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8042: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8043: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8044: td div.norm {line-height:normal;}
                   8045: 
                   8046: /*
                   8047:   option passed -y3
                   8048: */
                   8049: 
                   8050: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8051: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8052: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8053: 
1.1230    damieng  8054: /*
                   8055:   sections with roles, for content only
                   8056: */
                   8057: section[class^="role-"] {
                   8058:   padding-left: 10px;
                   8059:   padding-right: 5px;
                   8060:   margin-top: 8px;
                   8061:   margin-bottom: 8px;
                   8062:   border: 1px solid #2A4;
                   8063:   border-radius: 5px;
                   8064:   box-shadow: 0px 1px 1px #BBB;
                   8065: }
                   8066: section[class^="role-"]>h1 {
                   8067:   position: relative;
                   8068:   margin: 0px;
                   8069:   padding-top: 10px;
                   8070:   padding-left: 40px;
                   8071: }
                   8072: section[class^="role-"]>h1:before {
                   8073:   position: absolute;
                   8074:   left: -5px;
                   8075:   top: 5px;
                   8076: }
                   8077: section.role-activity>h1:before {
                   8078:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8079: }
                   8080: section.role-advice>h1:before {
                   8081:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8082: }
                   8083: section.role-bibliography>h1:before {
                   8084:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8085: }
                   8086: section.role-citation>h1:before {
                   8087:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8088: }
                   8089: section.role-conclusion>h1:before {
                   8090:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8091: }
                   8092: section.role-definition>h1:before {
                   8093:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8094: }
                   8095: section.role-demonstration>h1:before {
                   8096:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8097: }
                   8098: section.role-example>h1:before {
                   8099:   content:url('/adm/daxe/images/section_icons/example.png');
                   8100: }
                   8101: section.role-explanation>h1:before {
                   8102:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8103: }
                   8104: section.role-introduction>h1:before {
                   8105:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8106: }
                   8107: section.role-method>h1:before {
                   8108:   content:url('/adm/daxe/images/section_icons/method.png');
                   8109: }
                   8110: section.role-more_information>h1:before {
                   8111:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8112: }
                   8113: section.role-objectives>h1:before {
                   8114:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8115: }
                   8116: section.role-prerequisites>h1:before {
                   8117:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8118: }
                   8119: section.role-remark>h1:before {
                   8120:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8121: }
                   8122: section.role-reminder>h1:before {
                   8123:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8124: }
                   8125: section.role-summary>h1:before {
                   8126:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8127: }
                   8128: section.role-syntax>h1:before {
                   8129:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8130: }
                   8131: section.role-warning>h1:before {
                   8132:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8133: }
                   8134: 
1.1269    raeburn  8135: #LC_minitab_header {
                   8136:   float:left;
                   8137:   width:100%;
                   8138:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8139:   font-size:93%;
                   8140:   line-height:normal;
                   8141:   margin: 0.5em 0 0.5em 0;
                   8142: }
                   8143: #LC_minitab_header ul {
                   8144:   margin:0;
                   8145:   padding:10px 10px 0;
                   8146:   list-style:none;
                   8147: }
                   8148: #LC_minitab_header li {
                   8149:   float:left;
                   8150:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8151:   margin:0;
                   8152:   padding:0 0 0 9px;
                   8153: }
                   8154: #LC_minitab_header a {
                   8155:   display:block;
                   8156:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8157:   padding:5px 15px 4px 6px;
                   8158: }
                   8159: #LC_minitab_header #LC_current_minitab {
                   8160:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8161: }
                   8162: #LC_minitab_header #LC_current_minitab a {
                   8163:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8164:   padding-bottom:5px;
                   8165: }
                   8166: 
                   8167: 
1.343     albertel 8168: END
                   8169: }
                   8170: 
1.306     albertel 8171: =pod
                   8172: 
                   8173: =item * &headtag()
                   8174: 
                   8175: Returns a uniform footer for LON-CAPA web pages.
                   8176: 
1.307     albertel 8177: Inputs: $title - optional title for the head
                   8178:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8179:         $args - optional arguments
1.319     albertel 8180:             force_register - if is true call registerurl so the remote is 
                   8181:                              informed
1.415     albertel 8182:             redirect       -> array ref of
                   8183:                                    1- seconds before redirect occurs
                   8184:                                    2- url to redirect to
                   8185:                                    3- whether the side effect should occur
1.315     albertel 8186:                            (side effect of setting 
                   8187:                                $env{'internal.head.redirect'} to the url 
                   8188:                                redirected too)
1.352     albertel 8189:             domain         -> force to color decorate a page for a specific
                   8190:                                domain
                   8191:             function       -> force usage of a specific rolish color scheme
                   8192:             bgcolor        -> override the default page bgcolor
1.460     albertel 8193:             no_auto_mt_title
                   8194:                            -> prevent &mt()ing the title arg
1.464     albertel 8195: 
1.306     albertel 8196: =cut
                   8197: 
                   8198: sub headtag {
1.313     albertel 8199:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8200:     
1.363     albertel 8201:     my $function = $args->{'function'} || &get_users_function();
                   8202:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8203:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8204:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8205:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8206: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8207: 		   #time(),
1.418     albertel 8208: 		   $env{'environment.color.timestamp'},
1.363     albertel 8209: 		   $function,$domain,$bgcolor);
                   8210: 
1.369     www      8211:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8212: 
1.308     albertel 8213:     my $result =
                   8214: 	'<head>'.
1.1160    raeburn  8215: 	&font_settings($args);
1.319     albertel 8216: 
1.1188    raeburn  8217:     my $inhibitprint;
                   8218:     if ($args->{'print_suppress'}) {
                   8219:         $inhibitprint = &print_suppression();
                   8220:     }
1.1064    raeburn  8221: 
1.461     albertel 8222:     if (!$args->{'frameset'}) {
                   8223: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8224:     }
1.962     droeschl 8225:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8226:         $result .= Apache::lonxml::display_title();
1.319     albertel 8227:     }
1.436     albertel 8228:     if (!$args->{'no_nav_bar'} 
                   8229: 	&& !$args->{'only_body'}
                   8230: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8231: 	$result .= &help_menu_js($httphost);
1.1032    www      8232:         $result.=&modal_window();
1.1038    www      8233:         $result.=&togglebox_script();
1.1034    www      8234:         $result.=&wishlist_window();
1.1041    www      8235:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8236:     } else {
                   8237:         if ($args->{'add_modal'}) {
                   8238:            $result.=&modal_window();
                   8239:         }
                   8240:         if ($args->{'add_wishlist'}) {
                   8241:            $result.=&wishlist_window();
                   8242:         }
1.1038    www      8243:         if ($args->{'add_togglebox'}) {
                   8244:            $result.=&togglebox_script();
                   8245:         }
1.1041    www      8246:         if ($args->{'add_progressbar'}) {
                   8247:            $result.=&LCprogressbarUpdate_script();
                   8248:         }
1.436     albertel 8249:     }
1.314     albertel 8250:     if (ref($args->{'redirect'})) {
1.414     albertel 8251: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8252: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8253: 	if (!$inhibit_continue) {
                   8254: 	    $env{'internal.head.redirect'} = $url;
                   8255: 	}
1.313     albertel 8256: 	$result.=<<ADDMETA
                   8257: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8258: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8259: ADDMETA
1.1210    raeburn  8260:     } else {
                   8261:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8262:             my $requrl = $env{'request.uri'};
                   8263:             if ($requrl eq '') {
                   8264:                 $requrl = $ENV{'REQUEST_URI'};
                   8265:                 $requrl =~ s/\?.+$//;
                   8266:             }
                   8267:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8268:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8269:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8270:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8271:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8272:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   8273:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8274:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   8275:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   8276:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   8277:                             if (($newserver) && ($newserver ne $lonhost)) {
                   8278:                                 my $numsec = 5;
                   8279:                                 my $timeout = $numsec * 1000;
                   8280:                                 my ($newurl,$locknum,%locks,$msg);
                   8281:                                 if ($env{'request.role.adv'}) {
                   8282:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8283:                                 }
                   8284:                                 my $disable_submit = 0;
                   8285:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   8286:                                     $disable_submit = 1;
                   8287:                                 }
                   8288:                                 if ($locknum) {
                   8289:                                     my @lockinfo = sort(values(%locks));
                   8290:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   8291:                                            join(", ",sort(values(%locks)))."\\n".
                   8292:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   8293:                                 } else {
                   8294:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8295:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   8296:                                     }
                   8297:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8298:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8299:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8300:                                         $newurl .= '&role='.$env{'request.role'};
                   8301:                                     }
                   8302:                                     if ($env{'request.symb'}) {
                   8303:                                         $newurl .= '&symb='.$env{'request.symb'};
                   8304:                                     } else {
                   8305:                                         $newurl .= '&origurl='.$requrl;
                   8306:                                     }
                   8307:                                 }
1.1222    damieng  8308:                                 &js_escape(\$msg);
1.1210    raeburn  8309:                                 $result.=<<OFFLOAD
                   8310: <meta http-equiv="pragma" content="no-cache" />
                   8311: <script type="text/javascript">
1.1215    raeburn  8312: // <![CDATA[
1.1210    raeburn  8313: function LC_Offload_Now() {
                   8314:     var dest = "$newurl";
                   8315:     if (dest != '') {
                   8316:         window.location.href="$newurl";
                   8317:     }
                   8318: }
1.1214    raeburn  8319: \$(document).ready(function () {
                   8320:     window.alert('$msg');
                   8321:     if ($disable_submit) {
1.1210    raeburn  8322:         \$(".LC_hwk_submit").prop("disabled", true);
                   8323:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  8324:     }
                   8325:     setTimeout('LC_Offload_Now()', $timeout);
                   8326: });
1.1215    raeburn  8327: // ]]>
1.1210    raeburn  8328: </script>
                   8329: OFFLOAD
                   8330:                             }
                   8331:                         }
                   8332:                     }
                   8333:                 }
                   8334:             }
                   8335:         }
1.313     albertel 8336:     }
1.306     albertel 8337:     if (!defined($title)) {
                   8338: 	$title = 'The LearningOnline Network with CAPA';
                   8339:     }
1.460     albertel 8340:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8341:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  8342: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8343:     if (!$args->{'frameset'}) {
                   8344:         $result .= ' /';
                   8345:     }
                   8346:     $result .= '>' 
1.1064    raeburn  8347:         .$inhibitprint
1.414     albertel 8348: 	.$head_extra;
1.1242    raeburn  8349:     my $clientmobile;
                   8350:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8351:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8352:     } else {
                   8353:         $clientmobile = $env{'browser.mobile'};
                   8354:     }
                   8355:     if ($clientmobile) {
1.1137    raeburn  8356:         $result .= '
                   8357: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8358: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8359:     }
1.1278    raeburn  8360:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8361:     return $result.'</head>';
1.306     albertel 8362: }
                   8363: 
                   8364: =pod
                   8365: 
1.340     albertel 8366: =item * &font_settings()
                   8367: 
                   8368: Returns neccessary <meta> to set the proper encoding
                   8369: 
1.1160    raeburn  8370: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8371: 
                   8372: =cut
                   8373: 
                   8374: sub font_settings {
1.1160    raeburn  8375:     my ($args) = @_;
1.340     albertel 8376:     my $headerstring='';
1.1160    raeburn  8377:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8378:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  8379:         $headerstring.=
                   8380:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8381:         if (!$args->{'frameset'}) {
                   8382: 	    $headerstring.= ' /';
                   8383:         }
                   8384: 	$headerstring .= '>'."\n";
1.340     albertel 8385:     }
                   8386:     return $headerstring;
                   8387: }
                   8388: 
1.341     albertel 8389: =pod
                   8390: 
1.1064    raeburn  8391: =item * &print_suppression()
                   8392: 
                   8393: In course context returns css which causes the body to be blank when media="print",
                   8394: if printout generation is unavailable for the current resource.
                   8395: 
                   8396: This could be because:
                   8397: 
                   8398: (a) printstartdate is in the future
                   8399: 
                   8400: (b) printenddate is in the past
                   8401: 
                   8402: (c) there is an active exam block with "printout"
                   8403: functionality blocked
                   8404: 
                   8405: Users with pav, pfo or evb privileges are exempt.
                   8406: 
                   8407: Inputs: none
                   8408: 
                   8409: =cut
                   8410: 
                   8411: 
                   8412: sub print_suppression {
                   8413:     my $noprint;
                   8414:     if ($env{'request.course.id'}) {
                   8415:         my $scope = $env{'request.course.id'};
                   8416:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8417:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8418:             return;
                   8419:         }
                   8420:         if ($env{'request.course.sec'} ne '') {
                   8421:             $scope .= "/$env{'request.course.sec'}";
                   8422:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8423:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8424:                 return;
1.1064    raeburn  8425:             }
                   8426:         }
                   8427:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8428:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8429:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8430:         if ($blocked) {
                   8431:             my $checkrole = "cm./$cdom/$cnum";
                   8432:             if ($env{'request.course.sec'} ne '') {
                   8433:                 $checkrole .= "/$env{'request.course.sec'}";
                   8434:             }
                   8435:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8436:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8437:                 $noprint = 1;
                   8438:             }
                   8439:         }
                   8440:         unless ($noprint) {
                   8441:             my $symb = &Apache::lonnet::symbread();
                   8442:             if ($symb ne '') {
                   8443:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8444:                 if (ref($navmap)) {
                   8445:                     my $res = $navmap->getBySymb($symb);
                   8446:                     if (ref($res)) {
                   8447:                         if (!$res->resprintable()) {
                   8448:                             $noprint = 1;
                   8449:                         }
                   8450:                     }
                   8451:                 }
                   8452:             }
                   8453:         }
                   8454:         if ($noprint) {
                   8455:             return <<"ENDSTYLE";
                   8456: <style type="text/css" media="print">
                   8457:     body { display:none }
                   8458: </style>
                   8459: ENDSTYLE
                   8460:         }
                   8461:     }
                   8462:     return;
                   8463: }
                   8464: 
                   8465: =pod
                   8466: 
1.341     albertel 8467: =item * &xml_begin()
                   8468: 
                   8469: Returns the needed doctype and <html>
                   8470: 
                   8471: Inputs: none
                   8472: 
                   8473: =cut
                   8474: 
                   8475: sub xml_begin {
1.1168    raeburn  8476:     my ($is_frameset) = @_;
1.341     albertel 8477:     my $output='';
                   8478: 
                   8479:     if ($env{'browser.mathml'}) {
                   8480: 	$output='<?xml version="1.0"?>'
                   8481:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8482: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8483:             
                   8484: #	    .'<!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">] >'
                   8485: 	    .'<!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">'
                   8486:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8487: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8488:     } elsif ($is_frameset) {
                   8489:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8490:                 '<html>'."\n";
1.341     albertel 8491:     } else {
1.1168    raeburn  8492: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8493:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8494:     }
                   8495:     return $output;
                   8496: }
1.340     albertel 8497: 
                   8498: =pod
                   8499: 
1.306     albertel 8500: =item * &start_page()
                   8501: 
                   8502: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8503: 
1.648     raeburn  8504: Inputs:
                   8505: 
                   8506: =over 4
                   8507: 
                   8508: $title - optional title for the page
                   8509: 
                   8510: $head_extra - optional extra HTML to incude inside the <head>
                   8511: 
                   8512: $args - additional optional args supported are:
                   8513: 
                   8514: =over 8
                   8515: 
                   8516:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8517:                                     arg on
1.814     bisitz   8518:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8519:              add_entries    -> additional attributes to add to the  <body>
                   8520:              domain         -> force to color decorate a page for a 
1.317     albertel 8521:                                     specific domain
1.648     raeburn  8522:              function       -> force usage of a specific rolish color
1.317     albertel 8523:                                     scheme
1.648     raeburn  8524:              redirect       -> see &headtag()
                   8525:              bgcolor        -> override the default page bg color
                   8526:              js_ready       -> return a string ready for being used in 
1.317     albertel 8527:                                     a javascript writeln
1.648     raeburn  8528:              html_encode    -> return a string ready for being used in 
1.320     albertel 8529:                                     a html attribute
1.648     raeburn  8530:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8531:                                     $forcereg arg
1.648     raeburn  8532:              frameset       -> if true will start with a <frameset>
1.330     albertel 8533:                                     rather than <body>
1.648     raeburn  8534:              skip_phases    -> hash ref of 
1.338     albertel 8535:                                     head -> skip the <html><head> generation
                   8536:                                     body -> skip all <body> generation
1.648     raeburn  8537:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8538:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8539:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  8540:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8541:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  8542:              group          -> includes the current group, if page is for a 
1.1274    raeburn  8543:                                specific group
                   8544:              use_absolute   -> for request for external resource or syllabus, this
                   8545:                                will contain https://<hostname> if server uses
                   8546:                                https (as per hosts.tab), but request is for http
                   8547:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8548: 
1.648     raeburn  8549: =back
1.460     albertel 8550: 
1.648     raeburn  8551: =back
1.562     albertel 8552: 
1.306     albertel 8553: =cut
                   8554: 
                   8555: sub start_page {
1.309     albertel 8556:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8557:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8558: 
1.315     albertel 8559:     $env{'internal.start_page'}++;
1.1096    raeburn  8560:     my ($result,@advtools);
1.964     droeschl 8561: 
1.338     albertel 8562:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8563:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8564:     }
                   8565:     
                   8566:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8567: 	if ($args->{'frameset'}) {
                   8568: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8569: 						$args->{'add_entries'});
                   8570: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8571:         } else {
                   8572:             $result .=
                   8573:                 &bodytag($title, 
                   8574:                          $args->{'function'},       $args->{'add_entries'},
                   8575:                          $args->{'only_body'},      $args->{'domain'},
                   8576:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8577:                          $args->{'bgcolor'},        $args,
                   8578:                          \@advtools);
1.831     bisitz   8579:         }
1.330     albertel 8580:     }
1.338     albertel 8581: 
1.315     albertel 8582:     if ($args->{'js_ready'}) {
1.713     kaisler  8583: 		$result = &js_ready($result);
1.315     albertel 8584:     }
1.320     albertel 8585:     if ($args->{'html_encode'}) {
1.713     kaisler  8586: 		$result = &html_encode($result);
                   8587:     }
                   8588: 
1.813     bisitz   8589:     # Preparation for new and consistent functionlist at top of screen
                   8590:     # if ($args->{'functionlist'}) {
                   8591:     #            $result .= &build_functionlist();
                   8592:     #}
                   8593: 
1.964     droeschl 8594:     # Don't add anything more if only_body wanted or in const space
                   8595:     return $result if    $args->{'only_body'} 
                   8596:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8597: 
                   8598:     #Breadcrumbs
1.758     kaisler  8599:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8600: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8601: 		#if any br links exists, add them to the breadcrumbs
                   8602: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8603: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8604: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8605: 			}
                   8606: 		}
1.1096    raeburn  8607:                 # if @advtools array contains items add then to the breadcrumbs
                   8608:                 if (@advtools > 0) {
                   8609:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8610:                 }
1.1272    raeburn  8611:                 my $menulink;
                   8612:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8613:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
                   8614:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   8615:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   8616:                      (!$env{'request.role.adv'}))) {
                   8617:                     $menulink = 0;
                   8618:                 } else {
                   8619:                     undef($menulink);
                   8620:                 }
1.758     kaisler  8621: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8622: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  8623: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  8624:                 } else {
1.1272    raeburn  8625: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8626: 		}
1.320     albertel 8627:     }
1.315     albertel 8628:     return $result;
1.306     albertel 8629: }
                   8630: 
                   8631: sub end_page {
1.315     albertel 8632:     my ($args) = @_;
                   8633:     $env{'internal.end_page'}++;
1.330     albertel 8634:     my $result;
1.335     albertel 8635:     if ($args->{'discussion'}) {
                   8636: 	my ($target,$parser);
                   8637: 	if (ref($args->{'discussion'})) {
                   8638: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8639: 				$args->{'discussion'}{'parser'});
                   8640: 	}
                   8641: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8642:     }
1.330     albertel 8643:     if ($args->{'frameset'}) {
                   8644: 	$result .= '</frameset>';
                   8645:     } else {
1.635     raeburn  8646: 	$result .= &endbodytag($args);
1.330     albertel 8647:     }
1.1080    raeburn  8648:     unless ($args->{'notbody'}) {
                   8649:         $result .= "\n</html>";
                   8650:     }
1.330     albertel 8651: 
1.315     albertel 8652:     if ($args->{'js_ready'}) {
1.317     albertel 8653: 	$result = &js_ready($result);
1.315     albertel 8654:     }
1.335     albertel 8655: 
1.320     albertel 8656:     if ($args->{'html_encode'}) {
                   8657: 	$result = &html_encode($result);
                   8658:     }
1.335     albertel 8659: 
1.315     albertel 8660:     return $result;
                   8661: }
                   8662: 
1.1034    www      8663: sub wishlist_window {
                   8664:     return(<<'ENDWISHLIST');
1.1046    raeburn  8665: <script type="text/javascript">
1.1034    www      8666: // <![CDATA[
                   8667: // <!-- BEGIN LON-CAPA Internal
                   8668: function set_wishlistlink(title, path) {
                   8669:     if (!title) {
                   8670:         title = document.title;
                   8671:         title = title.replace(/^LON-CAPA /,'');
                   8672:     }
1.1175    raeburn  8673:     title = encodeURIComponent(title);
1.1203    raeburn  8674:     title = title.replace("'","\\\'");
1.1034    www      8675:     if (!path) {
                   8676:         path = location.pathname;
                   8677:     }
1.1175    raeburn  8678:     path = encodeURIComponent(path);
1.1203    raeburn  8679:     path = path.replace("'","\\\'");
1.1034    www      8680:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8681:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8682: }
                   8683: // END LON-CAPA Internal -->
                   8684: // ]]>
                   8685: </script>
                   8686: ENDWISHLIST
                   8687: }
                   8688: 
1.1030    www      8689: sub modal_window {
                   8690:     return(<<'ENDMODAL');
1.1046    raeburn  8691: <script type="text/javascript">
1.1030    www      8692: // <![CDATA[
                   8693: // <!-- BEGIN LON-CAPA Internal
                   8694: var modalWindow = {
                   8695: 	parent:"body",
                   8696: 	windowId:null,
                   8697: 	content:null,
                   8698: 	width:null,
                   8699: 	height:null,
                   8700: 	close:function()
                   8701: 	{
                   8702: 	        $(".LCmodal-window").remove();
                   8703: 	        $(".LCmodal-overlay").remove();
                   8704: 	},
                   8705: 	open:function()
                   8706: 	{
                   8707: 		var modal = "";
                   8708: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8709: 		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;\">";
                   8710: 		modal += this.content;
                   8711: 		modal += "</div>";	
                   8712: 
                   8713: 		$(this.parent).append(modal);
                   8714: 
                   8715: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8716: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8717: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8718: 	}
                   8719: };
1.1140    raeburn  8720: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8721: 	{
1.1266    raeburn  8722:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8723: 		modalWindow.windowId = "myModal";
                   8724: 		modalWindow.width = width;
                   8725: 		modalWindow.height = height;
1.1196    raeburn  8726: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8727: 		modalWindow.open();
1.1208    raeburn  8728: 	};
1.1030    www      8729: // END LON-CAPA Internal -->
                   8730: // ]]>
                   8731: </script>
                   8732: ENDMODAL
                   8733: }
                   8734: 
                   8735: sub modal_link {
1.1140    raeburn  8736:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8737:     unless ($width) { $width=480; }
                   8738:     unless ($height) { $height=400; }
1.1031    www      8739:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  8740:     unless ($transparency) { $transparency='true'; }
                   8741: 
1.1074    raeburn  8742:     my $target_attr;
                   8743:     if (defined($target)) {
                   8744:         $target_attr = 'target="'.$target.'"';
                   8745:     }
                   8746:     return <<"ENDLINK";
1.1140    raeburn  8747: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8748:            $linktext</a>
                   8749: ENDLINK
1.1030    www      8750: }
                   8751: 
1.1032    www      8752: sub modal_adhoc_script {
                   8753:     my ($funcname,$width,$height,$content)=@_;
                   8754:     return (<<ENDADHOC);
1.1046    raeburn  8755: <script type="text/javascript">
1.1032    www      8756: // <![CDATA[
                   8757:         var $funcname = function()
                   8758:         {
                   8759:                 modalWindow.windowId = "myModal";
                   8760:                 modalWindow.width = $width;
                   8761:                 modalWindow.height = $height;
                   8762:                 modalWindow.content = '$content';
                   8763:                 modalWindow.open();
                   8764:         };  
                   8765: // ]]>
                   8766: </script>
                   8767: ENDADHOC
                   8768: }
                   8769: 
1.1041    www      8770: sub modal_adhoc_inner {
                   8771:     my ($funcname,$width,$height,$content)=@_;
                   8772:     my $innerwidth=$width-20;
                   8773:     $content=&js_ready(
1.1140    raeburn  8774:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   8775:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8776:                  $content.
1.1041    www      8777:                  &end_scrollbox().
1.1140    raeburn  8778:                  &end_page()
1.1041    www      8779:              );
                   8780:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8781: }
                   8782: 
                   8783: sub modal_adhoc_window {
                   8784:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8785:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8786:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8787: }
                   8788: 
                   8789: sub modal_adhoc_launch {
                   8790:     my ($funcname,$width,$height,$content)=@_;
                   8791:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8792: <script type="text/javascript">
                   8793: // <![CDATA[
                   8794: $funcname();
                   8795: // ]]>
                   8796: </script>
                   8797: ENDLAUNCH
                   8798: }
                   8799: 
                   8800: sub modal_adhoc_close {
                   8801:     return (<<ENDCLOSE);
                   8802: <script type="text/javascript">
                   8803: // <![CDATA[
                   8804: modalWindow.close();
                   8805: // ]]>
                   8806: </script>
                   8807: ENDCLOSE
                   8808: }
                   8809: 
1.1038    www      8810: sub togglebox_script {
                   8811:    return(<<ENDTOGGLE);
                   8812: <script type="text/javascript"> 
                   8813: // <![CDATA[
                   8814: function LCtoggleDisplay(id,hidetext,showtext) {
                   8815:    link = document.getElementById(id + "link").childNodes[0];
                   8816:    with (document.getElementById(id).style) {
                   8817:       if (display == "none" ) {
                   8818:           display = "inline";
                   8819:           link.nodeValue = hidetext;
                   8820:         } else {
                   8821:           display = "none";
                   8822:           link.nodeValue = showtext;
                   8823:        }
                   8824:    }
                   8825: }
                   8826: // ]]>
                   8827: </script>
                   8828: ENDTOGGLE
                   8829: }
                   8830: 
1.1039    www      8831: sub start_togglebox {
                   8832:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8833:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8834:     unless ($showtext) { $showtext=&mt('show'); }
                   8835:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8836:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8837:     return &start_data_table().
                   8838:            &start_data_table_header_row().
                   8839:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8840:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8841:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8842:            &end_data_table_header_row().
                   8843:            '<tr id="'.$id.'" style="display:none""><td>';
                   8844: }
                   8845: 
                   8846: sub end_togglebox {
                   8847:     return '</td></tr>'.&end_data_table();
                   8848: }
                   8849: 
1.1041    www      8850: sub LCprogressbar_script {
1.1045    www      8851:    my ($id)=@_;
1.1041    www      8852:    return(<<ENDPROGRESS);
                   8853: <script type="text/javascript">
                   8854: // <![CDATA[
1.1045    www      8855: \$('#progressbar$id').progressbar({
1.1041    www      8856:   value: 0,
                   8857:   change: function(event, ui) {
                   8858:     var newVal = \$(this).progressbar('option', 'value');
                   8859:     \$('.pblabel', this).text(LCprogressTxt);
                   8860:   }
                   8861: });
                   8862: // ]]>
                   8863: </script>
                   8864: ENDPROGRESS
                   8865: }
                   8866: 
                   8867: sub LCprogressbarUpdate_script {
                   8868:    return(<<ENDPROGRESSUPDATE);
                   8869: <style type="text/css">
                   8870: .ui-progressbar { position:relative; }
                   8871: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8872: </style>
                   8873: <script type="text/javascript">
                   8874: // <![CDATA[
1.1045    www      8875: var LCprogressTxt='---';
                   8876: 
                   8877: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8878:    LCprogressTxt=progresstext;
1.1045    www      8879:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8880: }
                   8881: // ]]>
                   8882: </script>
                   8883: ENDPROGRESSUPDATE
                   8884: }
                   8885: 
1.1042    www      8886: my $LClastpercent;
1.1045    www      8887: my $LCidcnt;
                   8888: my $LCcurrentid;
1.1042    www      8889: 
1.1041    www      8890: sub LCprogressbar {
1.1042    www      8891:     my ($r)=(@_);
                   8892:     $LClastpercent=0;
1.1045    www      8893:     $LCidcnt++;
                   8894:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8895:     my $starting=&mt('Starting');
                   8896:     my $content=(<<ENDPROGBAR);
1.1045    www      8897:   <div id="progressbar$LCcurrentid">
1.1041    www      8898:     <span class="pblabel">$starting</span>
                   8899:   </div>
                   8900: ENDPROGBAR
1.1045    www      8901:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8902: }
                   8903: 
                   8904: sub LCprogressbarUpdate {
1.1042    www      8905:     my ($r,$val,$text)=@_;
                   8906:     unless ($val) { 
                   8907:        if ($LClastpercent) {
                   8908:            $val=$LClastpercent;
                   8909:        } else {
                   8910:            $val=0;
                   8911:        }
                   8912:     }
1.1041    www      8913:     if ($val<0) { $val=0; }
                   8914:     if ($val>100) { $val=0; }
1.1042    www      8915:     $LClastpercent=$val;
1.1041    www      8916:     unless ($text) { $text=$val.'%'; }
                   8917:     $text=&js_ready($text);
1.1044    www      8918:     &r_print($r,<<ENDUPDATE);
1.1041    www      8919: <script type="text/javascript">
                   8920: // <![CDATA[
1.1045    www      8921: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8922: // ]]>
                   8923: </script>
                   8924: ENDUPDATE
1.1035    www      8925: }
                   8926: 
1.1042    www      8927: sub LCprogressbarClose {
                   8928:     my ($r)=@_;
                   8929:     $LClastpercent=0;
1.1044    www      8930:     &r_print($r,<<ENDCLOSE);
1.1042    www      8931: <script type="text/javascript">
                   8932: // <![CDATA[
1.1045    www      8933: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8934: // ]]>
                   8935: </script>
                   8936: ENDCLOSE
1.1044    www      8937: }
                   8938: 
                   8939: sub r_print {
                   8940:     my ($r,$to_print)=@_;
                   8941:     if ($r) {
                   8942:       $r->print($to_print);
                   8943:       $r->rflush();
                   8944:     } else {
                   8945:       print($to_print);
                   8946:     }
1.1042    www      8947: }
                   8948: 
1.320     albertel 8949: sub html_encode {
                   8950:     my ($result) = @_;
                   8951: 
1.322     albertel 8952:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8953:     
                   8954:     return $result;
                   8955: }
1.1044    www      8956: 
1.317     albertel 8957: sub js_ready {
                   8958:     my ($result) = @_;
                   8959: 
1.323     albertel 8960:     $result =~ s/[\n\r]/ /xmsg;
                   8961:     $result =~ s/\\/\\\\/xmsg;
                   8962:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8963:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8964:     
                   8965:     return $result;
                   8966: }
                   8967: 
1.315     albertel 8968: sub validate_page {
                   8969:     if (  exists($env{'internal.start_page'})
1.316     albertel 8970: 	  &&     $env{'internal.start_page'} > 1) {
                   8971: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8972: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8973: 				 $ENV{'request.filename'});
1.315     albertel 8974:     }
                   8975:     if (  exists($env{'internal.end_page'})
1.316     albertel 8976: 	  &&     $env{'internal.end_page'} > 1) {
                   8977: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8978: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8979: 				 $env{'request.filename'});
1.315     albertel 8980:     }
                   8981:     if (     exists($env{'internal.start_page'})
                   8982: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8983: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8984: 				 $env{'request.filename'});
1.315     albertel 8985:     }
                   8986:     if (   ! exists($env{'internal.start_page'})
                   8987: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8988: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8989: 				 $env{'request.filename'});
1.315     albertel 8990:     }
1.306     albertel 8991: }
1.315     albertel 8992: 
1.996     www      8993: 
                   8994: sub start_scrollbox {
1.1140    raeburn  8995:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8996:     unless ($outerwidth) { $outerwidth='520px'; }
                   8997:     unless ($width) { $width='500px'; }
                   8998:     unless ($height) { $height='200px'; }
1.1075    raeburn  8999:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9000:     if ($id ne '') {
1.1140    raeburn  9001:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  9002:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9003:     }
1.1075    raeburn  9004:     if ($bgcolor ne '') {
                   9005:         $tdcol = "background-color: $bgcolor;";
                   9006:     }
1.1137    raeburn  9007:     my $nicescroll_js;
                   9008:     if ($env{'browser.mobile'}) {
1.1140    raeburn  9009:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9010:     }
                   9011:     return <<"END";
                   9012: $nicescroll_js
                   9013: 
                   9014: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   9015: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   9016: END
                   9017: }
                   9018: 
                   9019: sub end_scrollbox {
                   9020:     return '</div></td></tr></table>';
                   9021: }
                   9022: 
                   9023: sub nicescroll_javascript {
                   9024:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9025:     my %options;
                   9026:     if (ref($cursor) eq 'HASH') {
                   9027:         %options = %{$cursor};
                   9028:     }
                   9029:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9030:         $options{'railalign'} = 'left';
                   9031:     }
                   9032:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9033:         my $function  = &get_users_function();
                   9034:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9035:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9036:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9037:         }
1.1140    raeburn  9038:     }
                   9039:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9040:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9041:             $options{'cursoropacity'}='1.0';
                   9042:         }
1.1140    raeburn  9043:     } else {
                   9044:         $options{'cursoropacity'}='1.0';
                   9045:     }
                   9046:     if ($options{'cursorfixedheight'} eq 'none') {
                   9047:         delete($options{'cursorfixedheight'});
                   9048:     } else {
                   9049:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9050:     }
                   9051:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9052:         delete($options{'railoffset'});
                   9053:     }
                   9054:     my @niceoptions;
                   9055:     while (my($key,$value) = each(%options)) {
                   9056:         if ($value =~ /^\{.+\}$/) {
                   9057:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9058:         } else {
1.1140    raeburn  9059:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9060:         }
1.1140    raeburn  9061:     }
                   9062:     my $nicescroll_js = '
1.1137    raeburn  9063: $(document).ready(
1.1140    raeburn  9064:       function() {
                   9065:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9066:       }
1.1137    raeburn  9067: );
                   9068: ';
1.1140    raeburn  9069:     if ($framecheck) {
                   9070:         $nicescroll_js .= '
                   9071: function expand_div(caller) {
                   9072:     if (top === self) {
                   9073:         document.getElementById("'.$id.'").style.width = "auto";
                   9074:         document.getElementById("'.$id.'").style.height = "auto";
                   9075:     } else {
                   9076:         try {
                   9077:             if (parent.frames) {
                   9078:                 if (parent.frames.length > 1) {
                   9079:                     var framesrc = parent.frames[1].location.href;
                   9080:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9081:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9082:                         document.getElementById("'.$id.'").style.width = "auto";
                   9083:                         document.getElementById("'.$id.'").style.height = "auto";
                   9084:                     }
                   9085:                 }
                   9086:             }
                   9087:         } catch (e) {
                   9088:             return;
                   9089:         }
1.1137    raeburn  9090:     }
1.1140    raeburn  9091:     return;
1.996     www      9092: }
1.1140    raeburn  9093: ';
                   9094:     }
                   9095:     if ($needjsready) {
                   9096:         $nicescroll_js = '
                   9097: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9098:     } else {
                   9099:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9100:     }
                   9101:     return $nicescroll_js;
1.996     www      9102: }
                   9103: 
1.318     albertel 9104: sub simple_error_page {
1.1150    bisitz   9105:     my ($r,$title,$msg,$args) = @_;
1.1151    raeburn  9106:     if (ref($args) eq 'HASH') {
                   9107:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   9108:     } else {
                   9109:         $msg = &mt($msg);
                   9110:     }
1.1150    bisitz   9111: 
1.318     albertel 9112:     my $page =
                   9113: 	&Apache::loncommon::start_page($title).
1.1150    bisitz   9114: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9115: 	&Apache::loncommon::end_page();
                   9116:     if (ref($r)) {
                   9117: 	$r->print($page);
1.327     albertel 9118: 	return;
1.318     albertel 9119:     }
                   9120:     return $page;
                   9121: }
1.347     albertel 9122: 
                   9123: {
1.610     albertel 9124:     my @row_count;
1.961     onken    9125: 
                   9126:     sub start_data_table_count {
                   9127:         unshift(@row_count, 0);
                   9128:         return;
                   9129:     }
                   9130: 
                   9131:     sub end_data_table_count {
                   9132:         shift(@row_count);
                   9133:         return;
                   9134:     }
                   9135: 
1.347     albertel 9136:     sub start_data_table {
1.1018    raeburn  9137: 	my ($add_class,$id) = @_;
1.422     albertel 9138: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9139:         my $table_id;
                   9140:         if (defined($id)) {
                   9141:             $table_id = ' id="'.$id.'"';
                   9142:         }
1.961     onken    9143: 	&start_data_table_count();
1.1018    raeburn  9144: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9145:     }
                   9146: 
                   9147:     sub end_data_table {
1.961     onken    9148: 	&end_data_table_count();
1.389     albertel 9149: 	return '</table>'."\n";;
1.347     albertel 9150:     }
                   9151: 
                   9152:     sub start_data_table_row {
1.974     wenzelju 9153: 	my ($add_class, $id) = @_;
1.610     albertel 9154: 	$row_count[0]++;
                   9155: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9156: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9157:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9158:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9159:     }
1.471     banghart 9160:     
                   9161:     sub continue_data_table_row {
1.974     wenzelju 9162: 	my ($add_class, $id) = @_;
1.610     albertel 9163: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9164: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9165:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9166:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9167:     }
1.347     albertel 9168: 
                   9169:     sub end_data_table_row {
1.389     albertel 9170: 	return '</tr>'."\n";;
1.347     albertel 9171:     }
1.367     www      9172: 
1.421     albertel 9173:     sub start_data_table_empty_row {
1.707     bisitz   9174: #	$row_count[0]++;
1.421     albertel 9175: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9176:     }
                   9177: 
                   9178:     sub end_data_table_empty_row {
                   9179: 	return '</tr>'."\n";;
                   9180:     }
                   9181: 
1.367     www      9182:     sub start_data_table_header_row {
1.389     albertel 9183: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9184:     }
                   9185: 
                   9186:     sub end_data_table_header_row {
1.389     albertel 9187: 	return '</tr>'."\n";;
1.367     www      9188:     }
1.890     droeschl 9189: 
                   9190:     sub data_table_caption {
                   9191:         my $caption = shift;
                   9192:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9193:     }
1.347     albertel 9194: }
                   9195: 
1.548     albertel 9196: =pod
                   9197: 
                   9198: =item * &inhibit_menu_check($arg)
                   9199: 
                   9200: Checks for a inhibitmenu state and generates output to preserve it
                   9201: 
                   9202: Inputs:         $arg - can be any of
                   9203:                      - undef - in which case the return value is a string 
                   9204:                                to add  into arguments list of a uri
                   9205:                      - 'input' - in which case the return value is a HTML
                   9206:                                  <form> <input> field of type hidden to
                   9207:                                  preserve the value
                   9208:                      - a url - in which case the return value is the url with
                   9209:                                the neccesary cgi args added to preserve the
                   9210:                                inhibitmenu state
                   9211:                      - a ref to a url - no return value, but the string is
                   9212:                                         updated to include the neccessary cgi
                   9213:                                         args to preserve the inhibitmenu state
                   9214: 
                   9215: =cut
                   9216: 
                   9217: sub inhibit_menu_check {
                   9218:     my ($arg) = @_;
                   9219:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9220:     if ($arg eq 'input') {
                   9221: 	if ($env{'form.inhibitmenu'}) {
                   9222: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9223: 	} else {
                   9224: 	    return
                   9225: 	}
                   9226:     }
                   9227:     if ($env{'form.inhibitmenu'}) {
                   9228: 	if (ref($arg)) {
                   9229: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9230: 	} elsif ($arg eq '') {
                   9231: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9232: 	} else {
                   9233: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9234: 	}
                   9235:     }
                   9236:     if (!ref($arg)) {
                   9237: 	return $arg;
                   9238:     }
                   9239: }
                   9240: 
1.251     albertel 9241: ###############################################
1.182     matthew  9242: 
                   9243: =pod
                   9244: 
1.549     albertel 9245: =back
                   9246: 
                   9247: =head1 User Information Routines
                   9248: 
                   9249: =over 4
                   9250: 
1.405     albertel 9251: =item * &get_users_function()
1.182     matthew  9252: 
                   9253: Used by &bodytag to determine the current users primary role.
                   9254: Returns either 'student','coordinator','admin', or 'author'.
                   9255: 
                   9256: =cut
                   9257: 
                   9258: ###############################################
                   9259: sub get_users_function {
1.815     tempelho 9260:     my $function = 'norole';
1.818     tempelho 9261:     if ($env{'request.role'}=~/^(st)/) {
                   9262:         $function='student';
                   9263:     }
1.907     raeburn  9264:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9265:         $function='coordinator';
                   9266:     }
1.258     albertel 9267:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9268:         $function='admin';
                   9269:     }
1.826     bisitz   9270:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9271:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9272:         $function='author';
                   9273:     }
                   9274:     return $function;
1.54      www      9275: }
1.99      www      9276: 
                   9277: ###############################################
                   9278: 
1.233     raeburn  9279: =pod
                   9280: 
1.821     raeburn  9281: =item * &show_course()
                   9282: 
                   9283: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9284: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9285: 
                   9286: Inputs:
                   9287: None
                   9288: 
                   9289: Outputs:
                   9290: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9291: 
                   9292: =cut
                   9293: 
                   9294: ###############################################
                   9295: sub show_course {
                   9296:     my $course = !$env{'user.adv'};
                   9297:     if (!$env{'user.adv'}) {
                   9298:         foreach my $env (keys(%env)) {
                   9299:             next if ($env !~ m/^user\.priv\./);
                   9300:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9301:                 $course = 0;
                   9302:                 last;
                   9303:             }
                   9304:         }
                   9305:     }
                   9306:     return $course;
                   9307: }
                   9308: 
                   9309: ###############################################
                   9310: 
                   9311: =pod
                   9312: 
1.542     raeburn  9313: =item * &check_user_status()
1.274     raeburn  9314: 
                   9315: Determines current status of supplied role for a
                   9316: specific user. Roles can be active, previous or future.
                   9317: 
                   9318: Inputs: 
                   9319: user's domain, user's username, course's domain,
1.375     raeburn  9320: course's number, optional section ID.
1.274     raeburn  9321: 
                   9322: Outputs:
                   9323: role status: active, previous or future. 
                   9324: 
                   9325: =cut
                   9326: 
                   9327: sub check_user_status {
1.412     raeburn  9328:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9329:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  9330:     my @uroles = keys(%userinfo);
1.274     raeburn  9331:     my $srchstr;
                   9332:     my $active_chk = 'none';
1.412     raeburn  9333:     my $now = time;
1.274     raeburn  9334:     if (@uroles > 0) {
1.908     raeburn  9335:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9336:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9337:         } else {
1.412     raeburn  9338:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9339:         }
                   9340:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9341:             my $role_end = 0;
                   9342:             my $role_start = 0;
                   9343:             $active_chk = 'active';
1.412     raeburn  9344:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9345:                 $role_end = $1;
                   9346:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9347:                     $role_start = $1;
1.274     raeburn  9348:                 }
                   9349:             }
                   9350:             if ($role_start > 0) {
1.412     raeburn  9351:                 if ($now < $role_start) {
1.274     raeburn  9352:                     $active_chk = 'future';
                   9353:                 }
                   9354:             }
                   9355:             if ($role_end > 0) {
1.412     raeburn  9356:                 if ($now > $role_end) {
1.274     raeburn  9357:                     $active_chk = 'previous';
                   9358:                 }
                   9359:             }
                   9360:         }
                   9361:     }
                   9362:     return $active_chk;
                   9363: }
                   9364: 
                   9365: ###############################################
                   9366: 
                   9367: =pod
                   9368: 
1.405     albertel 9369: =item * &get_sections()
1.233     raeburn  9370: 
                   9371: Determines all the sections for a course including
                   9372: sections with students and sections containing other roles.
1.419     raeburn  9373: Incoming parameters: 
                   9374: 
                   9375: 1. domain
                   9376: 2. course number 
                   9377: 3. reference to array containing roles for which sections should 
                   9378: be gathered (optional).
                   9379: 4. reference to array containing status types for which sections 
                   9380: should be gathered (optional).
                   9381: 
                   9382: If the third argument is undefined, sections are gathered for any role. 
                   9383: If the fourth argument is undefined, sections are gathered for any status.
                   9384: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9385:  
1.374     raeburn  9386: Returns section hash (keys are section IDs, values are
                   9387: number of users in each section), subject to the
1.419     raeburn  9388: optional roles filter, optional status filter 
1.233     raeburn  9389: 
                   9390: =cut
                   9391: 
                   9392: ###############################################
                   9393: sub get_sections {
1.419     raeburn  9394:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9395:     if (!defined($cdom) || !defined($cnum)) {
                   9396:         my $cid =  $env{'request.course.id'};
                   9397: 
                   9398: 	return if (!defined($cid));
                   9399: 
                   9400:         $cdom = $env{'course.'.$cid.'.domain'};
                   9401:         $cnum = $env{'course.'.$cid.'.num'};
                   9402:     }
                   9403: 
                   9404:     my %sectioncount;
1.419     raeburn  9405:     my $now = time;
1.240     albertel 9406: 
1.1118    raeburn  9407:     my $check_students = 1;
                   9408:     my $only_students = 0;
                   9409:     if (ref($possible_roles) eq 'ARRAY') {
                   9410:         if (grep(/^st$/,@{$possible_roles})) {
                   9411:             if (@{$possible_roles} == 1) {
                   9412:                 $only_students = 1;
                   9413:             }
                   9414:         } else {
                   9415:             $check_students = 0;
                   9416:         }
                   9417:     }
                   9418: 
                   9419:     if ($check_students) { 
1.276     albertel 9420: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9421: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9422: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9423:         my $start_index = &Apache::loncoursedata::CL_START();
                   9424:         my $end_index = &Apache::loncoursedata::CL_END();
                   9425:         my $status;
1.366     albertel 9426: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9427: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9428: 				                     $data->[$status_index],
                   9429:                                                      $data->[$start_index],
                   9430:                                                      $data->[$end_index]);
                   9431:             if ($stu_status eq 'Active') {
                   9432:                 $status = 'active';
                   9433:             } elsif ($end < $now) {
                   9434:                 $status = 'previous';
                   9435:             } elsif ($start > $now) {
                   9436:                 $status = 'future';
                   9437:             } 
                   9438: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9439:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9440:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9441: 		    $sectioncount{$section}++;
                   9442:                 }
1.240     albertel 9443: 	    }
                   9444: 	}
                   9445:     }
1.1118    raeburn  9446:     if ($only_students) {
                   9447:         return %sectioncount;
                   9448:     }
1.240     albertel 9449:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9450:     foreach my $user (sort(keys(%courseroles))) {
                   9451: 	if ($user !~ /^(\w{2})/) { next; }
                   9452: 	my ($role) = ($user =~ /^(\w{2})/);
                   9453: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9454: 	my ($section,$status);
1.240     albertel 9455: 	if ($role eq 'cr' &&
                   9456: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9457: 	    $section=$1;
                   9458: 	}
                   9459: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9460: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9461:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9462:         if ($end == -1 && $start == -1) {
                   9463:             next; #deleted role
                   9464:         }
                   9465:         if (!defined($possible_status)) { 
                   9466:             $sectioncount{$section}++;
                   9467:         } else {
                   9468:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9469:                 $status = 'active';
                   9470:             } elsif ($end < $now) {
                   9471:                 $status = 'future';
                   9472:             } elsif ($start > $now) {
                   9473:                 $status = 'previous';
                   9474:             }
                   9475:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9476:                 $sectioncount{$section}++;
                   9477:             }
                   9478:         }
1.233     raeburn  9479:     }
1.366     albertel 9480:     return %sectioncount;
1.233     raeburn  9481: }
                   9482: 
1.274     raeburn  9483: ###############################################
1.294     raeburn  9484: 
                   9485: =pod
1.405     albertel 9486: 
                   9487: =item * &get_course_users()
                   9488: 
1.275     raeburn  9489: Retrieves usernames:domains for users in the specified course
                   9490: with specific role(s), and access status. 
                   9491: 
                   9492: Incoming parameters:
1.277     albertel 9493: 1. course domain
                   9494: 2. course number
                   9495: 3. access status: users must have - either active, 
1.275     raeburn  9496: previous, future, or all.
1.277     albertel 9497: 4. reference to array of permissible roles
1.288     raeburn  9498: 5. reference to array of section restrictions (optional)
                   9499: 6. reference to results object (hash of hashes).
                   9500: 7. reference to optional userdata hash
1.609     raeburn  9501: 8. reference to optional statushash
1.630     raeburn  9502: 9. flag if privileged users (except those set to unhide in
                   9503:    course settings) should be excluded    
1.609     raeburn  9504: Keys of top level results hash are roles.
1.275     raeburn  9505: Keys of inner hashes are username:domain, with 
                   9506: values set to access type.
1.288     raeburn  9507: Optional userdata hash returns an array with arguments in the 
                   9508: same order as loncoursedata::get_classlist() for student data.
                   9509: 
1.609     raeburn  9510: Optional statushash returns
                   9511: 
1.288     raeburn  9512: Entries for end, start, section and status are blank because
                   9513: of the possibility of multiple values for non-student roles.
                   9514: 
1.275     raeburn  9515: =cut
1.405     albertel 9516: 
1.275     raeburn  9517: ###############################################
1.405     albertel 9518: 
1.275     raeburn  9519: sub get_course_users {
1.630     raeburn  9520:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9521:     my %idx = ();
1.419     raeburn  9522:     my %seclists;
1.288     raeburn  9523: 
                   9524:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9525:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9526:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9527:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9528:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9529:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9530:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9531:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9532: 
1.290     albertel 9533:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9534:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9535:         my $now = time;
1.277     albertel 9536:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9537:             my $match = 0;
1.412     raeburn  9538:             my $secmatch = 0;
1.419     raeburn  9539:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9540:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9541:             if ($section eq '') {
                   9542:                 $section = 'none';
                   9543:             }
1.291     albertel 9544:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9545:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9546:                     $secmatch = 1;
                   9547:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9548:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9549:                         $secmatch = 1;
                   9550:                     }
                   9551:                 } else {  
1.419     raeburn  9552: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9553: 		        $secmatch = 1;
                   9554:                     }
1.290     albertel 9555: 		}
1.412     raeburn  9556:                 if (!$secmatch) {
                   9557:                     next;
                   9558:                 }
1.419     raeburn  9559:             }
1.275     raeburn  9560:             if (defined($$types{'active'})) {
1.288     raeburn  9561:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9562:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9563:                     $match = 1;
1.275     raeburn  9564:                 }
                   9565:             }
                   9566:             if (defined($$types{'previous'})) {
1.609     raeburn  9567:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9568:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9569:                     $match = 1;
1.275     raeburn  9570:                 }
                   9571:             }
                   9572:             if (defined($$types{'future'})) {
1.609     raeburn  9573:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9574:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9575:                     $match = 1;
1.275     raeburn  9576:                 }
                   9577:             }
1.609     raeburn  9578:             if ($match) {
                   9579:                 push(@{$seclists{$student}},$section);
                   9580:                 if (ref($userdata) eq 'HASH') {
                   9581:                     $$userdata{$student} = $$classlist{$student};
                   9582:                 }
                   9583:                 if (ref($statushash) eq 'HASH') {
                   9584:                     $statushash->{$student}{'st'}{$section} = $status;
                   9585:                 }
1.288     raeburn  9586:             }
1.275     raeburn  9587:         }
                   9588:     }
1.412     raeburn  9589:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9590:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9591:         my $now = time;
1.609     raeburn  9592:         my %displaystatus = ( previous => 'Expired',
                   9593:                               active   => 'Active',
                   9594:                               future   => 'Future',
                   9595:                             );
1.1121    raeburn  9596:         my (%nothide,@possdoms);
1.630     raeburn  9597:         if ($hidepriv) {
                   9598:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9599:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9600:                 if ($user !~ /:/) {
                   9601:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9602:                 } else {
                   9603:                     $nothide{$user} = 1;
                   9604:                 }
                   9605:             }
1.1121    raeburn  9606:             my @possdoms = ($cdom);
                   9607:             if ($coursehash{'checkforpriv'}) {
                   9608:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9609:             }
1.630     raeburn  9610:         }
1.439     raeburn  9611:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9612:             my $match = 0;
1.412     raeburn  9613:             my $secmatch = 0;
1.439     raeburn  9614:             my $status;
1.412     raeburn  9615:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9616:             $user =~ s/:$//;
1.439     raeburn  9617:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9618:             if ($end == -1 || $start == -1) {
                   9619:                 next;
                   9620:             }
                   9621:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9622:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9623:                 my ($uname,$udom) = split(/:/,$user);
                   9624:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9625:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9626:                         $secmatch = 1;
                   9627:                     } elsif ($usec eq '') {
1.420     albertel 9628:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9629:                             $secmatch = 1;
                   9630:                         }
                   9631:                     } else {
                   9632:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9633:                             $secmatch = 1;
                   9634:                         }
                   9635:                     }
                   9636:                     if (!$secmatch) {
                   9637:                         next;
                   9638:                     }
1.288     raeburn  9639:                 }
1.419     raeburn  9640:                 if ($usec eq '') {
                   9641:                     $usec = 'none';
                   9642:                 }
1.275     raeburn  9643:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9644:                     if ($hidepriv) {
1.1121    raeburn  9645:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9646:                             (!$nothide{$uname.':'.$udom})) {
                   9647:                             next;
                   9648:                         }
                   9649:                     }
1.503     raeburn  9650:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9651:                         $status = 'previous';
                   9652:                     } elsif ($start > $now) {
                   9653:                         $status = 'future';
                   9654:                     } else {
                   9655:                         $status = 'active';
                   9656:                     }
1.277     albertel 9657:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9658:                         if ($status eq $type) {
1.420     albertel 9659:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9660:                                 push(@{$$users{$role}{$user}},$type);
                   9661:                             }
1.288     raeburn  9662:                             $match = 1;
                   9663:                         }
                   9664:                     }
1.419     raeburn  9665:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9666:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9667: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9668:                         }
1.420     albertel 9669:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9670:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9671:                         }
1.609     raeburn  9672:                         if (ref($statushash) eq 'HASH') {
                   9673:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9674:                         }
1.275     raeburn  9675:                     }
                   9676:                 }
                   9677:             }
                   9678:         }
1.290     albertel 9679:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9680:             if ((defined($cdom)) && (defined($cnum))) {
                   9681:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9682:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9683:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9684:                     next if ($owner eq '');
                   9685:                     my ($ownername,$ownerdom);
                   9686:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9687:                         $ownername = $1;
                   9688:                         $ownerdom = $2;
                   9689:                     } else {
                   9690:                         $ownername = $owner;
                   9691:                         $ownerdom = $cdom;
                   9692:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9693:                     }
                   9694:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9695:                     if (defined($userdata) && 
1.609     raeburn  9696: 			!exists($$userdata{$owner})) {
                   9697: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9698:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9699:                             push(@{$seclists{$owner}},'none');
                   9700:                         }
                   9701:                         if (ref($statushash) eq 'HASH') {
                   9702:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9703:                         }
1.290     albertel 9704: 		    }
1.279     raeburn  9705:                 }
                   9706:             }
                   9707:         }
1.419     raeburn  9708:         foreach my $user (keys(%seclists)) {
                   9709:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9710:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9711:         }
1.275     raeburn  9712:     }
                   9713:     return;
                   9714: }
                   9715: 
1.288     raeburn  9716: sub get_user_info {
                   9717:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9718:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9719: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9720:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9721:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9722:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9723:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9724:     return;
                   9725: }
1.275     raeburn  9726: 
1.472     raeburn  9727: ###############################################
                   9728: 
                   9729: =pod
                   9730: 
                   9731: =item * &get_user_quota()
                   9732: 
1.1134    raeburn  9733: Retrieves quota assigned for storage of user files.
                   9734: Default is to report quota for portfolio files.
1.472     raeburn  9735: 
                   9736: Incoming parameters:
                   9737: 1. user's username
                   9738: 2. user's domain
1.1134    raeburn  9739: 3. quota name - portfolio, author, or course
1.1136    raeburn  9740:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  9741: 4. crstype - official, unofficial, textbook, placement or community, 
                   9742:    if quota name is course
1.472     raeburn  9743: 
                   9744: Returns:
1.1163    raeburn  9745: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9746: 2. (Optional) Type of setting: custom or default
                   9747:    (individually assigned or default for user's 
                   9748:    institutional status).
                   9749: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9750:    or student - types as defined in localenroll::inst_usertypes 
                   9751:    for user's domain, which determines default quota for user.
                   9752: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9753: 
                   9754: If a value has been stored in the user's environment, 
1.536     raeburn  9755: it will return that, otherwise it returns the maximal default
1.1134    raeburn  9756: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9757: 
                   9758: =cut
                   9759: 
                   9760: ###############################################
                   9761: 
                   9762: 
                   9763: sub get_user_quota {
1.1136    raeburn  9764:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9765:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9766:     if (!defined($udom)) {
                   9767:         $udom = $env{'user.domain'};
                   9768:     }
                   9769:     if (!defined($uname)) {
                   9770:         $uname = $env{'user.name'};
                   9771:     }
                   9772:     if (($udom eq '' || $uname eq '') ||
                   9773:         ($udom eq 'public') && ($uname eq 'public')) {
                   9774:         $quota = 0;
1.536     raeburn  9775:         $quotatype = 'default';
                   9776:         $defquota = 0; 
1.472     raeburn  9777:     } else {
1.536     raeburn  9778:         my $inststatus;
1.1134    raeburn  9779:         if ($quotaname eq 'course') {
                   9780:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9781:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9782:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9783:             } else {
                   9784:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9785:                 $quota = $cenv{'internal.uploadquota'};
                   9786:             }
1.536     raeburn  9787:         } else {
1.1134    raeburn  9788:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9789:                 if ($quotaname eq 'author') {
                   9790:                     $quota = $env{'environment.authorquota'};
                   9791:                 } else {
                   9792:                     $quota = $env{'environment.portfolioquota'};
                   9793:                 }
                   9794:                 $inststatus = $env{'environment.inststatus'};
                   9795:             } else {
                   9796:                 my %userenv = 
                   9797:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9798:                                          'authorquota','inststatus'],$udom,$uname);
                   9799:                 my ($tmp) = keys(%userenv);
                   9800:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9801:                     if ($quotaname eq 'author') {
                   9802:                         $quota = $userenv{'authorquota'};
                   9803:                     } else {
                   9804:                         $quota = $userenv{'portfolioquota'};
                   9805:                     }
                   9806:                     $inststatus = $userenv{'inststatus'};
                   9807:                 } else {
                   9808:                     undef(%userenv);
                   9809:                 }
                   9810:             }
                   9811:         }
                   9812:         if ($quota eq '' || wantarray) {
                   9813:             if ($quotaname eq 'course') {
                   9814:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  9815:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  9816:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   9817:                     ($crstype eq 'placement')) { 
1.1136    raeburn  9818:                     $defquota = $domdefs{$crstype.'quota'};
                   9819:                 }
                   9820:                 if ($defquota eq '') {
                   9821:                     $defquota = 500;
                   9822:                 }
1.1134    raeburn  9823:             } else {
                   9824:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9825:             }
                   9826:             if ($quota eq '') {
                   9827:                 $quota = $defquota;
                   9828:                 $quotatype = 'default';
                   9829:             } else {
                   9830:                 $quotatype = 'custom';
                   9831:             }
1.472     raeburn  9832:         }
                   9833:     }
1.536     raeburn  9834:     if (wantarray) {
                   9835:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9836:     } else {
                   9837:         return $quota;
                   9838:     }
1.472     raeburn  9839: }
                   9840: 
                   9841: ###############################################
                   9842: 
                   9843: =pod
                   9844: 
                   9845: =item * &default_quota()
                   9846: 
1.536     raeburn  9847: Retrieves default quota assigned for storage of user portfolio files,
                   9848: given an (optional) user's institutional status.
1.472     raeburn  9849: 
                   9850: Incoming parameters:
1.1142    raeburn  9851: 
1.472     raeburn  9852: 1. domain
1.536     raeburn  9853: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9854:    status types (e.g., faculty, staff, student etc.)
                   9855:    which apply to the user for whom the default is being retrieved.
                   9856:    If the institutional status string in undefined, the domain
1.1134    raeburn  9857:    default quota will be returned.
                   9858: 3.  quota name - portfolio, author, or course
                   9859:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9860: 
                   9861: Returns:
1.1142    raeburn  9862: 
1.1163    raeburn  9863: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9864: 2. (Optional) institutional type which determined the value of the
                   9865:    default quota.
1.472     raeburn  9866: 
                   9867: If a value has been stored in the domain's configuration db,
                   9868: it will return that, otherwise it returns 20 (for backwards 
                   9869: compatibility with domains which have not set up a configuration
1.1163    raeburn  9870: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9871: 
1.536     raeburn  9872: If the user's status includes multiple types (e.g., staff and student),
                   9873: the largest default quota which applies to the user determines the
                   9874: default quota returned.
                   9875: 
1.472     raeburn  9876: =cut
                   9877: 
                   9878: ###############################################
                   9879: 
                   9880: 
                   9881: sub default_quota {
1.1134    raeburn  9882:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9883:     my ($defquota,$settingstatus);
                   9884:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9885:                                             ['quotas'],$udom);
1.1134    raeburn  9886:     my $key = 'defaultquota';
                   9887:     if ($quotaname eq 'author') {
                   9888:         $key = 'authorquota';
                   9889:     }
1.622     raeburn  9890:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9891:         if ($inststatus ne '') {
1.765     raeburn  9892:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9893:             foreach my $item (@statuses) {
1.1134    raeburn  9894:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9895:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9896:                         if ($defquota eq '') {
1.1134    raeburn  9897:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9898:                             $settingstatus = $item;
1.1134    raeburn  9899:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9900:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9901:                             $settingstatus = $item;
                   9902:                         }
                   9903:                     }
1.1134    raeburn  9904:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9905:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9906:                         if ($defquota eq '') {
                   9907:                             $defquota = $quotahash{'quotas'}{$item};
                   9908:                             $settingstatus = $item;
                   9909:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9910:                             $defquota = $quotahash{'quotas'}{$item};
                   9911:                             $settingstatus = $item;
                   9912:                         }
1.536     raeburn  9913:                     }
                   9914:                 }
                   9915:             }
                   9916:         }
                   9917:         if ($defquota eq '') {
1.1134    raeburn  9918:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9919:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9920:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9921:                 $defquota = $quotahash{'quotas'}{'default'};
                   9922:             }
1.536     raeburn  9923:             $settingstatus = 'default';
1.1139    raeburn  9924:             if ($defquota eq '') {
                   9925:                 if ($quotaname eq 'author') {
                   9926:                     $defquota = 500;
                   9927:                 }
                   9928:             }
1.536     raeburn  9929:         }
                   9930:     } else {
                   9931:         $settingstatus = 'default';
1.1134    raeburn  9932:         if ($quotaname eq 'author') {
                   9933:             $defquota = 500;
                   9934:         } else {
                   9935:             $defquota = 20;
                   9936:         }
1.536     raeburn  9937:     }
                   9938:     if (wantarray) {
                   9939:         return ($defquota,$settingstatus);
1.472     raeburn  9940:     } else {
1.536     raeburn  9941:         return $defquota;
1.472     raeburn  9942:     }
                   9943: }
                   9944: 
1.1135    raeburn  9945: ###############################################
                   9946: 
                   9947: =pod
                   9948: 
1.1136    raeburn  9949: =item * &excess_filesize_warning()
1.1135    raeburn  9950: 
                   9951: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  9952: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  9953: space to be exceeded.
1.1136    raeburn  9954: 
                   9955: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  9956: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  9957: 
1.1165    raeburn  9958: Inputs: 7 
1.1136    raeburn  9959: 1. username or coursenum
1.1135    raeburn  9960: 2. domain
1.1136    raeburn  9961: 3. context ('author' or 'course')
1.1135    raeburn  9962: 4. filename of file for which action is being requested
                   9963: 5. filesize (kB) of file
                   9964: 6. action being taken: copy or upload.
1.1237    raeburn  9965: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  9966: 
                   9967: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  9968:          otherwise return null.
                   9969: 
                   9970: =back
1.1135    raeburn  9971: 
                   9972: =cut
                   9973: 
1.1136    raeburn  9974: sub excess_filesize_warning {
1.1165    raeburn  9975:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  9976:     my $current_disk_usage = 0;
1.1165    raeburn  9977:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  9978:     if ($context eq 'author') {
                   9979:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9980:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9981:     } else {
                   9982:         foreach my $subdir ('docs','supplemental') {
                   9983:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9984:         }
                   9985:     }
1.1135    raeburn  9986:     $disk_quota = int($disk_quota * 1000);
                   9987:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   9988:         return '<p class="LC_warning">'.
1.1135    raeburn  9989:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   9990:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9991:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  9992:                             $disk_quota,$current_disk_usage).
                   9993:                '</p>';
                   9994:     }
                   9995:     return;
                   9996: }
                   9997: 
                   9998: ###############################################
                   9999: 
                   10000: 
1.1136    raeburn  10001: 
                   10002: 
1.384     raeburn  10003: sub get_secgrprole_info {
                   10004:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10005:     my %sections_count = &get_sections($cdom,$cnum);
                   10006:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10007:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10008:     my @groups = sort(keys(%curr_groups));
                   10009:     my $allroles = [];
                   10010:     my $rolehash;
                   10011:     my $accesshash = {
                   10012:                      active => 'Currently has access',
                   10013:                      future => 'Will have future access',
                   10014:                      previous => 'Previously had access',
                   10015:                   };
                   10016:     if ($needroles) {
                   10017:         $rolehash = {'all' => 'all'};
1.385     albertel 10018:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10019: 	if (&Apache::lonnet::error(%user_roles)) {
                   10020: 	    undef(%user_roles);
                   10021: 	}
                   10022:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10023:             my ($role)=split(/\:/,$item,2);
                   10024:             if ($role eq 'cr') { next; }
                   10025:             if ($role =~ /^cr/) {
                   10026:                 $$rolehash{$role} = (split('/',$role))[3];
                   10027:             } else {
                   10028:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10029:             }
                   10030:         }
                   10031:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10032:             push(@{$allroles},$key);
                   10033:         }
                   10034:         push (@{$allroles},'st');
                   10035:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10036:     }
                   10037:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10038: }
                   10039: 
1.555     raeburn  10040: sub user_picker {
1.1279  ! raeburn  10041:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10042:     my $currdom = $dom;
1.1253    raeburn  10043:     my @alldoms = &Apache::lonnet::all_domains();
                   10044:     if (@alldoms == 1) {
                   10045:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10046:                                                ['directorysrch'],$alldoms[0]);
                   10047:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10048:         my $showdom = $domdesc;
                   10049:         if ($showdom eq '') {
                   10050:             $showdom = $dom;
                   10051:         }
                   10052:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10053:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10054:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10055:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10056:             }
                   10057:         }
                   10058:     }
1.555     raeburn  10059:     my %curr_selected = (
                   10060:                         srchin => 'dom',
1.580     raeburn  10061:                         srchby => 'lastname',
1.555     raeburn  10062:                       );
                   10063:     my $srchterm;
1.625     raeburn  10064:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10065:         if ($srch->{'srchby'} ne '') {
                   10066:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10067:         }
                   10068:         if ($srch->{'srchin'} ne '') {
                   10069:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10070:         }
                   10071:         if ($srch->{'srchtype'} ne '') {
                   10072:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10073:         }
                   10074:         if ($srch->{'srchdomain'} ne '') {
                   10075:             $currdom = $srch->{'srchdomain'};
                   10076:         }
                   10077:         $srchterm = $srch->{'srchterm'};
                   10078:     }
1.1222    damieng  10079:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10080:                     'usr'       => 'Search criteria',
1.563     raeburn  10081:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10082:                     'uname'     => 'username',
                   10083:                     'lastname'  => 'last name',
1.555     raeburn  10084:                     'lastfirst' => 'last name, first name',
1.558     albertel 10085:                     'crs'       => 'in this course',
1.576     raeburn  10086:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10087:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10088:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10089:                     'exact'     => 'is',
                   10090:                     'contains'  => 'contains',
1.569     raeburn  10091:                     'begins'    => 'begins with',
1.1222    damieng  10092:                                        );
                   10093:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10094:                     'youm'      => "You must include some text to search for.",
                   10095:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10096:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10097:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10098:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10099:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10100:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10101:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10102:                                        );
1.1222    damieng  10103:     &html_escape(\%html_lt);
                   10104:     &js_escape(\%js_lt);
1.1255    raeburn  10105:     my $domform;
1.1277    raeburn  10106:     my $allow_blank = 1;
1.1255    raeburn  10107:     if ($fixeddom) {
1.1277    raeburn  10108:         $allow_blank = 0;
                   10109:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  10110:     } else {
1.1277    raeburn  10111:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1255    raeburn  10112:     }
1.563     raeburn  10113:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10114: 
                   10115:     my @srchins = ('crs','dom','alc','instd');
                   10116: 
                   10117:     foreach my $option (@srchins) {
                   10118:         # FIXME 'alc' option unavailable until 
                   10119:         #       loncreateuser::print_user_query_page()
                   10120:         #       has been completed.
                   10121:         next if ($option eq 'alc');
1.880     raeburn  10122:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10123:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279  ! raeburn  10124:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10125:         if ($curr_selected{'srchin'} eq $option) {
                   10126:             $srchinsel .= ' 
1.1222    damieng  10127:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10128:         } else {
                   10129:             $srchinsel .= '
1.1222    damieng  10130:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10131:         }
1.555     raeburn  10132:     }
1.563     raeburn  10133:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10134: 
                   10135:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10136:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10137:         if ($curr_selected{'srchby'} eq $option) {
                   10138:             $srchbysel .= '
1.1222    damieng  10139:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10140:         } else {
                   10141:             $srchbysel .= '
1.1222    damieng  10142:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10143:          }
                   10144:     }
                   10145:     $srchbysel .= "\n  </select>\n";
                   10146: 
                   10147:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10148:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10149:         if ($curr_selected{'srchtype'} eq $option) {
                   10150:             $srchtypesel .= '
1.1222    damieng  10151:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10152:         } else {
                   10153:             $srchtypesel .= '
1.1222    damieng  10154:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10155:         }
                   10156:     }
                   10157:     $srchtypesel .= "\n  </select>\n";
                   10158: 
1.558     albertel 10159:     my ($newuserscript,$new_user_create);
1.994     raeburn  10160:     my $context_dom = $env{'request.role.domain'};
                   10161:     if ($context eq 'requestcrs') {
                   10162:         if ($env{'form.coursedom'} ne '') { 
                   10163:             $context_dom = $env{'form.coursedom'};
                   10164:         }
                   10165:     }
1.556     raeburn  10166:     if ($forcenewuser) {
1.576     raeburn  10167:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10168:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10169:                 if ($cancreate) {
                   10170:                     $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>';
                   10171:                 } else {
1.799     bisitz   10172:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10173:                     my %usertypetext = (
                   10174:                         official   => 'institutional',
                   10175:                         unofficial => 'non-institutional',
                   10176:                     );
1.799     bisitz   10177:                     $new_user_create = '<p class="LC_warning">'
                   10178:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10179:                                       .' '
                   10180:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10181:                                           ,'<a href="'.$helplink.'">','</a>')
                   10182:                                       .'</p><br />';
1.627     raeburn  10183:                 }
1.576     raeburn  10184:             }
                   10185:         }
                   10186: 
1.556     raeburn  10187:         $newuserscript = <<"ENDSCRIPT";
                   10188: 
1.570     raeburn  10189: function setSearch(createnew,callingForm) {
1.556     raeburn  10190:     if (createnew == 1) {
1.570     raeburn  10191:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10192:             if (callingForm.srchby.options[i].value == 'uname') {
                   10193:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10194:             }
                   10195:         }
1.570     raeburn  10196:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10197:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10198: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10199:             }
                   10200:         }
1.570     raeburn  10201:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10202:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10203:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10204:             }
                   10205:         }
1.570     raeburn  10206:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10207:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10208:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10209:             }
                   10210:         }
                   10211:     }
                   10212: }
                   10213: ENDSCRIPT
1.558     albertel 10214: 
1.556     raeburn  10215:     }
                   10216: 
1.555     raeburn  10217:     my $output = <<"END_BLOCK";
1.556     raeburn  10218: <script type="text/javascript">
1.824     bisitz   10219: // <![CDATA[
1.570     raeburn  10220: function validateEntry(callingForm) {
1.558     albertel 10221: 
1.556     raeburn  10222:     var checkok = 1;
1.558     albertel 10223:     var srchin;
1.570     raeburn  10224:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10225: 	if ( callingForm.srchin[i].checked ) {
                   10226: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10227: 	}
                   10228:     }
                   10229: 
1.570     raeburn  10230:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10231:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10232:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10233:     var srchterm =  callingForm.srchterm.value;
                   10234:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10235:     var msg = "";
                   10236: 
                   10237:     if (srchterm == "") {
                   10238:         checkok = 0;
1.1222    damieng  10239:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10240:     }
                   10241: 
1.569     raeburn  10242:     if (srchtype== 'begins') {
                   10243:         if (srchterm.length < 2) {
                   10244:             checkok = 0;
1.1222    damieng  10245:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10246:         }
                   10247:     }
                   10248: 
1.556     raeburn  10249:     if (srchtype== 'contains') {
                   10250:         if (srchterm.length < 3) {
                   10251:             checkok = 0;
1.1222    damieng  10252:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10253:         }
                   10254:     }
                   10255:     if (srchin == 'instd') {
                   10256:         if (srchdomain == '') {
                   10257:             checkok = 0;
1.1222    damieng  10258:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10259:         }
                   10260:     }
                   10261:     if (srchin == 'dom') {
                   10262:         if (srchdomain == '') {
                   10263:             checkok = 0;
1.1222    damieng  10264:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10265:         }
                   10266:     }
                   10267:     if (srchby == 'lastfirst') {
                   10268:         if (srchterm.indexOf(",") == -1) {
                   10269:             checkok = 0;
1.1222    damieng  10270:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10271:         }
                   10272:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10273:             checkok = 0;
1.1222    damieng  10274:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10275:         }
                   10276:     }
                   10277:     if (checkok == 0) {
1.1222    damieng  10278:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10279:         return;
                   10280:     }
                   10281:     if (checkok == 1) {
1.570     raeburn  10282:         callingForm.submit();
1.556     raeburn  10283:     }
                   10284: }
                   10285: 
                   10286: $newuserscript
                   10287: 
1.824     bisitz   10288: // ]]>
1.556     raeburn  10289: </script>
1.558     albertel 10290: 
                   10291: $new_user_create
                   10292: 
1.555     raeburn  10293: END_BLOCK
1.558     albertel 10294: 
1.876     raeburn  10295:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  10296:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10297:                $domform.
                   10298:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  10299:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10300:                $srchbysel.
                   10301:                $srchtypesel. 
                   10302:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10303:                $srchinsel.
                   10304:                &Apache::lonhtmlcommon::row_closure(1). 
                   10305:                &Apache::lonhtmlcommon::end_pick_box().
                   10306:                '<br />';
1.1253    raeburn  10307:     return ($output,1);
1.555     raeburn  10308: }
                   10309: 
1.612     raeburn  10310: sub user_rule_check {
1.615     raeburn  10311:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  10312:     my ($response,%inst_response);
1.612     raeburn  10313:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  10314:         if (keys(%{$usershash}) > 1) {
                   10315:             my (%by_username,%by_id,%userdoms);
                   10316:             my $checkid; 
                   10317:             if (ref($checks) eq 'HASH') {
                   10318:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10319:                     $checkid = 1;
                   10320:                 }
                   10321:             }
                   10322:             foreach my $user (keys(%{$usershash})) {
                   10323:                 my ($uname,$udom) = split(/:/,$user);
                   10324:                 if ($checkid) {
                   10325:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10326:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  10327:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  10328:                             $userdoms{$udom} = 1;
1.1227    raeburn  10329:                             if (ref($inst_results) eq 'HASH') {
                   10330:                                 $inst_results->{$uname.':'.$udom} = {};
                   10331:                             }
1.1226    raeburn  10332:                         }
                   10333:                     }
                   10334:                 } else {
                   10335:                     $by_username{$udom}{$uname} = 1;
                   10336:                     $userdoms{$udom} = 1;
1.1227    raeburn  10337:                     if (ref($inst_results) eq 'HASH') {
                   10338:                         $inst_results->{$uname.':'.$udom} = {};
                   10339:                     }
1.1226    raeburn  10340:                 }
                   10341:             }
                   10342:             foreach my $udom (keys(%userdoms)) {
                   10343:                 if (!$got_rules->{$udom}) {
                   10344:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10345:                                                              ['usercreation'],$udom);
                   10346:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10347:                         foreach my $item ('username','id') {
                   10348:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  10349:                                 $$curr_rules{$udom}{$item} =
                   10350:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  10351:                             }
                   10352:                         }
                   10353:                     }
                   10354:                     $got_rules->{$udom} = 1;
                   10355:                 }
1.612     raeburn  10356:             }
1.1226    raeburn  10357:             if ($checkid) {
                   10358:                 foreach my $udom (keys(%by_id)) {
                   10359:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10360:                     if ($outcome eq 'ok') {
1.1227    raeburn  10361:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10362:                             my $uname = $by_id{$udom}{$id};
                   10363:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10364:                         }
1.1226    raeburn  10365:                         if (ref($results) eq 'HASH') {
                   10366:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  10367:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10368:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10369:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10370:                                 }
1.1226    raeburn  10371:                             }
                   10372:                         }
                   10373:                     }
1.612     raeburn  10374:                 }
1.615     raeburn  10375:             } else {
1.1226    raeburn  10376:                 foreach my $udom (keys(%by_username)) {
                   10377:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10378:                     if ($outcome eq 'ok') {
1.1227    raeburn  10379:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10380:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10381:                         }
1.1226    raeburn  10382:                         if (ref($results) eq 'HASH') {
                   10383:                             foreach my $uname (keys(%{$results})) {
                   10384:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10385:                             }
                   10386:                         }
                   10387:                     }
                   10388:                 }
1.612     raeburn  10389:             }
1.1226    raeburn  10390:         } elsif (keys(%{$usershash}) == 1) {
                   10391:             my $user = (keys(%{$usershash}))[0];
                   10392:             my ($uname,$udom) = split(/:/,$user);
                   10393:             if (($udom ne '') && ($uname ne '')) {
                   10394:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10395:                     if (ref($checks) eq 'HASH') {
                   10396:                         if (defined($checks->{'username'})) {
                   10397:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   10398:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10399:                         } elsif (defined($checks->{'id'})) {
                   10400:                             if ($usershash->{$user}->{'id'} ne '') {
                   10401:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10402:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10403:                                                                   $usershash->{$user}->{'id'});
                   10404:                             } else {
                   10405:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10406:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10407:                             }
1.585     raeburn  10408:                         }
1.1226    raeburn  10409:                     } else {
                   10410:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10411:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10412:                        return;
                   10413:                     }
                   10414:                     if (!$got_rules->{$udom}) {
                   10415:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10416:                                                                  ['usercreation'],$udom);
                   10417:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10418:                             foreach my $item ('username','id') {
                   10419:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10420:                                    $$curr_rules{$udom}{$item} = 
                   10421:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10422:                                 }
                   10423:                             }
                   10424:                         }
                   10425:                         $got_rules->{$udom} = 1;
1.585     raeburn  10426:                     }
                   10427:                 }
1.1226    raeburn  10428:             } else {
                   10429:                 return;
                   10430:             }
                   10431:         } else {
                   10432:             return;
                   10433:         }
                   10434:         foreach my $user (keys(%{$usershash})) {
                   10435:             my ($uname,$udom) = split(/:/,$user);
                   10436:             next if (($udom eq '') || ($uname eq ''));
                   10437:             my $id;
1.1227    raeburn  10438:             if (ref($inst_results) eq 'HASH') {
                   10439:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10440:                     $id = $inst_results->{$user}->{'id'};
                   10441:                 }
                   10442:             }
                   10443:             if ($id eq '') { 
                   10444:                 if (ref($usershash->{$user})) {
                   10445:                     $id = $usershash->{$user}->{'id'};
                   10446:                 }
1.585     raeburn  10447:             }
1.612     raeburn  10448:             foreach my $item (keys(%{$checks})) {
                   10449:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10450:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10451:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  10452:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10453:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10454:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10455:                                 if ($rule_check{$rule}) {
                   10456:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  10457:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10458:                                         if (ref($inst_results) eq 'HASH') {
                   10459:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10460:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10461:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  10462:                                                 } elsif ($item eq 'id') {
                   10463:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10464:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10465:                                                     }
1.615     raeburn  10466:                                                 }
1.612     raeburn  10467:                                             }
                   10468:                                         }
1.615     raeburn  10469:                                     }
                   10470:                                     last;
1.585     raeburn  10471:                                 }
                   10472:                             }
                   10473:                         }
                   10474:                     }
                   10475:                 }
                   10476:             }
                   10477:         }
                   10478:     }
1.612     raeburn  10479:     return;
                   10480: }
                   10481: 
                   10482: sub user_rule_formats {
                   10483:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10484:     my %text = ( 
                   10485:                  'username' => 'Usernames',
                   10486:                  'id'       => 'IDs',
                   10487:                );
                   10488:     my $output;
                   10489:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10490:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10491:         if (@{$ruleorder} > 0) {
1.1102    raeburn  10492:             $output = '<br />'.
                   10493:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10494:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10495:                       ' <ul>';
1.612     raeburn  10496:             foreach my $rule (@{$ruleorder}) {
                   10497:                 if (ref($curr_rules) eq 'ARRAY') {
                   10498:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10499:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10500:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10501:                                         $rules->{$rule}{'desc'}.'</li>';
                   10502:                         }
                   10503:                     }
                   10504:                 }
                   10505:             }
                   10506:             $output .= '</ul>';
                   10507:         }
                   10508:     }
                   10509:     return $output;
                   10510: }
                   10511: 
                   10512: sub instrule_disallow_msg {
1.615     raeburn  10513:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10514:     my $response;
                   10515:     my %text = (
                   10516:                   item   => 'username',
                   10517:                   items  => 'usernames',
                   10518:                   match  => 'matches',
                   10519:                   do     => 'does',
                   10520:                   action => 'a username',
                   10521:                   one    => 'one',
                   10522:                );
                   10523:     if ($count > 1) {
                   10524:         $text{'item'} = 'usernames';
                   10525:         $text{'match'} ='match';
                   10526:         $text{'do'} = 'do';
                   10527:         $text{'action'} = 'usernames',
                   10528:         $text{'one'} = 'ones';
                   10529:     }
                   10530:     if ($checkitem eq 'id') {
                   10531:         $text{'items'} = 'IDs';
                   10532:         $text{'item'} = 'ID';
                   10533:         $text{'action'} = 'an ID';
1.615     raeburn  10534:         if ($count > 1) {
                   10535:             $text{'item'} = 'IDs';
                   10536:             $text{'action'} = 'IDs';
                   10537:         }
1.612     raeburn  10538:     }
1.674     bisitz   10539:     $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  10540:     if ($mode eq 'upload') {
                   10541:         if ($checkitem eq 'username') {
                   10542:             $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'}.");
                   10543:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10544:             $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  10545:         }
1.669     raeburn  10546:     } elsif ($mode eq 'selfcreate') {
                   10547:         if ($checkitem eq 'id') {
                   10548:             $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.");
                   10549:         }
1.615     raeburn  10550:     } else {
                   10551:         if ($checkitem eq 'username') {
                   10552:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10553:         } elsif ($checkitem eq 'id') {
                   10554:             $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.");
                   10555:         }
1.612     raeburn  10556:     }
                   10557:     return $response;
1.585     raeburn  10558: }
                   10559: 
1.624     raeburn  10560: sub personal_data_fieldtitles {
                   10561:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10562:                         id => 'Student/Employee ID',
                   10563:                         permanentemail => 'E-mail address',
                   10564:                         lastname => 'Last Name',
                   10565:                         firstname => 'First Name',
                   10566:                         middlename => 'Middle Name',
                   10567:                         generation => 'Generation',
                   10568:                         gen => 'Generation',
1.765     raeburn  10569:                         inststatus => 'Affiliation',
1.624     raeburn  10570:                    );
                   10571:     return %fieldtitles;
                   10572: }
                   10573: 
1.642     raeburn  10574: sub sorted_inst_types {
                   10575:     my ($dom) = @_;
1.1185    raeburn  10576:     my ($usertypes,$order);
                   10577:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10578:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10579:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10580:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10581:     } else {
                   10582:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10583:     }
1.642     raeburn  10584:     my $othertitle = &mt('All users');
                   10585:     if ($env{'request.course.id'}) {
1.668     raeburn  10586:         $othertitle  = &mt('Any users');
1.642     raeburn  10587:     }
                   10588:     my @types;
                   10589:     if (ref($order) eq 'ARRAY') {
                   10590:         @types = @{$order};
                   10591:     }
                   10592:     if (@types == 0) {
                   10593:         if (ref($usertypes) eq 'HASH') {
                   10594:             @types = sort(keys(%{$usertypes}));
                   10595:         }
                   10596:     }
                   10597:     if (keys(%{$usertypes}) > 0) {
                   10598:         $othertitle = &mt('Other users');
                   10599:     }
                   10600:     return ($othertitle,$usertypes,\@types);
                   10601: }
                   10602: 
1.645     raeburn  10603: sub get_institutional_codes {
                   10604:     my ($settings,$allcourses,$LC_code) = @_;
                   10605: # Get complete list of course sections to update
                   10606:     my @currsections = ();
                   10607:     my @currxlists = ();
                   10608:     my $coursecode = $$settings{'internal.coursecode'};
                   10609: 
                   10610:     if ($$settings{'internal.sectionnums'} ne '') {
                   10611:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10612:     }
                   10613: 
                   10614:     if ($$settings{'internal.crosslistings'} ne '') {
                   10615:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10616:     }
                   10617: 
                   10618:     if (@currxlists > 0) {
                   10619:         foreach (@currxlists) {
                   10620:             if (m/^([^:]+):(\w*)$/) {
                   10621:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  10622:                     push(@{$allcourses},$1);
1.645     raeburn  10623:                     $$LC_code{$1} = $2;
                   10624:                 }
                   10625:             }
                   10626:         }
                   10627:     }
                   10628:  
                   10629:     if (@currsections > 0) {
                   10630:         foreach (@currsections) {
                   10631:             if (m/^(\w+):(\w*)$/) {
                   10632:                 my $sec = $coursecode.$1;
                   10633:                 my $lc_sec = $2;
                   10634:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1263    raeburn  10635:                     push(@{$allcourses},$sec);
1.645     raeburn  10636:                     $$LC_code{$sec} = $lc_sec;
                   10637:                 }
                   10638:             }
                   10639:         }
                   10640:     }
                   10641:     return;
                   10642: }
                   10643: 
1.971     raeburn  10644: sub get_standard_codeitems {
                   10645:     return ('Year','Semester','Department','Number','Section');
                   10646: }
                   10647: 
1.112     bowersj2 10648: =pod
                   10649: 
1.780     raeburn  10650: =head1 Slot Helpers
                   10651: 
                   10652: =over 4
                   10653: 
                   10654: =item * sorted_slots()
                   10655: 
1.1040    raeburn  10656: Sorts an array of slot names in order of an optional sort key,
                   10657: default sort is by slot start time (earliest first). 
1.780     raeburn  10658: 
                   10659: Inputs:
                   10660: 
                   10661: =over 4
                   10662: 
                   10663: slotsarr  - Reference to array of unsorted slot names.
                   10664: 
                   10665: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10666: 
1.1040    raeburn  10667: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10668: 
1.549     albertel 10669: =back
                   10670: 
1.780     raeburn  10671: Returns:
                   10672: 
                   10673: =over 4
                   10674: 
1.1040    raeburn  10675: sorted   - An array of slot names sorted by a specified sort key 
                   10676:            (default sort key is start time of the slot).
1.780     raeburn  10677: 
                   10678: =back
                   10679: 
                   10680: =cut
                   10681: 
                   10682: 
                   10683: sub sorted_slots {
1.1040    raeburn  10684:     my ($slotsarr,$slots,$sortkey) = @_;
                   10685:     if ($sortkey eq '') {
                   10686:         $sortkey = 'starttime';
                   10687:     }
1.780     raeburn  10688:     my @sorted;
                   10689:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10690:         @sorted =
                   10691:             sort {
                   10692:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10693:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10694:                      }
                   10695:                      if (ref($slots->{$a})) { return -1;}
                   10696:                      if (ref($slots->{$b})) { return 1;}
                   10697:                      return 0;
                   10698:                  } @{$slotsarr};
                   10699:     }
                   10700:     return @sorted;
                   10701: }
                   10702: 
1.1040    raeburn  10703: =pod
                   10704: 
                   10705: =item * get_future_slots()
                   10706: 
                   10707: Inputs:
                   10708: 
                   10709: =over 4
                   10710: 
                   10711: cnum - course number
                   10712: 
                   10713: cdom - course domain
                   10714: 
                   10715: now - current UNIX time
                   10716: 
                   10717: symb - optional symb
                   10718: 
                   10719: =back
                   10720: 
                   10721: Returns:
                   10722: 
                   10723: =over 4
                   10724: 
                   10725: sorted_reservable - ref to array of student_schedulable slots currently 
                   10726:                     reservable, ordered by end date of reservation period.
                   10727: 
                   10728: reservable_now - ref to hash of student_schedulable slots currently
                   10729:                  reservable.
                   10730: 
                   10731:     Keys in inner hash are:
                   10732:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10733:     (b) endreserve: end date of reservation period.
                   10734:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10735:         selected.
1.1040    raeburn  10736: 
                   10737: sorted_future - ref to array of student_schedulable slots reservable in
                   10738:                 the future, ordered by start date of reservation period.
                   10739: 
                   10740: future_reservable - ref to hash of student_schedulable slots reservable
                   10741:                     in the future.
                   10742: 
                   10743:     Keys in inner hash are:
                   10744:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10745:     (b) startreserve: start date of reservation period.
                   10746:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10747:         selected.
1.1040    raeburn  10748: 
                   10749: =back
                   10750: 
                   10751: =cut
                   10752: 
                   10753: sub get_future_slots {
                   10754:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  10755:     my $map;
                   10756:     if ($symb) {
                   10757:         ($map) = &Apache::lonnet::decode_symb($symb);
                   10758:     }
1.1040    raeburn  10759:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10760:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10761:     foreach my $slot (keys(%slots)) {
                   10762:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10763:         if ($symb) {
1.1229    raeburn  10764:             if ($slots{$slot}->{'symb'} ne '') {
                   10765:                 my $canuse;
                   10766:                 my %oksymbs;
                   10767:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   10768:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   10769:                 if ($oksymbs{$symb}) {
                   10770:                     $canuse = 1;
                   10771:                 } else {
                   10772:                     foreach my $item (@slotsymbs) {
                   10773:                         if ($item =~ /\.(page|sequence)$/) {
                   10774:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   10775:                             if (($map ne '') && ($map eq $sloturl)) {
                   10776:                                 $canuse = 1;
                   10777:                                 last;
                   10778:                             }
                   10779:                         }
                   10780:                     }
                   10781:                 }
                   10782:                 next unless ($canuse);
                   10783:             }
1.1040    raeburn  10784:         }
                   10785:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10786:             ($slots{$slot}->{'endtime'} > $now)) {
                   10787:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10788:                 my $userallowed = 0;
                   10789:                 if ($slots{$slot}->{'allowedsections'}) {
                   10790:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10791:                     if (!defined($env{'request.role.sec'})
                   10792:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10793:                         $userallowed=1;
                   10794:                     } else {
                   10795:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10796:                             $userallowed=1;
                   10797:                         }
                   10798:                     }
                   10799:                     unless ($userallowed) {
                   10800:                         if (defined($env{'request.course.groups'})) {
                   10801:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10802:                             foreach my $group (@groups) {
                   10803:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10804:                                     $userallowed=1;
                   10805:                                     last;
                   10806:                                 }
                   10807:                             }
                   10808:                         }
                   10809:                     }
                   10810:                 }
                   10811:                 if ($slots{$slot}->{'allowedusers'}) {
                   10812:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10813:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10814:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10815:                         $userallowed = 1;
                   10816:                     }
                   10817:                 }
                   10818:                 next unless($userallowed);
                   10819:             }
                   10820:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10821:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10822:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  10823:             my $uniqueperiod;
                   10824:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10825:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10826:             }
1.1040    raeburn  10827:             if (($startreserve < $now) &&
                   10828:                 (!$endreserve || $endreserve > $now)) {
                   10829:                 my $lastres = $endreserve;
                   10830:                 if (!$lastres) {
                   10831:                     $lastres = $slots{$slot}->{'starttime'};
                   10832:                 }
                   10833:                 $reservable_now{$slot} = {
                   10834:                                            symb       => $symb,
1.1250    raeburn  10835:                                            endreserve => $lastres,
                   10836:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  10837:                                          };
                   10838:             } elsif (($startreserve > $now) &&
                   10839:                      (!$endreserve || $endreserve > $startreserve)) {
                   10840:                 $future_reservable{$slot} = {
                   10841:                                               symb         => $symb,
1.1250    raeburn  10842:                                               startreserve => $startreserve,
                   10843:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10844:                                             };
                   10845:             }
                   10846:         }
                   10847:     }
                   10848:     my @unsorted_reservable = keys(%reservable_now);
                   10849:     if (@unsorted_reservable > 0) {
                   10850:         @sorted_reservable = 
                   10851:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10852:     }
                   10853:     my @unsorted_future = keys(%future_reservable);
                   10854:     if (@unsorted_future > 0) {
                   10855:         @sorted_future =
                   10856:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10857:     }
                   10858:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10859: }
1.780     raeburn  10860: 
                   10861: =pod
                   10862: 
1.1057    foxr     10863: =back
                   10864: 
1.549     albertel 10865: =head1 HTTP Helpers
                   10866: 
                   10867: =over 4
                   10868: 
1.648     raeburn  10869: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10870: 
1.258     albertel 10871: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10872: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10873: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10874: 
                   10875: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10876: $possible_names is an ref to an array of form element names.  As an example:
                   10877: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10878: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10879: 
                   10880: =cut
1.1       albertel 10881: 
1.6       albertel 10882: sub get_unprocessed_cgi {
1.25      albertel 10883:   my ($query,$possible_names)= @_;
1.26      matthew  10884:   # $Apache::lonxml::debug=1;
1.356     albertel 10885:   foreach my $pair (split(/&/,$query)) {
                   10886:     my ($name, $value) = split(/=/,$pair);
1.369     www      10887:     $name = &unescape($name);
1.25      albertel 10888:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10889:       $value =~ tr/+/ /;
                   10890:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10891:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10892:     }
1.16      harris41 10893:   }
1.6       albertel 10894: }
                   10895: 
1.112     bowersj2 10896: =pod
                   10897: 
1.648     raeburn  10898: =item * &cacheheader() 
1.112     bowersj2 10899: 
                   10900: returns cache-controlling header code
                   10901: 
                   10902: =cut
                   10903: 
1.7       albertel 10904: sub cacheheader {
1.258     albertel 10905:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10906:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10907:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10908:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10909:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10910:     return $output;
1.7       albertel 10911: }
                   10912: 
1.112     bowersj2 10913: =pod
                   10914: 
1.648     raeburn  10915: =item * &no_cache($r) 
1.112     bowersj2 10916: 
                   10917: specifies header code to not have cache
                   10918: 
                   10919: =cut
                   10920: 
1.9       albertel 10921: sub no_cache {
1.216     albertel 10922:     my ($r) = @_;
                   10923:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10924: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10925:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10926:     $r->no_cache(1);
                   10927:     $r->header_out("Expires" => $date);
                   10928:     $r->header_out("Pragma" => "no-cache");
1.123     www      10929: }
                   10930: 
                   10931: sub content_type {
1.181     albertel 10932:     my ($r,$type,$charset) = @_;
1.299     foxr     10933:     if ($r) {
                   10934: 	#  Note that printout.pl calls this with undef for $r.
                   10935: 	&no_cache($r);
                   10936:     }
1.258     albertel 10937:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10938:     unless ($charset) {
                   10939: 	$charset=&Apache::lonlocal::current_encoding;
                   10940:     }
                   10941:     if ($charset) { $type.='; charset='.$charset; }
                   10942:     if ($r) {
                   10943: 	$r->content_type($type);
                   10944:     } else {
                   10945: 	print("Content-type: $type\n\n");
                   10946:     }
1.9       albertel 10947: }
1.25      albertel 10948: 
1.112     bowersj2 10949: =pod
                   10950: 
1.648     raeburn  10951: =item * &add_to_env($name,$value) 
1.112     bowersj2 10952: 
1.258     albertel 10953: adds $name to the %env hash with value
1.112     bowersj2 10954: $value, if $name already exists, the entry is converted to an array
                   10955: reference and $value is added to the array.
                   10956: 
                   10957: =cut
                   10958: 
1.25      albertel 10959: sub add_to_env {
                   10960:   my ($name,$value)=@_;
1.258     albertel 10961:   if (defined($env{$name})) {
                   10962:     if (ref($env{$name})) {
1.25      albertel 10963:       #already have multiple values
1.258     albertel 10964:       push(@{ $env{$name} },$value);
1.25      albertel 10965:     } else {
                   10966:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10967:       my $first=$env{$name};
                   10968:       undef($env{$name});
                   10969:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10970:     }
                   10971:   } else {
1.258     albertel 10972:     $env{$name}=$value;
1.25      albertel 10973:   }
1.31      albertel 10974: }
1.149     albertel 10975: 
                   10976: =pod
                   10977: 
1.648     raeburn  10978: =item * &get_env_multiple($name) 
1.149     albertel 10979: 
1.258     albertel 10980: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10981: values may be defined and end up as an array ref.
                   10982: 
                   10983: returns an array of values
                   10984: 
                   10985: =cut
                   10986: 
                   10987: sub get_env_multiple {
                   10988:     my ($name) = @_;
                   10989:     my @values;
1.258     albertel 10990:     if (defined($env{$name})) {
1.149     albertel 10991:         # exists is it an array
1.258     albertel 10992:         if (ref($env{$name})) {
                   10993:             @values=@{ $env{$name} };
1.149     albertel 10994:         } else {
1.258     albertel 10995:             $values[0]=$env{$name};
1.149     albertel 10996:         }
                   10997:     }
                   10998:     return(@values);
                   10999: }
                   11000: 
1.1249    damieng  11001: # Looks at given dependencies, and returns something depending on the context.
                   11002: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   11003: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   11004: # For all other contexts, returns ($output, $counter, $numpathchg).
                   11005: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   11006: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
                   11007: # $numpathchg: integer with the number of cleaned up dependency paths.
                   11008: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   11009: # \%mapping: hash reference clean path -> original path for all dependencies.
                   11010: # @param {string} actionurl - The path to the handler, indicative of the context.
                   11011: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   11012: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   11013: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   11014: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
                   11015: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  11016: sub ask_for_embedded_content {
1.1249    damieng  11017:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  11018:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11019:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  11020:         %currsubfile,%unused,$rem);
1.1071    raeburn  11021:     my $counter = 0;
                   11022:     my $numnew = 0;
1.987     raeburn  11023:     my $numremref = 0;
                   11024:     my $numinvalid = 0;
                   11025:     my $numpathchg = 0;
                   11026:     my $numexisting = 0;
1.1071    raeburn  11027:     my $numunused = 0;
                   11028:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11029:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11030:     my $heading = &mt('Upload embedded files');
                   11031:     my $buttontext = &mt('Upload');
                   11032: 
1.1249    damieng  11033:     # fills these variables based on the context:
                   11034:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11035:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11036:     if ($env{'request.course.id'}) {
1.1123    raeburn  11037:         if ($actionurl eq '/adm/dependencies') {
                   11038:             $navmap = Apache::lonnavmaps::navmap->new();
                   11039:         }
                   11040:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11041:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11042:     }
1.1123    raeburn  11043:     if (($actionurl eq '/adm/portfolio') || 
                   11044:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11045:         my $current_path='/';
                   11046:         if ($env{'form.currentpath'}) {
                   11047:             $current_path = $env{'form.currentpath'};
                   11048:         }
                   11049:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  11050:             $udom = $cdom;
                   11051:             $uname = $cnum;
1.984     raeburn  11052:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11053:         } else {
                   11054:             $udom = $env{'user.domain'};
                   11055:             $uname = $env{'user.name'};
                   11056:             $url = '/userfiles/portfolio';
                   11057:         }
1.987     raeburn  11058:         $toplevel = $url.'/';
1.984     raeburn  11059:         $url .= $current_path;
                   11060:         $getpropath = 1;
1.987     raeburn  11061:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11062:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11063:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11064:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11065:         $toplevel = $url;
1.984     raeburn  11066:         if ($rest ne '') {
1.987     raeburn  11067:             $url .= $rest;
                   11068:         }
                   11069:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11070:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11071:             $url = $args->{'docs_url'};
                   11072:             $toplevel = $url;
1.1084    raeburn  11073:             if ($args->{'context'} eq 'paste') {
                   11074:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11075:                 ($path) = 
                   11076:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11077:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11078:                 $fileloc =~ s{^/}{};
                   11079:             }
1.1071    raeburn  11080:         }
1.1084    raeburn  11081:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  11082:         if ($env{'request.course.id'} ne '') {
                   11083:             if (ref($args) eq 'HASH') {
                   11084:                 $url = $args->{'docs_url'};
                   11085:                 $title = $args->{'docs_title'};
1.1126    raeburn  11086:                 $toplevel = $url; 
                   11087:                 unless ($toplevel =~ m{^/}) {
                   11088:                     $toplevel = "/$url";
                   11089:                 }
1.1085    raeburn  11090:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  11091:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11092:                     $path = $1;
                   11093:                 } else {
                   11094:                     ($path) =
                   11095:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11096:                 }
1.1195    raeburn  11097:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11098:                     $fileloc = $toplevel;
                   11099:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11100:                     my ($udom,$uname,$fname) =
                   11101:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11102:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11103:                 } else {
                   11104:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11105:                 }
1.1071    raeburn  11106:                 $fileloc =~ s{^/}{};
                   11107:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11108:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11109:             }
1.987     raeburn  11110:         }
1.1123    raeburn  11111:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11112:         $udom = $cdom;
                   11113:         $uname = $cnum;
                   11114:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11115:         $toplevel = $url;
                   11116:         $path = $url;
                   11117:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11118:         $fileloc =~ s{^/}{};
1.987     raeburn  11119:     }
1.1249    damieng  11120:     
                   11121:     # parses the dependency paths to get some info
                   11122:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   11123:     # $newfiles: hash URL -> 1 for new files or external URLs
                   11124:     # (will be completed later)
                   11125:     # $mapping:
                   11126:     #   for external URLs: external URL -> external URL
                   11127:     #   for relative paths: clean path -> original path
                   11128:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   11129:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  11130:     foreach my $file (keys(%{$allfiles})) {
                   11131:         my $embed_file;
                   11132:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11133:             $embed_file = $1;
                   11134:         } else {
                   11135:             $embed_file = $file;
                   11136:         }
1.1158    raeburn  11137:         my ($absolutepath,$cleaned_file);
                   11138:         if ($embed_file =~ m{^\w+://}) {
                   11139:             $cleaned_file = $embed_file;
1.1147    raeburn  11140:             $newfiles{$cleaned_file} = 1;
                   11141:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11142:         } else {
1.1158    raeburn  11143:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11144:             if ($embed_file =~ m{^/}) {
                   11145:                 $absolutepath = $embed_file;
                   11146:             }
1.1147    raeburn  11147:             if ($cleaned_file =~ m{/}) {
                   11148:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11149:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11150:                 my $item = $fname;
                   11151:                 if ($path ne '') {
                   11152:                     $item = $path.'/'.$fname;
                   11153:                     $subdependencies{$path}{$fname} = 1;
                   11154:                 } else {
                   11155:                     $dependencies{$item} = 1;
                   11156:                 }
                   11157:                 if ($absolutepath) {
                   11158:                     $mapping{$item} = $absolutepath;
                   11159:                 } else {
                   11160:                     $mapping{$item} = $embed_file;
                   11161:                 }
                   11162:             } else {
                   11163:                 $dependencies{$embed_file} = 1;
                   11164:                 if ($absolutepath) {
1.1147    raeburn  11165:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11166:                 } else {
1.1147    raeburn  11167:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11168:                 }
                   11169:             }
1.984     raeburn  11170:         }
                   11171:     }
1.1249    damieng  11172:     
                   11173:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   11174:     # and lists
                   11175:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   11176:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   11177:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   11178:     #                                    the path had to be cleaned up
                   11179:     # $existing: hash clean path -> 1 if the file exists
                   11180:     # $numexisting: number of keys in $existing
                   11181:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   11182:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   11183:     #                                      dependency subdirectories that are
                   11184:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  11185:     my $dirptr = 16384;
1.984     raeburn  11186:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11187:         $currsubfile{$path} = {};
1.1123    raeburn  11188:         if (($actionurl eq '/adm/portfolio') || 
                   11189:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11190:             my ($sublistref,$listerror) =
                   11191:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11192:             if (ref($sublistref) eq 'ARRAY') {
                   11193:                 foreach my $line (@{$sublistref}) {
                   11194:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11195:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11196:                 }
1.984     raeburn  11197:             }
1.987     raeburn  11198:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11199:             if (opendir(my $dir,$url.'/'.$path)) {
                   11200:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11201:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11202:             }
1.1084    raeburn  11203:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11204:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11205:                   ($args->{'context'} eq 'paste')) ||
                   11206:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11207:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  11208:                 my $dir;
                   11209:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11210:                     $dir = $fileloc;
                   11211:                 } else {
                   11212:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11213:                 }
1.1071    raeburn  11214:                 if ($dir ne '') {
                   11215:                     my ($sublistref,$listerror) =
                   11216:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11217:                     if (ref($sublistref) eq 'ARRAY') {
                   11218:                         foreach my $line (@{$sublistref}) {
                   11219:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11220:                                 undef,$mtime)=split(/\&/,$line,12);
                   11221:                             unless (($testdir&$dirptr) ||
                   11222:                                     ($file_name =~ /^\.\.?$/)) {
                   11223:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11224:                             }
                   11225:                         }
                   11226:                     }
                   11227:                 }
1.984     raeburn  11228:             }
                   11229:         }
                   11230:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11231:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11232:                 my $item = $path.'/'.$file;
                   11233:                 unless ($mapping{$item} eq $item) {
                   11234:                     $pathchanges{$item} = 1;
                   11235:                 }
                   11236:                 $existing{$item} = 1;
                   11237:                 $numexisting ++;
                   11238:             } else {
                   11239:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11240:             }
                   11241:         }
1.1071    raeburn  11242:         if ($actionurl eq '/adm/dependencies') {
                   11243:             foreach my $path (keys(%currsubfile)) {
                   11244:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11245:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11246:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  11247:                              next if (($rem ne '') &&
                   11248:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11249:                                        (ref($navmap) &&
                   11250:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11251:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11252:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11253:                              $unused{$path.'/'.$file} = 1; 
                   11254:                          }
                   11255:                     }
                   11256:                 }
                   11257:             }
                   11258:         }
1.984     raeburn  11259:     }
1.1249    damieng  11260:     
                   11261:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   11262:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  11263:     my %currfile;
1.1123    raeburn  11264:     if (($actionurl eq '/adm/portfolio') ||
                   11265:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11266:         my ($dirlistref,$listerror) =
                   11267:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11268:         if (ref($dirlistref) eq 'ARRAY') {
                   11269:             foreach my $line (@{$dirlistref}) {
                   11270:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11271:                 $currfile{$file_name} = 1;
                   11272:             }
1.984     raeburn  11273:         }
1.987     raeburn  11274:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11275:         if (opendir(my $dir,$url)) {
1.987     raeburn  11276:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11277:             map {$currfile{$_} = 1;} @dir_list;
                   11278:         }
1.1084    raeburn  11279:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11280:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11281:               ($args->{'context'} eq 'paste')) ||
                   11282:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11283:         if ($env{'request.course.id'} ne '') {
                   11284:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11285:             if ($dir ne '') {
                   11286:                 my ($dirlistref,$listerror) =
                   11287:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11288:                 if (ref($dirlistref) eq 'ARRAY') {
                   11289:                     foreach my $line (@{$dirlistref}) {
                   11290:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11291:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11292:                         unless (($testdir&$dirptr) ||
                   11293:                                 ($file_name =~ /^\.\.?$/)) {
                   11294:                             $currfile{$file_name} = [$size,$mtime];
                   11295:                         }
                   11296:                     }
                   11297:                 }
                   11298:             }
                   11299:         }
1.984     raeburn  11300:     }
1.1249    damieng  11301:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   11302:     # are not in subdirectories, using $currfile
1.984     raeburn  11303:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11304:         if (exists($currfile{$file})) {
1.987     raeburn  11305:             unless ($mapping{$file} eq $file) {
                   11306:                 $pathchanges{$file} = 1;
                   11307:             }
                   11308:             $existing{$file} = 1;
                   11309:             $numexisting ++;
                   11310:         } else {
1.984     raeburn  11311:             $newfiles{$file} = 1;
                   11312:         }
                   11313:     }
1.1071    raeburn  11314:     foreach my $file (keys(%currfile)) {
                   11315:         unless (($file eq $filename) ||
                   11316:                 ($file eq $filename.'.bak') ||
                   11317:                 ($dependencies{$file})) {
1.1085    raeburn  11318:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  11319:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11320:                     next if (($rem ne '') &&
                   11321:                              (($env{"httpref.$rem".$file} ne '') ||
                   11322:                               (ref($navmap) &&
                   11323:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11324:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11325:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11326:                 }
1.1085    raeburn  11327:             }
1.1071    raeburn  11328:             $unused{$file} = 1;
                   11329:         }
                   11330:     }
1.1249    damieng  11331:     
                   11332:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  11333:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11334:         ($args->{'context'} eq 'paste')) {
                   11335:         $counter = scalar(keys(%existing));
                   11336:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  11337:         return ($output,$counter,$numpathchg,\%existing);
                   11338:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   11339:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11340:         $counter = scalar(keys(%existing));
                   11341:         $numpathchg = scalar(keys(%pathchanges));
                   11342:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  11343:     }
1.1249    damieng  11344:     
                   11345:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   11346:     
                   11347:     # $upload_output: missing dependencies (with upload form)
                   11348:     # $modify_output: uploaded dependencies (in use)
                   11349:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  11350:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11351:         if ($actionurl eq '/adm/dependencies') {
                   11352:             next if ($embed_file =~ m{^\w+://});
                   11353:         }
1.660     raeburn  11354:         $upload_output .= &start_data_table_row().
1.1123    raeburn  11355:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11356:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11357:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  11358:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11359:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11360:         }
1.1123    raeburn  11361:         $upload_output .= '</td>';
1.1071    raeburn  11362:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  11363:             $upload_output.='<td align="right">'.
                   11364:                             '<span class="LC_info LC_fontsize_medium">'.
                   11365:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11366:             $numremref++;
1.660     raeburn  11367:         } elsif ($args->{'error_on_invalid_names'}
                   11368:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  11369:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11370:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11371:             $numinvalid++;
1.660     raeburn  11372:         } else {
1.1123    raeburn  11373:             $upload_output .= '<td>'.
                   11374:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11375:                                                      $embed_file,\%mapping,
1.1071    raeburn  11376:                                                      $allfiles,$codebase,'upload');
                   11377:             $counter ++;
                   11378:             $numnew ++;
1.987     raeburn  11379:         }
                   11380:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11381:     }
                   11382:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11383:         if ($actionurl eq '/adm/dependencies') {
                   11384:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11385:             $modify_output .= &start_data_table_row().
                   11386:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11387:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11388:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11389:                               '<td>'.$size.'</td>'.
                   11390:                               '<td>'.$mtime.'</td>'.
                   11391:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11392:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11393:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11394:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11395:                               &embedded_file_element('upload_embedded',$counter,
                   11396:                                                      $embed_file,\%mapping,
                   11397:                                                      $allfiles,$codebase,'modify').
                   11398:                               '</div></td>'.
                   11399:                               &end_data_table_row()."\n";
                   11400:             $counter ++;
                   11401:         } else {
                   11402:             $upload_output .= &start_data_table_row().
1.1123    raeburn  11403:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11404:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11405:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11406:                               &Apache::loncommon::end_data_table_row()."\n";
                   11407:         }
                   11408:     }
                   11409:     my $delidx = $counter;
                   11410:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11411:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11412:         $delete_output .= &start_data_table_row().
                   11413:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11414:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11415:                           '<td>'.$size.'</td>'.
                   11416:                           '<td>'.$mtime.'</td>'.
                   11417:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11418:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11419:                           &embedded_file_element('upload_embedded',$delidx,
                   11420:                                                  $oldfile,\%mapping,$allfiles,
                   11421:                                                  $codebase,'delete').'</td>'.
                   11422:                           &end_data_table_row()."\n"; 
                   11423:         $numunused ++;
                   11424:         $delidx ++;
1.987     raeburn  11425:     }
                   11426:     if ($upload_output) {
                   11427:         $upload_output = &start_data_table().
                   11428:                          $upload_output.
                   11429:                          &end_data_table()."\n";
                   11430:     }
1.1071    raeburn  11431:     if ($modify_output) {
                   11432:         $modify_output = &start_data_table().
                   11433:                          &start_data_table_header_row().
                   11434:                          '<th>'.&mt('File').'</th>'.
                   11435:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11436:                          '<th>'.&mt('Modified').'</th>'.
                   11437:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11438:                          &end_data_table_header_row().
                   11439:                          $modify_output.
                   11440:                          &end_data_table()."\n";
                   11441:     }
                   11442:     if ($delete_output) {
                   11443:         $delete_output = &start_data_table().
                   11444:                          &start_data_table_header_row().
                   11445:                          '<th>'.&mt('File').'</th>'.
                   11446:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11447:                          '<th>'.&mt('Modified').'</th>'.
                   11448:                          '<th>'.&mt('Delete?').'</th>'.
                   11449:                          &end_data_table_header_row().
                   11450:                          $delete_output.
                   11451:                          &end_data_table()."\n";
                   11452:     }
1.987     raeburn  11453:     my $applies = 0;
                   11454:     if ($numremref) {
                   11455:         $applies ++;
                   11456:     }
                   11457:     if ($numinvalid) {
                   11458:         $applies ++;
                   11459:     }
                   11460:     if ($numexisting) {
                   11461:         $applies ++;
                   11462:     }
1.1071    raeburn  11463:     if ($counter || $numunused) {
1.987     raeburn  11464:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11465:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11466:                   $state.'<h3>'.$heading.'</h3>'; 
                   11467:         if ($actionurl eq '/adm/dependencies') {
                   11468:             if ($numnew) {
                   11469:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11470:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11471:                            $upload_output.'<br />'."\n";
                   11472:             }
                   11473:             if ($numexisting) {
                   11474:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11475:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11476:                            $modify_output.'<br />'."\n";
                   11477:                            $buttontext = &mt('Save changes');
                   11478:             }
                   11479:             if ($numunused) {
                   11480:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11481:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11482:                            $delete_output.'<br />'."\n";
                   11483:                            $buttontext = &mt('Save changes');
                   11484:             }
                   11485:         } else {
                   11486:             $output .= $upload_output.'<br />'."\n";
                   11487:         }
                   11488:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11489:                    $counter.'" />'."\n";
                   11490:         if ($actionurl eq '/adm/dependencies') { 
                   11491:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11492:                        $numnew.'" />'."\n";
                   11493:         } elsif ($actionurl eq '') {
1.987     raeburn  11494:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11495:         }
                   11496:     } elsif ($applies) {
                   11497:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11498:         if ($applies > 1) {
                   11499:             $output .=  
1.1123    raeburn  11500:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11501:             if ($numremref) {
                   11502:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11503:             }
                   11504:             if ($numinvalid) {
                   11505:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11506:             }
                   11507:             if ($numexisting) {
                   11508:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11509:             }
                   11510:             $output .= '</ul><br />';
                   11511:         } elsif ($numremref) {
                   11512:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11513:         } elsif ($numinvalid) {
                   11514:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11515:         } elsif ($numexisting) {
                   11516:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11517:         }
                   11518:         $output .= $upload_output.'<br />';
                   11519:     }
                   11520:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11521:     $chgcount = $counter;
1.987     raeburn  11522:     if (keys(%pathchanges) > 0) {
                   11523:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11524:             if ($counter) {
1.987     raeburn  11525:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11526:                                                   $embed_file,\%mapping,
1.1071    raeburn  11527:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11528:             } else {
                   11529:                 $pathchange_output .= 
                   11530:                     &start_data_table_row().
                   11531:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11532:                     $chgcount.'" checked="checked" /></td>'.
                   11533:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11534:                     '<td>'.$embed_file.
                   11535:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11536:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11537:                     '</td>'.&end_data_table_row();
1.660     raeburn  11538:             }
1.987     raeburn  11539:             $numpathchg ++;
                   11540:             $chgcount ++;
1.660     raeburn  11541:         }
                   11542:     }
1.1127    raeburn  11543:     if (($counter) || ($numunused)) {
1.987     raeburn  11544:         if ($numpathchg) {
                   11545:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11546:                        $numpathchg.'" />'."\n";
                   11547:         }
                   11548:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11549:             ($actionurl eq '/adm/imsimport')) {
                   11550:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11551:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11552:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11553:         } elsif ($actionurl eq '/adm/dependencies') {
                   11554:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11555:         }
1.1123    raeburn  11556:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11557:     } elsif ($numpathchg) {
                   11558:         my %pathchange = ();
                   11559:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11560:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11561:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  11562:         }
1.987     raeburn  11563:     }
1.1071    raeburn  11564:     return ($output,$counter,$numpathchg);
1.987     raeburn  11565: }
                   11566: 
1.1147    raeburn  11567: =pod
                   11568: 
                   11569: =item * clean_path($name)
                   11570: 
                   11571: Performs clean-up of directories, subdirectories and filename in an
                   11572: embedded object, referenced in an HTML file which is being uploaded
                   11573: to a course or portfolio, where 
                   11574: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11575: checked.
                   11576: 
                   11577: Clean-up is similar to replacements in lonnet::clean_filename()
                   11578: except each / between sub-directory and next level is preserved.
                   11579: 
                   11580: =cut
                   11581: 
                   11582: sub clean_path {
                   11583:     my ($embed_file) = @_;
                   11584:     $embed_file =~s{^/+}{};
                   11585:     my @contents;
                   11586:     if ($embed_file =~ m{/}) {
                   11587:         @contents = split(/\//,$embed_file);
                   11588:     } else {
                   11589:         @contents = ($embed_file);
                   11590:     }
                   11591:     my $lastidx = scalar(@contents)-1;
                   11592:     for (my $i=0; $i<=$lastidx; $i++) { 
                   11593:         $contents[$i]=~s{\\}{/}g;
                   11594:         $contents[$i]=~s/\s+/\_/g;
                   11595:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11596:         if ($i == $lastidx) {
                   11597:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11598:         }
                   11599:     }
                   11600:     if ($lastidx > 0) {
                   11601:         return join('/',@contents);
                   11602:     } else {
                   11603:         return $contents[0];
                   11604:     }
                   11605: }
                   11606: 
1.987     raeburn  11607: sub embedded_file_element {
1.1071    raeburn  11608:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11609:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11610:                    (ref($codebase) eq 'HASH'));
                   11611:     my $output;
1.1071    raeburn  11612:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11613:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11614:     }
                   11615:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11616:                &escape($embed_file).'" />';
                   11617:     unless (($context eq 'upload_embedded') && 
                   11618:             ($mapping->{$embed_file} eq $embed_file)) {
                   11619:         $output .='
                   11620:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11621:     }
                   11622:     my $attrib;
                   11623:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11624:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11625:     }
                   11626:     $output .=
                   11627:         "\n\t\t".
                   11628:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11629:         $attrib.'" />';
                   11630:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11631:         $output .=
                   11632:             "\n\t\t".
                   11633:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11634:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11635:     }
1.987     raeburn  11636:     return $output;
1.660     raeburn  11637: }
                   11638: 
1.1071    raeburn  11639: sub get_dependency_details {
                   11640:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11641:     my ($size,$mtime,$showsize,$showmtime);
                   11642:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11643:         if ($embed_file =~ m{/}) {
                   11644:             my ($path,$fname) = split(/\//,$embed_file);
                   11645:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11646:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11647:             }
                   11648:         } else {
                   11649:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11650:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11651:             }
                   11652:         }
                   11653:         $showsize = $size/1024.0;
                   11654:         $showsize = sprintf("%.1f",$showsize);
                   11655:         if ($mtime > 0) {
                   11656:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11657:         }
                   11658:     }
                   11659:     return ($showsize,$showmtime);
                   11660: }
                   11661: 
                   11662: sub ask_embedded_js {
                   11663:     return <<"END";
                   11664: <script type="text/javascript"">
                   11665: // <![CDATA[
                   11666: function toggleBrowse(counter) {
                   11667:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11668:     var fileid = document.getElementById('embedded_item_'+counter);
                   11669:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11670:     if (chkboxid.checked == true) {
                   11671:         uploaddivid.style.display='block';
                   11672:     } else {
                   11673:         uploaddivid.style.display='none';
                   11674:         fileid.value = '';
                   11675:     }
                   11676: }
                   11677: // ]]>
                   11678: </script>
                   11679: 
                   11680: END
                   11681: }
                   11682: 
1.661     raeburn  11683: sub upload_embedded {
                   11684:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11685:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11686:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11687:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11688:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11689:         my $orig_uploaded_filename =
                   11690:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11691:         foreach my $type ('orig','ref','attrib','codebase') {
                   11692:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11693:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11694:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11695:             }
                   11696:         }
1.661     raeburn  11697:         my ($path,$fname) =
                   11698:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11699:         # no path, whole string is fname
                   11700:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11701:         $fname = &Apache::lonnet::clean_filename($fname);
                   11702:         # See if there is anything left
                   11703:         next if ($fname eq '');
                   11704: 
                   11705:         # Check if file already exists as a file or directory.
                   11706:         my ($state,$msg);
                   11707:         if ($context eq 'portfolio') {
                   11708:             my $port_path = $dirpath;
                   11709:             if ($group ne '') {
                   11710:                 $port_path = "groups/$group/$port_path";
                   11711:             }
1.987     raeburn  11712:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11713:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11714:                                               $dir_root,$port_path,$disk_quota,
                   11715:                                               $current_disk_usage,$uname,$udom);
                   11716:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11717:                 || $state eq 'file_locked') {
1.661     raeburn  11718:                 $output .= $msg;
                   11719:                 next;
                   11720:             }
                   11721:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11722:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11723:             if ($state eq 'exists') {
                   11724:                 $output .= $msg;
                   11725:                 next;
                   11726:             }
                   11727:         }
                   11728:         # Check if extension is valid
                   11729:         if (($fname =~ /\.(\w+)$/) &&
                   11730:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   11731:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11732:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11733:             next;
                   11734:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11735:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11736:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11737:             next;
                   11738:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   11739:             $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  11740:             next;
                   11741:         }
                   11742:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  11743:         my $subdir = $path;
                   11744:         $subdir =~ s{/+$}{};
1.661     raeburn  11745:         if ($context eq 'portfolio') {
1.984     raeburn  11746:             my $result;
                   11747:             if ($state eq 'existingfile') {
                   11748:                 $result=
                   11749:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  11750:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11751:             } else {
1.984     raeburn  11752:                 $result=
                   11753:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11754:                                                     $dirpath.
1.1123    raeburn  11755:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11756:                 if ($result !~ m|^/uploaded/|) {
                   11757:                     $output .= '<span class="LC_error">'
                   11758:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11759:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11760:                                .'</span><br />';
                   11761:                     next;
                   11762:                 } else {
1.987     raeburn  11763:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11764:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11765:                 }
1.661     raeburn  11766:             }
1.1123    raeburn  11767:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  11768:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11769:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11770:             my $result =
1.1126    raeburn  11771:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11772:             if ($result !~ m|^/uploaded/|) {
                   11773:                 $output .= '<span class="LC_error">'
                   11774:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11775:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11776:                            .'</span><br />';
                   11777:                     next;
                   11778:             } else {
                   11779:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11780:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  11781:                 if ($context eq 'syllabus') {
                   11782:                     &Apache::lonnet::make_public_indefinitely($result);
                   11783:                 }
1.987     raeburn  11784:             }
1.661     raeburn  11785:         } else {
                   11786: # Save the file
                   11787:             my $target = $env{'form.embedded_item_'.$i};
                   11788:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11789:             my $dest = $fullpath.$fname;
                   11790:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11791:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11792:             my $count;
                   11793:             my $filepath = $dir_root;
1.1027    raeburn  11794:             foreach my $subdir (@parts) {
                   11795:                 $filepath .= "/$subdir";
                   11796:                 if (!-e $filepath) {
1.661     raeburn  11797:                     mkdir($filepath,0770);
                   11798:                 }
                   11799:             }
                   11800:             my $fh;
                   11801:             if (!open($fh,'>'.$dest)) {
                   11802:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11803:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11804:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11805:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11806:                            '</span><br />';
                   11807:             } else {
                   11808:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11809:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11810:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11811:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11812:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11813:                               '</span><br />';
                   11814:                 } else {
1.987     raeburn  11815:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11816:                                $url.'</span>').'<br />';
                   11817:                     unless ($context eq 'testbank') {
                   11818:                         $footer .= &mt('View embedded file: [_1]',
                   11819:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11820:                     }
                   11821:                 }
                   11822:                 close($fh);
                   11823:             }
                   11824:         }
                   11825:         if ($env{'form.embedded_ref_'.$i}) {
                   11826:             $pathchange{$i} = 1;
                   11827:         }
                   11828:     }
                   11829:     if ($output) {
                   11830:         $output = '<p>'.$output.'</p>';
                   11831:     }
                   11832:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11833:     $returnflag = 'ok';
1.1071    raeburn  11834:     my $numpathchgs = scalar(keys(%pathchange));
                   11835:     if ($numpathchgs > 0) {
1.987     raeburn  11836:         if ($context eq 'portfolio') {
                   11837:             $output .= '<p>'.&mt('or').'</p>';
                   11838:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11839:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11840:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11841:             $returnflag = 'modify_orightml';
                   11842:         }
                   11843:     }
1.1071    raeburn  11844:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11845: }
                   11846: 
                   11847: sub modify_html_form {
                   11848:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11849:     my $end = 0;
                   11850:     my $modifyform;
                   11851:     if ($context eq 'upload_embedded') {
                   11852:         return unless (ref($pathchange) eq 'HASH');
                   11853:         if ($env{'form.number_embedded_items'}) {
                   11854:             $end += $env{'form.number_embedded_items'};
                   11855:         }
                   11856:         if ($env{'form.number_pathchange_items'}) {
                   11857:             $end += $env{'form.number_pathchange_items'};
                   11858:         }
                   11859:         if ($end) {
                   11860:             for (my $i=0; $i<$end; $i++) {
                   11861:                 if ($i < $env{'form.number_embedded_items'}) {
                   11862:                     next unless($pathchange->{$i});
                   11863:                 }
                   11864:                 $modifyform .=
                   11865:                     &start_data_table_row().
                   11866:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11867:                     'checked="checked" /></td>'.
                   11868:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11869:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11870:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11871:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11872:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11873:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11874:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11875:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11876:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11877:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11878:                     &end_data_table_row();
1.1071    raeburn  11879:             }
1.987     raeburn  11880:         }
                   11881:     } else {
                   11882:         $modifyform = $pathchgtable;
                   11883:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11884:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11885:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11886:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11887:         }
                   11888:     }
                   11889:     if ($modifyform) {
1.1071    raeburn  11890:         if ($actionurl eq '/adm/dependencies') {
                   11891:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11892:         }
1.987     raeburn  11893:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11894:                '<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".
                   11895:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11896:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11897:                '</ol></p>'."\n".'<p>'.
                   11898:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11899:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11900:                &start_data_table()."\n".
                   11901:                &start_data_table_header_row().
                   11902:                '<th>'.&mt('Change?').'</th>'.
                   11903:                '<th>'.&mt('Current reference').'</th>'.
                   11904:                '<th>'.&mt('Required reference').'</th>'.
                   11905:                &end_data_table_header_row()."\n".
                   11906:                $modifyform.
                   11907:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11908:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11909:                '</form>'."\n";
                   11910:     }
                   11911:     return;
                   11912: }
                   11913: 
                   11914: sub modify_html_refs {
1.1123    raeburn  11915:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11916:     my $container;
                   11917:     if ($context eq 'portfolio') {
                   11918:         $container = $env{'form.container'};
                   11919:     } elsif ($context eq 'coursedoc') {
                   11920:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11921:     } elsif ($context eq 'manage_dependencies') {
                   11922:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11923:         $container = "/$container";
1.1123    raeburn  11924:     } elsif ($context eq 'syllabus') {
                   11925:         $container = $url;
1.987     raeburn  11926:     } else {
1.1027    raeburn  11927:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11928:     }
                   11929:     my (%allfiles,%codebase,$output,$content);
                   11930:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  11931:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  11932:         if (wantarray) {
                   11933:             return ('',0,0); 
                   11934:         } else {
                   11935:             return;
                   11936:         }
                   11937:     }
                   11938:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11939:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11940:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11941:             if (wantarray) {
                   11942:                 return ('',0,0);
                   11943:             } else {
                   11944:                 return;
                   11945:             }
                   11946:         } 
1.987     raeburn  11947:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11948:         if ($content eq '-1') {
                   11949:             if (wantarray) {
                   11950:                 return ('',0,0);
                   11951:             } else {
                   11952:                 return;
                   11953:             }
                   11954:         }
1.987     raeburn  11955:     } else {
1.1071    raeburn  11956:         unless ($container =~ /^\Q$dir_root\E/) {
                   11957:             if (wantarray) {
                   11958:                 return ('',0,0);
                   11959:             } else {
                   11960:                 return;
                   11961:             }
                   11962:         } 
1.987     raeburn  11963:         if (open(my $fh,"<$container")) {
                   11964:             $content = join('', <$fh>);
                   11965:             close($fh);
                   11966:         } else {
1.1071    raeburn  11967:             if (wantarray) {
                   11968:                 return ('',0,0);
                   11969:             } else {
                   11970:                 return;
                   11971:             }
1.987     raeburn  11972:         }
                   11973:     }
                   11974:     my ($count,$codebasecount) = (0,0);
                   11975:     my $mm = new File::MMagic;
                   11976:     my $mime_type = $mm->checktype_contents($content);
                   11977:     if ($mime_type eq 'text/html') {
                   11978:         my $parse_result = 
                   11979:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11980:                                                     \%codebase,\$content);
                   11981:         if ($parse_result eq 'ok') {
                   11982:             foreach my $i (@changes) {
                   11983:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11984:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11985:                 if ($allfiles{$ref}) {
                   11986:                     my $newname =  $orig;
                   11987:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11988:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11989:                     if ($attrib_regexp =~ /:/) {
                   11990:                         $attrib_regexp =~ s/\:/|/g;
                   11991:                     }
                   11992:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11993:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11994:                         $count += $numchg;
1.1123    raeburn  11995:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  11996:                         delete($allfiles{$ref});
1.987     raeburn  11997:                     }
                   11998:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11999:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12000:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12001:                         $codebasecount ++;
                   12002:                     }
                   12003:                 }
                   12004:             }
1.1123    raeburn  12005:             my $skiprewrites;
1.987     raeburn  12006:             if ($count || $codebasecount) {
                   12007:                 my $saveresult;
1.1071    raeburn  12008:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12009:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12010:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12011:                     if ($url eq $container) {
                   12012:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12013:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12014:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12015:                                             $fname.'</span>').'</p>';
1.987     raeburn  12016:                     } else {
                   12017:                          $output = '<p class="LC_error">'.
                   12018:                                    &mt('Error: update failed for: [_1].',
                   12019:                                    '<span class="LC_filename">'.
                   12020:                                    $container.'</span>').'</p>';
                   12021:                     }
1.1123    raeburn  12022:                     if ($context eq 'syllabus') {
                   12023:                         unless ($saveresult eq 'ok') {
                   12024:                             $skiprewrites = 1;
                   12025:                         }
                   12026:                     }
1.987     raeburn  12027:                 } else {
                   12028:                     if (open(my $fh,">$container")) {
                   12029:                         print $fh $content;
                   12030:                         close($fh);
                   12031:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12032:                                   $count,'<span class="LC_filename">'.
                   12033:                                   $container.'</span>').'</p>';
1.661     raeburn  12034:                     } else {
1.987     raeburn  12035:                          $output = '<p class="LC_error">'.
                   12036:                                    &mt('Error: could not update [_1].',
                   12037:                                    '<span class="LC_filename">'.
                   12038:                                    $container.'</span>').'</p>';
1.661     raeburn  12039:                     }
                   12040:                 }
                   12041:             }
1.1123    raeburn  12042:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12043:                 my ($actionurl,$state);
                   12044:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12045:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12046:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12047:                                               \%codebase,
                   12048:                                               {'context' => 'rewrites',
                   12049:                                                'ignore_remote_references' => 1,});
                   12050:                 if (ref($mapping) eq 'HASH') {
                   12051:                     my $rewrites = 0;
                   12052:                     foreach my $key (keys(%{$mapping})) {
                   12053:                         next if ($key =~ m{^https?://});
                   12054:                         my $ref = $mapping->{$key};
                   12055:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12056:                         my $attrib;
                   12057:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12058:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12059:                         }
                   12060:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12061:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12062:                             $rewrites += $numchg;
                   12063:                         }
                   12064:                     }
                   12065:                     if ($rewrites) {
                   12066:                         my $saveresult; 
                   12067:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12068:                         if ($url eq $container) {
                   12069:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12070:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12071:                                             $count,'<span class="LC_filename">'.
                   12072:                                             $fname.'</span>').'</p>';
                   12073:                         } else {
                   12074:                             $output .= '<p class="LC_error">'.
                   12075:                                        &mt('Error: could not update links in [_1].',
                   12076:                                        '<span class="LC_filename">'.
                   12077:                                        $container.'</span>').'</p>';
                   12078: 
                   12079:                         }
                   12080:                     }
                   12081:                 }
                   12082:             }
1.987     raeburn  12083:         } else {
                   12084:             &logthis('Failed to parse '.$container.
                   12085:                      ' to modify references: '.$parse_result);
1.661     raeburn  12086:         }
                   12087:     }
1.1071    raeburn  12088:     if (wantarray) {
                   12089:         return ($output,$count,$codebasecount);
                   12090:     } else {
                   12091:         return $output;
                   12092:     }
1.661     raeburn  12093: }
                   12094: 
                   12095: sub check_for_existing {
                   12096:     my ($path,$fname,$element) = @_;
                   12097:     my ($state,$msg);
                   12098:     if (-d $path.'/'.$fname) {
                   12099:         $state = 'exists';
                   12100:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12101:     } elsif (-e $path.'/'.$fname) {
                   12102:         $state = 'exists';
                   12103:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12104:     }
                   12105:     if ($state eq 'exists') {
                   12106:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12107:     }
                   12108:     return ($state,$msg);
                   12109: }
                   12110: 
                   12111: sub check_for_upload {
                   12112:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12113:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12114:     my $filesize = length($env{'form.'.$element});
                   12115:     if (!$filesize) {
                   12116:         my $msg = '<span class="LC_error">'.
                   12117:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12118:                       '<span class="LC_filename">'.$fname.'</span>',
                   12119:                       $filesize).'<br />'.
1.1007    raeburn  12120:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12121:                   '</span>';
                   12122:         return ('zero_bytes',$msg);
                   12123:     }
                   12124:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12125:     my $getpropath = 1;
1.1021    raeburn  12126:     my ($dirlistref,$listerror) =
                   12127:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12128:     my $found_file = 0;
                   12129:     my $locked_file = 0;
1.991     raeburn  12130:     my @lockers;
                   12131:     my $navmap;
                   12132:     if ($env{'request.course.id'}) {
                   12133:         $navmap = Apache::lonnavmaps::navmap->new();
                   12134:     }
1.1021    raeburn  12135:     if (ref($dirlistref) eq 'ARRAY') {
                   12136:         foreach my $line (@{$dirlistref}) {
                   12137:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12138:             if ($file_name eq $fname){
                   12139:                 $file_name = $path.$file_name;
                   12140:                 if ($group ne '') {
                   12141:                     $file_name = $group.$file_name;
                   12142:                 }
                   12143:                 $found_file = 1;
                   12144:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12145:                     foreach my $lock (@lockers) {
                   12146:                         if (ref($lock) eq 'ARRAY') {
                   12147:                             my ($symb,$crsid) = @{$lock};
                   12148:                             if ($crsid eq $env{'request.course.id'}) {
                   12149:                                 if (ref($navmap)) {
                   12150:                                     my $res = $navmap->getBySymb($symb);
                   12151:                                     foreach my $part (@{$res->parts()}) { 
                   12152:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12153:                                         unless (($slot_status == $res->RESERVED) ||
                   12154:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12155:                                             $locked_file = 1;
                   12156:                                         }
1.991     raeburn  12157:                                     }
1.1021    raeburn  12158:                                 } else {
                   12159:                                     $locked_file = 1;
1.991     raeburn  12160:                                 }
                   12161:                             } else {
                   12162:                                 $locked_file = 1;
                   12163:                             }
                   12164:                         }
1.1021    raeburn  12165:                    }
                   12166:                 } else {
                   12167:                     my @info = split(/\&/,$rest);
                   12168:                     my $currsize = $info[6]/1000;
                   12169:                     if ($currsize < $filesize) {
                   12170:                         my $extra = $filesize - $currsize;
                   12171:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   12172:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12173:                                       &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded if existing (smaller) file with same name (size = [_3] kilobytes) is replaced.',
1.1179    bisitz   12174:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12175:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12176:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12177:                             return ('will_exceed_quota',$msg);
                   12178:                         }
1.984     raeburn  12179:                     }
                   12180:                 }
1.661     raeburn  12181:             }
                   12182:         }
                   12183:     }
                   12184:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   12185:         my $msg = '<p class="LC_warning">'.
                   12186:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  12187:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12188:         return ('will_exceed_quota',$msg);
                   12189:     } elsif ($found_file) {
                   12190:         if ($locked_file) {
1.1179    bisitz   12191:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12192:             $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
1.1179    bisitz   12193:             $msg .= '</p>';
1.661     raeburn  12194:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12195:             return ('file_locked',$msg);
                   12196:         } else {
1.1179    bisitz   12197:             my $msg = '<p class="LC_error">';
1.984     raeburn  12198:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1179    bisitz   12199:             $msg .= '</p>';
1.984     raeburn  12200:             return ('existingfile',$msg);
1.661     raeburn  12201:         }
                   12202:     }
                   12203: }
                   12204: 
1.987     raeburn  12205: sub check_for_traversal {
                   12206:     my ($path,$url,$toplevel) = @_;
                   12207:     my @parts=split(/\//,$path);
                   12208:     my $cleanpath;
                   12209:     my $fullpath = $url;
                   12210:     for (my $i=0;$i<@parts;$i++) {
                   12211:         next if ($parts[$i] eq '.');
                   12212:         if ($parts[$i] eq '..') {
                   12213:             $fullpath =~ s{([^/]+/)$}{};
                   12214:         } else {
                   12215:             $fullpath .= $parts[$i].'/';
                   12216:         }
                   12217:     }
                   12218:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12219:         $cleanpath = $1;
                   12220:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12221:         my $curr_toprel = $1;
                   12222:         my @parts = split(/\//,$curr_toprel);
                   12223:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12224:         my @urlparts = split(/\//,$url_toprel);
                   12225:         my $doubledots;
                   12226:         my $startdiff = -1;
                   12227:         for (my $i=0; $i<@urlparts; $i++) {
                   12228:             if ($startdiff == -1) {
                   12229:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12230:                     $startdiff = $i;
                   12231:                     $doubledots .= '../';
                   12232:                 }
                   12233:             } else {
                   12234:                 $doubledots .= '../';
                   12235:             }
                   12236:         }
                   12237:         if ($startdiff > -1) {
                   12238:             $cleanpath = $doubledots;
                   12239:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12240:                 $cleanpath .= $parts[$i].'/';
                   12241:             }
                   12242:         }
                   12243:     }
                   12244:     $cleanpath =~ s{(/)$}{};
                   12245:     return $cleanpath;
                   12246: }
1.31      albertel 12247: 
1.1053    raeburn  12248: sub is_archive_file {
                   12249:     my ($mimetype) = @_;
                   12250:     if (($mimetype eq 'application/octet-stream') ||
                   12251:         ($mimetype eq 'application/x-stuffit') ||
                   12252:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12253:         return 1;
                   12254:     }
                   12255:     return;
                   12256: }
                   12257: 
                   12258: sub decompress_form {
1.1065    raeburn  12259:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12260:     my %lt = &Apache::lonlocal::texthash (
                   12261:         this => 'This file is an archive file.',
1.1067    raeburn  12262:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12263:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12264:         youm => 'You may wish to extract its contents.',
                   12265:         extr => 'Extract contents',
1.1067    raeburn  12266:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12267:         proa => 'Process automatically?',
1.1053    raeburn  12268:         yes  => 'Yes',
                   12269:         no   => 'No',
1.1067    raeburn  12270:         fold => 'Title for folder containing movie',
                   12271:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12272:     );
1.1065    raeburn  12273:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12274:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12275:     my $info = &list_archive_contents($fileloc,\@paths);
                   12276:     if (@paths) {
                   12277:         foreach my $path (@paths) {
                   12278:             $path =~ s{^/}{};
1.1067    raeburn  12279:             if ($path =~ m{^([^/]+)/$}) {
                   12280:                 $topdir = $1;
                   12281:             }
1.1065    raeburn  12282:             if ($path =~ m{^([^/]+)/}) {
                   12283:                 $toplevel{$1} = $path;
                   12284:             } else {
                   12285:                 $toplevel{$path} = $path;
                   12286:             }
                   12287:         }
                   12288:     }
1.1067    raeburn  12289:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  12290:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12291:                         "$topdir/media/",
                   12292:                         "$topdir/media/$topdir.mp4",
                   12293:                         "$topdir/media/FirstFrame.png",
                   12294:                         "$topdir/media/player.swf",
                   12295:                         "$topdir/media/swfobject.js",
                   12296:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  12297:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  12298:                          "$topdir/$topdir.mp4",
                   12299:                          "$topdir/$topdir\_config.xml",
                   12300:                          "$topdir/$topdir\_controller.swf",
                   12301:                          "$topdir/$topdir\_embed.css",
                   12302:                          "$topdir/$topdir\_First_Frame.png",
                   12303:                          "$topdir/$topdir\_player.html",
                   12304:                          "$topdir/$topdir\_Thumbnails.png",
                   12305:                          "$topdir/playerProductInstall.swf",
                   12306:                          "$topdir/scripts/",
                   12307:                          "$topdir/scripts/config_xml.js",
                   12308:                          "$topdir/scripts/handlebars.js",
                   12309:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12310:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12311:                          "$topdir/scripts/modernizr.js",
                   12312:                          "$topdir/scripts/player-min.js",
                   12313:                          "$topdir/scripts/swfobject.js",
                   12314:                          "$topdir/skins/",
                   12315:                          "$topdir/skins/configuration_express.xml",
                   12316:                          "$topdir/skins/express_show/",
                   12317:                          "$topdir/skins/express_show/player-min.css",
                   12318:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  12319:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12320:                          "$topdir/$topdir.mp4",
                   12321:                          "$topdir/$topdir\_config.xml",
                   12322:                          "$topdir/$topdir\_controller.swf",
                   12323:                          "$topdir/$topdir\_embed.css",
                   12324:                          "$topdir/$topdir\_First_Frame.png",
                   12325:                          "$topdir/$topdir\_player.html",
                   12326:                          "$topdir/$topdir\_Thumbnails.png",
                   12327:                          "$topdir/playerProductInstall.swf",
                   12328:                          "$topdir/scripts/",
                   12329:                          "$topdir/scripts/config_xml.js",
                   12330:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12331:                          "$topdir/skins/",
                   12332:                          "$topdir/skins/configuration_express.xml",
                   12333:                          "$topdir/skins/express_show/",
                   12334:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12335:                          "$topdir/skins/express_show/spritesheet.png",
                   12336:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  12337:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12338:         if (@diffs == 0) {
1.1164    raeburn  12339:             $is_camtasia = 6;
                   12340:         } else {
1.1197    raeburn  12341:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  12342:             if (@diffs == 0) {
                   12343:                 $is_camtasia = 8;
1.1197    raeburn  12344:             } else {
                   12345:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12346:                 if (@diffs == 0) {
                   12347:                     $is_camtasia = 8;
                   12348:                 }
1.1164    raeburn  12349:             }
1.1067    raeburn  12350:         }
                   12351:     }
                   12352:     my $output;
                   12353:     if ($is_camtasia) {
                   12354:         $output = <<"ENDCAM";
                   12355: <script type="text/javascript" language="Javascript">
                   12356: // <![CDATA[
                   12357: 
                   12358: function camtasiaToggle() {
                   12359:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12360:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  12361:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12362:                 document.getElementById('camtasia_titles').style.display='block';
                   12363:             } else {
                   12364:                 document.getElementById('camtasia_titles').style.display='none';
                   12365:             }
                   12366:         }
                   12367:     }
                   12368:     return;
                   12369: }
                   12370: 
                   12371: // ]]>
                   12372: </script>
                   12373: <p>$lt{'camt'}</p>
                   12374: ENDCAM
1.1065    raeburn  12375:     } else {
1.1067    raeburn  12376:         $output = '<p>'.$lt{'this'};
                   12377:         if ($info eq '') {
                   12378:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12379:         } else {
                   12380:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12381:                        '<div><pre>'.$info.'</pre></div>';
                   12382:         }
1.1065    raeburn  12383:     }
1.1067    raeburn  12384:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12385:     my $duplicates;
                   12386:     my $num = 0;
                   12387:     if (ref($dirlist) eq 'ARRAY') {
                   12388:         foreach my $item (@{$dirlist}) {
                   12389:             if (ref($item) eq 'ARRAY') {
                   12390:                 if (exists($toplevel{$item->[0]})) {
                   12391:                     $duplicates .= 
                   12392:                         &start_data_table_row().
                   12393:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12394:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12395:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12396:                         'value="1" />'.&mt('Yes').'</label>'.
                   12397:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12398:                         '<td>'.$item->[0].'</td>';
                   12399:                     if ($item->[2]) {
                   12400:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12401:                     } else {
                   12402:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12403:                     }
                   12404:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12405:                                    '<td>'.
                   12406:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12407:                                    '</td>'.
                   12408:                                    &end_data_table_row();
                   12409:                     $num ++;
                   12410:                 }
                   12411:             }
                   12412:         }
                   12413:     }
                   12414:     my $itemcount;
                   12415:     if (@paths > 0) {
                   12416:         $itemcount = scalar(@paths);
                   12417:     } else {
                   12418:         $itemcount = 1;
                   12419:     }
1.1067    raeburn  12420:     if ($is_camtasia) {
                   12421:         $output .= $lt{'auto'}.'<br />'.
                   12422:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  12423:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12424:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12425:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12426:                    $lt{'no'}.'</label></span><br />'.
                   12427:                    '<div id="camtasia_titles" style="display:block">'.
                   12428:                    &Apache::lonhtmlcommon::start_pick_box().
                   12429:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12430:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12431:                    &Apache::lonhtmlcommon::row_closure().
                   12432:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12433:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12434:                    &Apache::lonhtmlcommon::row_closure(1).
                   12435:                    &Apache::lonhtmlcommon::end_pick_box().
                   12436:                    '</div>';
                   12437:     }
1.1065    raeburn  12438:     $output .= 
                   12439:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12440:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12441:         "\n";
1.1065    raeburn  12442:     if ($duplicates ne '') {
                   12443:         $output .= '<p><span class="LC_warning">'.
                   12444:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12445:                    &start_data_table().
                   12446:                    &start_data_table_header_row().
                   12447:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12448:                    '<th>'.&mt('Name').'</th>'.
                   12449:                    '<th>'.&mt('Type').'</th>'.
                   12450:                    '<th>'.&mt('Size').'</th>'.
                   12451:                    '<th>'.&mt('Last modified').'</th>'.
                   12452:                    &end_data_table_header_row().
                   12453:                    $duplicates.
                   12454:                    &end_data_table().
                   12455:                    '</p>';
                   12456:     }
1.1067    raeburn  12457:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12458:     if (ref($hiddenelements) eq 'HASH') {
                   12459:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12460:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12461:         }
                   12462:     }
                   12463:     $output .= <<"END";
1.1067    raeburn  12464: <br />
1.1053    raeburn  12465: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12466: </form>
                   12467: $noextract
                   12468: END
                   12469:     return $output;
                   12470: }
                   12471: 
1.1065    raeburn  12472: sub decompression_utility {
                   12473:     my ($program) = @_;
                   12474:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12475:     my $location;
                   12476:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12477:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12478:                          '/usr/sbin/') {
                   12479:             if (-x $dir.$program) {
                   12480:                 $location = $dir.$program;
                   12481:                 last;
                   12482:             }
                   12483:         }
                   12484:     }
                   12485:     return $location;
                   12486: }
                   12487: 
                   12488: sub list_archive_contents {
                   12489:     my ($file,$pathsref) = @_;
                   12490:     my (@cmd,$output);
                   12491:     my $needsregexp;
                   12492:     if ($file =~ /\.zip$/) {
                   12493:         @cmd = (&decompression_utility('unzip'),"-l");
                   12494:         $needsregexp = 1;
                   12495:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12496:              ($file =~ /\.tgz$/)) {
                   12497:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12498:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12499:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12500:     } elsif ($file =~ m|\.tar$|) {
                   12501:         @cmd = (&decompression_utility('tar'),"-tf");
                   12502:     }
                   12503:     if (@cmd) {
                   12504:         undef($!);
                   12505:         undef($@);
                   12506:         if (open(my $fh,"-|", @cmd, $file)) {
                   12507:             while (my $line = <$fh>) {
                   12508:                 $output .= $line;
                   12509:                 chomp($line);
                   12510:                 my $item;
                   12511:                 if ($needsregexp) {
                   12512:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12513:                 } else {
                   12514:                     $item = $line;
                   12515:                 }
                   12516:                 if ($item ne '') {
                   12517:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12518:                         push(@{$pathsref},$item);
                   12519:                     } 
                   12520:                 }
                   12521:             }
                   12522:             close($fh);
                   12523:         }
                   12524:     }
                   12525:     return $output;
                   12526: }
                   12527: 
1.1053    raeburn  12528: sub decompress_uploaded_file {
                   12529:     my ($file,$dir) = @_;
                   12530:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12531:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12532:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12533:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12534:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12535:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12536:     my $decompressed = $env{'cgi.decompressed'};
                   12537:     &Apache::lonnet::delenv('cgi.file');
                   12538:     &Apache::lonnet::delenv('cgi.dir');
                   12539:     &Apache::lonnet::delenv('cgi.decompressed');
                   12540:     return ($decompressed,$result);
                   12541: }
                   12542: 
1.1055    raeburn  12543: sub process_decompression {
                   12544:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   12545:     my ($dir,$error,$warning,$output);
1.1180    raeburn  12546:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   12547:         $error = &mt('Filename not a supported archive file type.').
                   12548:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12549:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12550:     } else {
                   12551:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12552:         if ($docuhome eq 'no_host') {
                   12553:             $error = &mt('Could not determine home server for course.');
                   12554:         } else {
                   12555:             my @ids=&Apache::lonnet::current_machine_ids();
                   12556:             my $currdir = "$dir_root/$destination";
                   12557:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12558:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12559:                        "$dir_root/$destination";
                   12560:             } else {
                   12561:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12562:                        "$dir_root/$docudom/$docuname/$destination";
                   12563:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12564:                     $error = &mt('Archive file not found.');
                   12565:                 }
                   12566:             }
1.1065    raeburn  12567:             my (@to_overwrite,@to_skip);
                   12568:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12569:                 my $total = $env{'form.archive_overwrite_total'};
                   12570:                 for (my $i=0; $i<$total; $i++) {
                   12571:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12572:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12573:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12574:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12575:                     }
                   12576:                 }
                   12577:             }
                   12578:             my $numskip = scalar(@to_skip);
                   12579:             if (($numskip > 0) && 
                   12580:                 ($numskip == $env{'form.archive_itemcount'})) {
                   12581:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12582:             } elsif ($dir eq '') {
1.1055    raeburn  12583:                 $error = &mt('Directory containing archive file unavailable.');
                   12584:             } elsif (!$error) {
1.1065    raeburn  12585:                 my ($decompressed,$display);
                   12586:                 if ($numskip > 0) {
                   12587:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12588:                     mkdir("$dir/$tempdir",0755);
                   12589:                     system("mv $dir/$file $dir/$tempdir/$file");
                   12590:                     ($decompressed,$display) = 
                   12591:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   12592:                     foreach my $item (@to_skip) {
                   12593:                         if (($item ne '') && ($item !~ /\.\./)) {
                   12594:                             if (-f "$dir/$tempdir/$item") { 
                   12595:                                 unlink("$dir/$tempdir/$item");
                   12596:                             } elsif (-d "$dir/$tempdir/$item") {
                   12597:                                 system("rm -rf $dir/$tempdir/$item");
                   12598:                             }
                   12599:                         }
                   12600:                     }
                   12601:                     system("mv $dir/$tempdir/* $dir");
                   12602:                     rmdir("$dir/$tempdir");   
                   12603:                 } else {
                   12604:                     ($decompressed,$display) = 
                   12605:                         &decompress_uploaded_file($file,$dir);
                   12606:                 }
1.1055    raeburn  12607:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12608:                     $output = '<p class="LC_info">'.
                   12609:                               &mt('Files extracted successfully from archive.').
                   12610:                               '</p>'."\n";
1.1055    raeburn  12611:                     my ($warning,$result,@contents);
                   12612:                     my ($newdirlistref,$newlisterror) =
                   12613:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12614:                                                  $docuname,1);
                   12615:                     my (%is_dir,%changes,@newitems);
                   12616:                     my $dirptr = 16384;
1.1065    raeburn  12617:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12618:                         foreach my $dir_line (@{$newdirlistref}) {
                   12619:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  12620:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   12621:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  12622:                                 push(@newitems,$item);
                   12623:                                 if ($dirptr&$testdir) {
                   12624:                                     $is_dir{$item} = 1;
                   12625:                                 }
                   12626:                                 $changes{$item} = 1;
                   12627:                             }
                   12628:                         }
                   12629:                     }
                   12630:                     if (keys(%changes) > 0) {
                   12631:                         foreach my $item (sort(@newitems)) {
                   12632:                             if ($changes{$item}) {
                   12633:                                 push(@contents,$item);
                   12634:                             }
                   12635:                         }
                   12636:                     }
                   12637:                     if (@contents > 0) {
1.1067    raeburn  12638:                         my $wantform;
                   12639:                         unless ($env{'form.autoextract_camtasia'}) {
                   12640:                             $wantform = 1;
                   12641:                         }
1.1056    raeburn  12642:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12643:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12644:                                                                 $currdir,\%is_dir,
                   12645:                                                                 \%children,\%parent,
1.1056    raeburn  12646:                                                                 \@contents,\%dirorder,
                   12647:                                                                 \%titles,$wantform);
1.1055    raeburn  12648:                         if ($datatable ne '') {
                   12649:                             $output .= &archive_options_form('decompressed',$datatable,
                   12650:                                                              $count,$hiddenelem);
1.1065    raeburn  12651:                             my $startcount = 6;
1.1055    raeburn  12652:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12653:                                                            \%titles,\%children);
1.1055    raeburn  12654:                         }
1.1067    raeburn  12655:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  12656:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12657:                             my %displayed;
                   12658:                             my $total = 1;
                   12659:                             $env{'form.archive_directory'} = [];
                   12660:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12661:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12662:                                 $path =~ s{/$}{};
                   12663:                                 my $item;
                   12664:                                 if ($path ne '') {
                   12665:                                     $item = "$path/$titles{$i}";
                   12666:                                 } else {
                   12667:                                     $item = $titles{$i};
                   12668:                                 }
                   12669:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12670:                                 if ($item eq $contents[0]) {
                   12671:                                     push(@{$env{'form.archive_directory'}},$i);
                   12672:                                     $env{'form.archive_'.$i} = 'display';
                   12673:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12674:                                     $displayed{'folder'} = $i;
1.1164    raeburn  12675:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12676:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  12677:                                     $env{'form.archive_'.$i} = 'display';
                   12678:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12679:                                     $displayed{'web'} = $i;
                   12680:                                 } else {
1.1164    raeburn  12681:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12682:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12683:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12684:                                         push(@{$env{'form.archive_directory'}},$i);
                   12685:                                     }
                   12686:                                     $env{'form.archive_'.$i} = 'dependency';
                   12687:                                 }
                   12688:                                 $total ++;
                   12689:                             }
                   12690:                             for (my $i=1; $i<$total; $i++) {
                   12691:                                 next if ($i == $displayed{'web'});
                   12692:                                 next if ($i == $displayed{'folder'});
                   12693:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12694:                             }
                   12695:                             $env{'form.phase'} = 'decompress_cleanup';
                   12696:                             $env{'form.archivedelete'} = 1;
                   12697:                             $env{'form.archive_count'} = $total-1;
                   12698:                             $output .=
                   12699:                                 &process_extracted_files('coursedocs',$docudom,
                   12700:                                                          $docuname,$destination,
                   12701:                                                          $dir_root,$hiddenelem);
                   12702:                         }
1.1055    raeburn  12703:                     } else {
                   12704:                         $warning = &mt('No new items extracted from archive file.');
                   12705:                     }
                   12706:                 } else {
                   12707:                     $output = $display;
                   12708:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12709:                 }
                   12710:             }
                   12711:         }
                   12712:     }
                   12713:     if ($error) {
                   12714:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12715:                    $error.'</p>'."\n";
                   12716:     }
                   12717:     if ($warning) {
                   12718:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12719:     }
                   12720:     return $output;
                   12721: }
                   12722: 
                   12723: sub get_extracted {
1.1056    raeburn  12724:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12725:         $titles,$wantform) = @_;
1.1055    raeburn  12726:     my $count = 0;
                   12727:     my $depth = 0;
                   12728:     my $datatable;
1.1056    raeburn  12729:     my @hierarchy;
1.1055    raeburn  12730:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12731:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12732:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12733:     foreach my $item (@{$contents}) {
                   12734:         $count ++;
1.1056    raeburn  12735:         @{$dirorder->{$count}} = @hierarchy;
                   12736:         $titles->{$count} = $item;
1.1055    raeburn  12737:         &archive_hierarchy($depth,$count,$parent,$children);
                   12738:         if ($wantform) {
                   12739:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12740:                                        $currdir,$depth,$count);
                   12741:         }
                   12742:         if ($is_dir->{$item}) {
                   12743:             $depth ++;
1.1056    raeburn  12744:             push(@hierarchy,$count);
                   12745:             $parent->{$depth} = $count;
1.1055    raeburn  12746:             $datatable .=
                   12747:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12748:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12749:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12750:             $depth --;
1.1056    raeburn  12751:             pop(@hierarchy);
1.1055    raeburn  12752:         }
                   12753:     }
                   12754:     return ($count,$datatable);
                   12755: }
                   12756: 
                   12757: sub recurse_extracted_archive {
1.1056    raeburn  12758:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12759:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12760:     my $result='';
1.1056    raeburn  12761:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12762:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12763:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12764:         return $result;
                   12765:     }
                   12766:     my $dirptr = 16384;
                   12767:     my ($newdirlistref,$newlisterror) =
                   12768:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12769:     if (ref($newdirlistref) eq 'ARRAY') {
                   12770:         foreach my $dir_line (@{$newdirlistref}) {
                   12771:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12772:             unless ($item =~ /^\.+$/) {
                   12773:                 $$count ++;
1.1056    raeburn  12774:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12775:                 $titles->{$$count} = $item;
1.1055    raeburn  12776:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12777: 
1.1055    raeburn  12778:                 my $is_dir;
                   12779:                 if ($dirptr&$testdir) {
                   12780:                     $is_dir = 1;
                   12781:                 }
                   12782:                 if ($wantform) {
                   12783:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12784:                 }
                   12785:                 if ($is_dir) {
                   12786:                     $$depth ++;
1.1056    raeburn  12787:                     push(@{$hierarchy},$$count);
                   12788:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12789:                     $result .=
                   12790:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12791:                                                    $docuname,$depth,$count,
1.1056    raeburn  12792:                                                    $hierarchy,$dirorder,$children,
                   12793:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12794:                     $$depth --;
1.1056    raeburn  12795:                     pop(@{$hierarchy});
1.1055    raeburn  12796:                 }
                   12797:             }
                   12798:         }
                   12799:     }
                   12800:     return $result;
                   12801: }
                   12802: 
                   12803: sub archive_hierarchy {
                   12804:     my ($depth,$count,$parent,$children) =@_;
                   12805:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12806:         if (exists($parent->{$depth})) {
                   12807:              $children->{$parent->{$depth}} .= $count.':';
                   12808:         }
                   12809:     }
                   12810:     return;
                   12811: }
                   12812: 
                   12813: sub archive_row {
                   12814:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12815:     my ($name) = ($item =~ m{([^/]+)$});
                   12816:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12817:                                        'display'    => 'Add as file',
1.1055    raeburn  12818:                                        'dependency' => 'Include as dependency',
                   12819:                                        'discard'    => 'Discard',
                   12820:                                       );
                   12821:     if ($is_dir) {
1.1059    raeburn  12822:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12823:     }
1.1056    raeburn  12824:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12825:     my $offset = 0;
1.1055    raeburn  12826:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12827:         $offset ++;
1.1065    raeburn  12828:         if ($action ne 'display') {
                   12829:             $offset ++;
                   12830:         }  
1.1055    raeburn  12831:         $output .= '<td><span class="LC_nobreak">'.
                   12832:                    '<label><input type="radio" name="archive_'.$count.
                   12833:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12834:         my $text = $choices{$action};
                   12835:         if ($is_dir) {
                   12836:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12837:             if ($action eq 'display') {
1.1059    raeburn  12838:                 $text = &mt('Add as folder');
1.1055    raeburn  12839:             }
1.1056    raeburn  12840:         } else {
                   12841:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12842: 
                   12843:         }
                   12844:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12845:         if ($action eq 'dependency') {
                   12846:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12847:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12848:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12849:                        '<option value=""></option>'."\n".
                   12850:                        '</select>'."\n".
                   12851:                        '</div>';
1.1059    raeburn  12852:         } elsif ($action eq 'display') {
                   12853:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12854:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12855:                        '</div>';
1.1055    raeburn  12856:         }
1.1056    raeburn  12857:         $output .= '</td>';
1.1055    raeburn  12858:     }
                   12859:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12860:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12861:     for (my $i=0; $i<$depth; $i++) {
                   12862:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12863:     }
                   12864:     if ($is_dir) {
                   12865:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12866:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12867:     } else {
                   12868:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12869:     }
                   12870:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12871:                &end_data_table_row();
                   12872:     return $output;
                   12873: }
                   12874: 
                   12875: sub archive_options_form {
1.1065    raeburn  12876:     my ($form,$display,$count,$hiddenelem) = @_;
                   12877:     my %lt = &Apache::lonlocal::texthash(
                   12878:                perm => 'Permanently remove archive file?',
                   12879:                hows => 'How should each extracted item be incorporated in the course?',
                   12880:                cont => 'Content actions for all',
                   12881:                addf => 'Add as folder/file',
                   12882:                incd => 'Include as dependency for a displayed file',
                   12883:                disc => 'Discard',
                   12884:                no   => 'No',
                   12885:                yes  => 'Yes',
                   12886:                save => 'Save',
                   12887:     );
                   12888:     my $output = <<"END";
                   12889: <form name="$form" method="post" action="">
                   12890: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12891: <label>
                   12892:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12893: </label>
                   12894: &nbsp;
                   12895: <label>
                   12896:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12897: </span>
                   12898: </p>
                   12899: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12900: <br />$lt{'hows'}
                   12901: <div class="LC_columnSection">
                   12902:   <fieldset>
                   12903:     <legend>$lt{'cont'}</legend>
                   12904:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12905:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12906:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12907:   </fieldset>
                   12908: </div>
                   12909: END
                   12910:     return $output.
1.1055    raeburn  12911:            &start_data_table()."\n".
1.1065    raeburn  12912:            $display."\n".
1.1055    raeburn  12913:            &end_data_table()."\n".
                   12914:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12915:            $hiddenelem.
1.1065    raeburn  12916:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12917:            '</form>';
                   12918: }
                   12919: 
                   12920: sub archive_javascript {
1.1056    raeburn  12921:     my ($startcount,$numitems,$titles,$children) = @_;
                   12922:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12923:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12924:     my $scripttag = <<START;
                   12925: <script type="text/javascript">
                   12926: // <![CDATA[
                   12927: 
                   12928: function checkAll(form,prefix) {
                   12929:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12930:     for (var i=0; i < form.elements.length; i++) {
                   12931:         var id = form.elements[i].id;
                   12932:         if ((id != '') && (id != undefined)) {
                   12933:             if (idstr.test(id)) {
                   12934:                 if (form.elements[i].type == 'radio') {
                   12935:                     form.elements[i].checked = true;
1.1056    raeburn  12936:                     var nostart = i-$startcount;
1.1059    raeburn  12937:                     var offset = nostart%7;
                   12938:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12939:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12940:                 }
                   12941:             }
                   12942:         }
                   12943:     }
                   12944: }
                   12945: 
                   12946: function propagateCheck(form,count) {
                   12947:     if (count > 0) {
1.1059    raeburn  12948:         var startelement = $startcount + ((count-1) * 7);
                   12949:         for (var j=1; j<6; j++) {
                   12950:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12951:                 var item = startelement + j; 
                   12952:                 if (form.elements[item].type == 'radio') {
                   12953:                     if (form.elements[item].checked) {
                   12954:                         containerCheck(form,count,j);
                   12955:                         break;
                   12956:                     }
1.1055    raeburn  12957:                 }
                   12958:             }
                   12959:         }
                   12960:     }
                   12961: }
                   12962: 
                   12963: numitems = $numitems
1.1056    raeburn  12964: var titles = new Array(numitems);
                   12965: var parents = new Array(numitems);
1.1055    raeburn  12966: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12967:     parents[i] = new Array;
1.1055    raeburn  12968: }
1.1059    raeburn  12969: var maintitle = '$maintitle';
1.1055    raeburn  12970: 
                   12971: START
                   12972: 
1.1056    raeburn  12973:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12974:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12975:         for (my $i=0; $i<@contents; $i ++) {
                   12976:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12977:         }
                   12978:     }
                   12979: 
1.1056    raeburn  12980:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12981:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12982:     }
                   12983: 
1.1055    raeburn  12984:     $scripttag .= <<END;
                   12985: 
                   12986: function containerCheck(form,count,offset) {
                   12987:     if (count > 0) {
1.1056    raeburn  12988:         dependencyCheck(form,count,offset);
1.1059    raeburn  12989:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12990:         form.elements[item].checked = true;
                   12991:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12992:             if (parents[count].length > 0) {
                   12993:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12994:                     containerCheck(form,parents[count][j],offset);
                   12995:                 }
                   12996:             }
                   12997:         }
                   12998:     }
                   12999: }
                   13000: 
                   13001: function dependencyCheck(form,count,offset) {
                   13002:     if (count > 0) {
1.1059    raeburn  13003:         var chosen = (offset+$startcount)+7*(count-1);
                   13004:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13005:         var currtype = form.elements[depitem].type;
                   13006:         if (form.elements[chosen].value == 'dependency') {
                   13007:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13008:             form.elements[depitem].options.length = 0;
                   13009:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  13010:             for (var i=1; i<=numitems; i++) {
                   13011:                 if (i == count) {
                   13012:                     continue;
                   13013:                 }
1.1059    raeburn  13014:                 var startelement = $startcount + (i-1) * 7;
                   13015:                 for (var j=1; j<6; j++) {
                   13016:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13017:                         var item = startelement + j;
                   13018:                         if (form.elements[item].type == 'radio') {
                   13019:                             if (form.elements[item].checked) {
                   13020:                                 if (form.elements[item].value == 'display') {
                   13021:                                     var n = form.elements[depitem].options.length;
                   13022:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13023:                                 }
                   13024:                             }
                   13025:                         }
                   13026:                     }
                   13027:                 }
                   13028:             }
                   13029:         } else {
                   13030:             document.getElementById('arc_depon_'+count).style.display='none';
                   13031:             form.elements[depitem].options.length = 0;
                   13032:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13033:         }
1.1059    raeburn  13034:         titleCheck(form,count,offset);
1.1056    raeburn  13035:     }
                   13036: }
                   13037: 
                   13038: function propagateSelect(form,count,offset) {
                   13039:     if (count > 0) {
1.1065    raeburn  13040:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13041:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13042:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13043:             if (parents[count].length > 0) {
                   13044:                 for (var j=0; j<parents[count].length; j++) {
                   13045:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13046:                 }
                   13047:             }
                   13048:         }
                   13049:     }
                   13050: }
1.1056    raeburn  13051: 
                   13052: function containerSelect(form,count,offset,picked) {
                   13053:     if (count > 0) {
1.1065    raeburn  13054:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13055:         if (form.elements[item].type == 'radio') {
                   13056:             if (form.elements[item].value == 'dependency') {
                   13057:                 if (form.elements[item+1].type == 'select-one') {
                   13058:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13059:                         if (form.elements[item+1].options[i].value == picked) {
                   13060:                             form.elements[item+1].selectedIndex = i;
                   13061:                             break;
                   13062:                         }
                   13063:                     }
                   13064:                 }
                   13065:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13066:                     if (parents[count].length > 0) {
                   13067:                         for (var j=0; j<parents[count].length; j++) {
                   13068:                             containerSelect(form,parents[count][j],offset,picked);
                   13069:                         }
                   13070:                     }
                   13071:                 }
                   13072:             }
                   13073:         }
                   13074:     }
                   13075: }
                   13076: 
1.1059    raeburn  13077: function titleCheck(form,count,offset) {
                   13078:     if (count > 0) {
                   13079:         var chosen = (offset+$startcount)+7*(count-1);
                   13080:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13081:         var currtype = form.elements[depitem].type;
                   13082:         if (form.elements[chosen].value == 'display') {
                   13083:             document.getElementById('arc_title_'+count).style.display='block';
                   13084:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13085:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13086:             }
                   13087:         } else {
                   13088:             document.getElementById('arc_title_'+count).style.display='none';
                   13089:             if (currtype == 'text') { 
                   13090:                 document.getElementById('archive_title_'+count).value='';
                   13091:             }
                   13092:         }
                   13093:     }
                   13094:     return;
                   13095: }
                   13096: 
1.1055    raeburn  13097: // ]]>
                   13098: </script>
                   13099: END
                   13100:     return $scripttag;
                   13101: }
                   13102: 
                   13103: sub process_extracted_files {
1.1067    raeburn  13104:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13105:     my $numitems = $env{'form.archive_count'};
                   13106:     return unless ($numitems);
                   13107:     my @ids=&Apache::lonnet::current_machine_ids();
                   13108:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13109:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13110:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13111:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13112:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13113:         $pathtocheck = "$dir_root/$destination";
                   13114:         $dir = $dir_root;
                   13115:         $ishome = 1;
                   13116:     } else {
                   13117:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13118:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   13119:         $dir = "$dir_root/$docudom/$docuname";    
                   13120:     }
                   13121:     my $currdir = "$dir_root/$destination";
                   13122:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13123:     if ($env{'form.folderpath'}) {
                   13124:         my @items = split('&',$env{'form.folderpath'});
                   13125:         $folders{'0'} = $items[-2];
1.1099    raeburn  13126:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13127:             $containers{'0'}='page';
                   13128:         } else {  
                   13129:             $containers{'0'}='sequence';
                   13130:         }
1.1055    raeburn  13131:     }
                   13132:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13133:     if ($numitems) {
                   13134:         for (my $i=1; $i<=$numitems; $i++) {
                   13135:             my $path = $env{'form.archive_content_'.$i};
                   13136:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13137:                 my $item = $1;
                   13138:                 $toplevelitems{$item} = $i;
                   13139:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13140:                     $is_dir{$item} = 1;
                   13141:                 }
                   13142:             }
                   13143:         }
                   13144:     }
1.1067    raeburn  13145:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13146:     if (keys(%toplevelitems) > 0) {
                   13147:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13148:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13149:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13150:     }
1.1066    raeburn  13151:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13152:     if ($numitems) {
                   13153:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  13154:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13155:             my $path = $env{'form.archive_content_'.$i};
                   13156:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13157:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13158:                     if ($prefix ne '' && $path ne '') {
                   13159:                         if (-e $prefix.$path) {
1.1066    raeburn  13160:                             if ((@archdirs > 0) && 
                   13161:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13162:                                 $todeletedir{$prefix.$path} = 1;
                   13163:                             } else {
                   13164:                                 $todelete{$prefix.$path} = 1;
                   13165:                             }
1.1055    raeburn  13166:                         }
                   13167:                     }
                   13168:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13169:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13170:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13171:                     $docstitle = $env{'form.archive_title_'.$i};
                   13172:                     if ($docstitle eq '') {
                   13173:                         $docstitle = $title;
                   13174:                     }
1.1055    raeburn  13175:                     $outer = 0;
1.1056    raeburn  13176:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13177:                         if (@{$dirorder{$i}} > 0) {
                   13178:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13179:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13180:                                     $outer = $item;
                   13181:                                     last;
                   13182:                                 }
                   13183:                             }
                   13184:                         }
                   13185:                     }
                   13186:                     my ($errtext,$fatal) = 
                   13187:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13188:                                                '/'.$folders{$outer}.'.'.
                   13189:                                                $containers{$outer});
                   13190:                     next if ($fatal);
                   13191:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13192:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13193:                             $mapinner{$i} = time;
1.1055    raeburn  13194:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13195:                             $containers{$i} = 'sequence';
                   13196:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13197:                                       $folders{$i}.'.'.$containers{$i};
                   13198:                             my $newidx = &LONCAPA::map::getresidx();
                   13199:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13200:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13201:                             push(@LONCAPA::map::order,$newidx);
                   13202:                             my ($outtext,$errtext) =
                   13203:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13204:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13205:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13206:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13207:                             unless ($errtext) {
                   13208:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   13209:                             }
1.1055    raeburn  13210:                         }
                   13211:                     } else {
                   13212:                         if ($context eq 'coursedocs') {
                   13213:                             my $newidx=&LONCAPA::map::getresidx();
                   13214:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13215:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13216:                                       $title;
                   13217:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13218:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   13219:                             }
                   13220:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13221:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13222:                             }
                   13223:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13224:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  13225:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  13226:                                 unless ($ishome) {
                   13227:                                     my $fetch = "$newdest{$i}/$title";
                   13228:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13229:                                     $prompttofetch{$fetch} = 1;
                   13230:                                 }
1.1055    raeburn  13231:                             }
                   13232:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13233:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13234:                             push(@LONCAPA::map::order, $newidx);
                   13235:                             my ($outtext,$errtext)=
                   13236:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13237:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13238:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  13239:                             unless ($errtext) {
                   13240:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13241:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   13242:                                 }
                   13243:                             }
1.1055    raeburn  13244:                         }
                   13245:                     }
1.1086    raeburn  13246:                 }
                   13247:             } else {
                   13248:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   13249:             }
                   13250:         }
                   13251:         for (my $i=1; $i<=$numitems; $i++) {
                   13252:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13253:             my $path = $env{'form.archive_content_'.$i};
                   13254:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13255:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13256:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13257:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13258:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13259:                         my ($itemidx,$fullpath,$relpath);
                   13260:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13261:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13262:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  13263:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13264:                                     $itemidx = $j;
1.1056    raeburn  13265:                                 }
                   13266:                             }
1.1086    raeburn  13267:                         }
                   13268:                         if ($itemidx eq '') {
                   13269:                             $itemidx =  0;
                   13270:                         } 
                   13271:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13272:                             if ($mapinner{$referrer{$i}}) {
                   13273:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13274:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13275:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13276:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13277:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13278:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13279:                                             if (!-e $fullpath) {
                   13280:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13281:                                             }
                   13282:                                         }
1.1086    raeburn  13283:                                     } else {
                   13284:                                         last;
1.1056    raeburn  13285:                                     }
1.1086    raeburn  13286:                                 }
                   13287:                             }
                   13288:                         } elsif ($newdest{$referrer{$i}}) {
                   13289:                             $fullpath = $newdest{$referrer{$i}};
                   13290:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13291:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13292:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13293:                                     last;
                   13294:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13295:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13296:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13297:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13298:                                         if (!-e $fullpath) {
                   13299:                                             mkdir($fullpath,0755);
1.1056    raeburn  13300:                                         }
                   13301:                                     }
1.1086    raeburn  13302:                                 } else {
                   13303:                                     last;
1.1056    raeburn  13304:                                 }
1.1055    raeburn  13305:                             }
                   13306:                         }
1.1086    raeburn  13307:                         if ($fullpath ne '') {
                   13308:                             if (-e "$prefix$path") {
                   13309:                                 system("mv $prefix$path $fullpath/$title");
                   13310:                             }
                   13311:                             if (-e "$fullpath/$title") {
                   13312:                                 my $showpath;
                   13313:                                 if ($relpath ne '') {
                   13314:                                     $showpath = "$relpath/$title";
                   13315:                                 } else {
                   13316:                                     $showpath = "/$title";
                   13317:                                 } 
                   13318:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   13319:                             } 
                   13320:                             unless ($ishome) {
                   13321:                                 my $fetch = "$fullpath/$title";
                   13322:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   13323:                                 $prompttofetch{$fetch} = 1;
                   13324:                             }
                   13325:                         }
1.1055    raeburn  13326:                     }
1.1086    raeburn  13327:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13328:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   13329:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  13330:                 }
                   13331:             } else {
                   13332:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   13333:             }
                   13334:         }
                   13335:         if (keys(%todelete)) {
                   13336:             foreach my $key (keys(%todelete)) {
                   13337:                 unlink($key);
1.1066    raeburn  13338:             }
                   13339:         }
                   13340:         if (keys(%todeletedir)) {
                   13341:             foreach my $key (keys(%todeletedir)) {
                   13342:                 rmdir($key);
                   13343:             }
                   13344:         }
                   13345:         foreach my $dir (sort(keys(%is_dir))) {
                   13346:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13347:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13348:             }
                   13349:         }
1.1067    raeburn  13350:         if ($result ne '') {
                   13351:             $output .= '<ul>'."\n".
                   13352:                        $result."\n".
                   13353:                        '</ul>';
                   13354:         }
                   13355:         unless ($ishome) {
                   13356:             my $replicationfail;
                   13357:             foreach my $item (keys(%prompttofetch)) {
                   13358:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13359:                 unless ($fetchresult eq 'ok') {
                   13360:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13361:                 }
                   13362:             }
                   13363:             if ($replicationfail) {
                   13364:                 $output .= '<p class="LC_error">'.
                   13365:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13366:                            $replicationfail.
                   13367:                            '</ul></p>';
                   13368:             }
                   13369:         }
1.1055    raeburn  13370:     } else {
                   13371:         $warning = &mt('No items found in archive.');
                   13372:     }
                   13373:     if ($error) {
                   13374:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13375:                    $error.'</p>'."\n";
                   13376:     }
                   13377:     if ($warning) {
                   13378:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13379:     }
                   13380:     return $output;
                   13381: }
                   13382: 
1.1066    raeburn  13383: sub cleanup_empty_dirs {
                   13384:     my ($path) = @_;
                   13385:     if (($path ne '') && (-d $path)) {
                   13386:         if (opendir(my $dirh,$path)) {
                   13387:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13388:             my $numitems = 0;
                   13389:             foreach my $item (@dircontents) {
                   13390:                 if (-d "$path/$item") {
1.1111    raeburn  13391:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13392:                     if (-e "$path/$item") {
                   13393:                         $numitems ++;
                   13394:                     }
                   13395:                 } else {
                   13396:                     $numitems ++;
                   13397:                 }
                   13398:             }
                   13399:             if ($numitems == 0) {
                   13400:                 rmdir($path);
                   13401:             }
                   13402:             closedir($dirh);
                   13403:         }
                   13404:     }
                   13405:     return;
                   13406: }
                   13407: 
1.41      ng       13408: =pod
1.45      matthew  13409: 
1.1162    raeburn  13410: =item * &get_folder_hierarchy()
1.1068    raeburn  13411: 
                   13412: Provides hierarchy of names of folders/sub-folders containing the current
                   13413: item,
                   13414: 
                   13415: Inputs: 3
                   13416:      - $navmap - navmaps object
                   13417: 
                   13418:      - $map - url for map (either the trigger itself, or map containing
                   13419:                            the resource, which is the trigger).
                   13420: 
                   13421:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13422: 
                   13423: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13424: 
                   13425: =cut
                   13426: 
                   13427: sub get_folder_hierarchy {
                   13428:     my ($navmap,$map,$showitem) = @_;
                   13429:     my @pathitems;
                   13430:     if (ref($navmap)) {
                   13431:         my $mapres = $navmap->getResourceByUrl($map);
                   13432:         if (ref($mapres)) {
                   13433:             my $pcslist = $mapres->map_hierarchy();
                   13434:             if ($pcslist ne '') {
                   13435:                 my @pcs = split(/,/,$pcslist);
                   13436:                 foreach my $pc (@pcs) {
                   13437:                     if ($pc == 1) {
1.1129    raeburn  13438:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13439:                     } else {
                   13440:                         my $res = $navmap->getByMapPc($pc);
                   13441:                         if (ref($res)) {
                   13442:                             my $title = $res->compTitle();
                   13443:                             $title =~ s/\W+/_/g;
                   13444:                             if ($title ne '') {
                   13445:                                 push(@pathitems,$title);
                   13446:                             }
                   13447:                         }
                   13448:                     }
                   13449:                 }
                   13450:             }
1.1071    raeburn  13451:             if ($showitem) {
                   13452:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  13453:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13454:                 } else {
                   13455:                     my $maptitle = $mapres->compTitle();
                   13456:                     $maptitle =~ s/\W+/_/g;
                   13457:                     if ($maptitle ne '') {
                   13458:                         push(@pathitems,$maptitle);
                   13459:                     }
1.1068    raeburn  13460:                 }
                   13461:             }
                   13462:         }
                   13463:     }
                   13464:     return @pathitems;
                   13465: }
                   13466: 
                   13467: =pod
                   13468: 
1.1015    raeburn  13469: =item * &get_turnedin_filepath()
                   13470: 
                   13471: Determines path in a user's portfolio file for storage of files uploaded
                   13472: to a specific essayresponse or dropbox item.
                   13473: 
                   13474: Inputs: 3 required + 1 optional.
                   13475: $symb is symb for resource, $uname and $udom are for current user (required).
                   13476: $caller is optional (can be "submission", if routine is called when storing
                   13477: an upoaded file when "Submit Answer" button was pressed).
                   13478: 
                   13479: Returns array containing $path and $multiresp. 
                   13480: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13481: than one file upload item.  Callers of routine should append partid as a 
                   13482: subdirectory to $path in cases where $multiresp is 1.
                   13483: 
                   13484: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13485: 
                   13486: =cut
                   13487: 
                   13488: sub get_turnedin_filepath {
                   13489:     my ($symb,$uname,$udom,$caller) = @_;
                   13490:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13491:     my $turnindir;
                   13492:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13493:     $turnindir = $userhash{'turnindir'};
                   13494:     my ($path,$multiresp);
                   13495:     if ($turnindir eq '') {
                   13496:         if ($caller eq 'submission') {
                   13497:             $turnindir = &mt('turned in');
                   13498:             $turnindir =~ s/\W+/_/g;
                   13499:             my %newhash = (
                   13500:                             'turnindir' => $turnindir,
                   13501:                           );
                   13502:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13503:         }
                   13504:     }
                   13505:     if ($turnindir ne '') {
                   13506:         $path = '/'.$turnindir.'/';
                   13507:         my ($multipart,$turnin,@pathitems);
                   13508:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13509:         if (defined($navmap)) {
                   13510:             my $mapres = $navmap->getResourceByUrl($map);
                   13511:             if (ref($mapres)) {
                   13512:                 my $pcslist = $mapres->map_hierarchy();
                   13513:                 if ($pcslist ne '') {
                   13514:                     foreach my $pc (split(/,/,$pcslist)) {
                   13515:                         my $res = $navmap->getByMapPc($pc);
                   13516:                         if (ref($res)) {
                   13517:                             my $title = $res->compTitle();
                   13518:                             $title =~ s/\W+/_/g;
                   13519:                             if ($title ne '') {
1.1149    raeburn  13520:                                 if (($pc > 1) && (length($title) > 12)) {
                   13521:                                     $title = substr($title,0,12);
                   13522:                                 }
1.1015    raeburn  13523:                                 push(@pathitems,$title);
                   13524:                             }
                   13525:                         }
                   13526:                     }
                   13527:                 }
                   13528:                 my $maptitle = $mapres->compTitle();
                   13529:                 $maptitle =~ s/\W+/_/g;
                   13530:                 if ($maptitle ne '') {
1.1149    raeburn  13531:                     if (length($maptitle) > 12) {
                   13532:                         $maptitle = substr($maptitle,0,12);
                   13533:                     }
1.1015    raeburn  13534:                     push(@pathitems,$maptitle);
                   13535:                 }
                   13536:                 unless ($env{'request.state'} eq 'construct') {
                   13537:                     my $res = $navmap->getBySymb($symb);
                   13538:                     if (ref($res)) {
                   13539:                         my $partlist = $res->parts();
                   13540:                         my $totaluploads = 0;
                   13541:                         if (ref($partlist) eq 'ARRAY') {
                   13542:                             foreach my $part (@{$partlist}) {
                   13543:                                 my @types = $res->responseType($part);
                   13544:                                 my @ids = $res->responseIds($part);
                   13545:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13546:                                     if ($types[$i] eq 'essay') {
                   13547:                                         my $partid = $part.'_'.$ids[$i];
                   13548:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13549:                                             $totaluploads ++;
                   13550:                                         }
                   13551:                                     }
                   13552:                                 }
                   13553:                             }
                   13554:                             if ($totaluploads > 1) {
                   13555:                                 $multiresp = 1;
                   13556:                             }
                   13557:                         }
                   13558:                     }
                   13559:                 }
                   13560:             } else {
                   13561:                 return;
                   13562:             }
                   13563:         } else {
                   13564:             return;
                   13565:         }
                   13566:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13567:         $restitle =~ s/\W+/_/g;
                   13568:         if ($restitle eq '') {
                   13569:             $restitle = ($resurl =~ m{/[^/]+$});
                   13570:             if ($restitle eq '') {
                   13571:                 $restitle = time;
                   13572:             }
                   13573:         }
1.1149    raeburn  13574:         if (length($restitle) > 12) {
                   13575:             $restitle = substr($restitle,0,12);
                   13576:         }
1.1015    raeburn  13577:         push(@pathitems,$restitle);
                   13578:         $path .= join('/',@pathitems);
                   13579:     }
                   13580:     return ($path,$multiresp);
                   13581: }
                   13582: 
                   13583: =pod
                   13584: 
1.464     albertel 13585: =back
1.41      ng       13586: 
1.112     bowersj2 13587: =head1 CSV Upload/Handling functions
1.38      albertel 13588: 
1.41      ng       13589: =over 4
                   13590: 
1.648     raeburn  13591: =item * &upfile_store($r)
1.41      ng       13592: 
                   13593: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13594: needs $env{'form.upfile'}
1.41      ng       13595: returns $datatoken to be put into hidden field
                   13596: 
                   13597: =cut
1.31      albertel 13598: 
                   13599: sub upfile_store {
                   13600:     my $r=shift;
1.258     albertel 13601:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13602:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13603:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13604:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13605: 
1.258     albertel 13606:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   13607: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 13608:     {
1.158     raeburn  13609:         my $datafile = $r->dir_config('lonDaemons').
                   13610:                            '/tmp/'.$datatoken.'.tmp';
                   13611:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 13612:             print $fh $env{'form.upfile'};
1.158     raeburn  13613:             close($fh);
                   13614:         }
1.31      albertel 13615:     }
                   13616:     return $datatoken;
                   13617: }
                   13618: 
1.56      matthew  13619: =pod
                   13620: 
1.648     raeburn  13621: =item * &load_tmp_file($r)
1.41      ng       13622: 
                   13623: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 13624: needs $env{'form.datatoken'},
                   13625: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13626: 
                   13627: =cut
1.31      albertel 13628: 
                   13629: sub load_tmp_file {
                   13630:     my $r=shift;
                   13631:     my @studentdata=();
                   13632:     {
1.158     raeburn  13633:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 13634:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  13635:         if ( open(my $fh,"<$studentfile") ) {
                   13636:             @studentdata=<$fh>;
                   13637:             close($fh);
                   13638:         }
1.31      albertel 13639:     }
1.258     albertel 13640:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13641: }
                   13642: 
1.56      matthew  13643: =pod
                   13644: 
1.648     raeburn  13645: =item * &upfile_record_sep()
1.41      ng       13646: 
                   13647: Separate uploaded file into records
                   13648: returns array of records,
1.258     albertel 13649: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13650: 
                   13651: =cut
1.31      albertel 13652: 
                   13653: sub upfile_record_sep {
1.258     albertel 13654:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13655:     } else {
1.248     albertel 13656: 	my @records;
1.258     albertel 13657: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13658: 	    if ($line=~/^\s*$/) { next; }
                   13659: 	    push(@records,$line);
                   13660: 	}
                   13661: 	return @records;
1.31      albertel 13662:     }
                   13663: }
                   13664: 
1.56      matthew  13665: =pod
                   13666: 
1.648     raeburn  13667: =item * &record_sep($record)
1.41      ng       13668: 
1.258     albertel 13669: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13670: 
                   13671: =cut
                   13672: 
1.263     www      13673: sub takeleft {
                   13674:     my $index=shift;
                   13675:     return substr('0000'.$index,-4,4);
                   13676: }
                   13677: 
1.31      albertel 13678: sub record_sep {
                   13679:     my $record=shift;
                   13680:     my %components=();
1.258     albertel 13681:     if ($env{'form.upfiletype'} eq 'xml') {
                   13682:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13683:         my $i=0;
1.356     albertel 13684:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13685:             $field=~s/^(\"|\')//;
                   13686:             $field=~s/(\"|\')$//;
1.263     www      13687:             $components{&takeleft($i)}=$field;
1.31      albertel 13688:             $i++;
                   13689:         }
1.258     albertel 13690:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13691:         my $i=0;
1.356     albertel 13692:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13693:             $field=~s/^(\"|\')//;
                   13694:             $field=~s/(\"|\')$//;
1.263     www      13695:             $components{&takeleft($i)}=$field;
1.31      albertel 13696:             $i++;
                   13697:         }
                   13698:     } else {
1.561     www      13699:         my $separator=',';
1.480     banghart 13700:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13701:             $separator=';';
1.480     banghart 13702:         }
1.31      albertel 13703:         my $i=0;
1.561     www      13704: # the character we are looking for to indicate the end of a quote or a record 
                   13705:         my $looking_for=$separator;
                   13706: # do not add the characters to the fields
                   13707:         my $ignore=0;
                   13708: # we just encountered a separator (or the beginning of the record)
                   13709:         my $just_found_separator=1;
                   13710: # store the field we are working on here
                   13711:         my $field='';
                   13712: # work our way through all characters in record
                   13713:         foreach my $character ($record=~/(.)/g) {
                   13714:             if ($character eq $looking_for) {
                   13715:                if ($character ne $separator) {
                   13716: # Found the end of a quote, again looking for separator
                   13717:                   $looking_for=$separator;
                   13718:                   $ignore=1;
                   13719:                } else {
                   13720: # Found a separator, store away what we got
                   13721:                   $components{&takeleft($i)}=$field;
                   13722: 	          $i++;
                   13723:                   $just_found_separator=1;
                   13724:                   $ignore=0;
                   13725:                   $field='';
                   13726:                }
                   13727:                next;
                   13728:             }
                   13729: # single or double quotation marks after a separator indicate beginning of a quote
                   13730: # we are now looking for the end of the quote and need to ignore separators
                   13731:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13732:                $looking_for=$character;
                   13733:                next;
                   13734:             }
                   13735: # ignore would be true after we reached the end of a quote
                   13736:             if ($ignore) { next; }
                   13737:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13738:             $field.=$character;
                   13739:             $just_found_separator=0; 
1.31      albertel 13740:         }
1.561     www      13741: # catch the very last entry, since we never encountered the separator
                   13742:         $components{&takeleft($i)}=$field;
1.31      albertel 13743:     }
                   13744:     return %components;
                   13745: }
                   13746: 
1.144     matthew  13747: ######################################################
                   13748: ######################################################
                   13749: 
1.56      matthew  13750: =pod
                   13751: 
1.648     raeburn  13752: =item * &upfile_select_html()
1.41      ng       13753: 
1.144     matthew  13754: Return HTML code to select a file from the users machine and specify 
                   13755: the file type.
1.41      ng       13756: 
                   13757: =cut
                   13758: 
1.144     matthew  13759: ######################################################
                   13760: ######################################################
1.31      albertel 13761: sub upfile_select_html {
1.144     matthew  13762:     my %Types = (
                   13763:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13764:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13765:                  space => &mt('Space separated'),
                   13766:                  tab   => &mt('Tabulator separated'),
                   13767: #                 xml   => &mt('HTML/XML'),
                   13768:                  );
                   13769:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13770:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13771:     foreach my $type (sort(keys(%Types))) {
                   13772:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13773:     }
                   13774:     $Str .= "</select>\n";
                   13775:     return $Str;
1.31      albertel 13776: }
                   13777: 
1.301     albertel 13778: sub get_samples {
                   13779:     my ($records,$toget) = @_;
                   13780:     my @samples=({});
                   13781:     my $got=0;
                   13782:     foreach my $rec (@$records) {
                   13783: 	my %temp = &record_sep($rec);
                   13784: 	if (! grep(/\S/, values(%temp))) { next; }
                   13785: 	if (%temp) {
                   13786: 	    $samples[$got]=\%temp;
                   13787: 	    $got++;
                   13788: 	    if ($got == $toget) { last; }
                   13789: 	}
                   13790:     }
                   13791:     return \@samples;
                   13792: }
                   13793: 
1.144     matthew  13794: ######################################################
                   13795: ######################################################
                   13796: 
1.56      matthew  13797: =pod
                   13798: 
1.648     raeburn  13799: =item * &csv_print_samples($r,$records)
1.41      ng       13800: 
                   13801: Prints a table of sample values from each column uploaded $r is an
                   13802: Apache Request ref, $records is an arrayref from
                   13803: &Apache::loncommon::upfile_record_sep
                   13804: 
                   13805: =cut
                   13806: 
1.144     matthew  13807: ######################################################
                   13808: ######################################################
1.31      albertel 13809: sub csv_print_samples {
                   13810:     my ($r,$records) = @_;
1.662     bisitz   13811:     my $samples = &get_samples($records,5);
1.301     albertel 13812: 
1.594     raeburn  13813:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13814:               &start_data_table_header_row());
1.356     albertel 13815:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13816:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13817:     $r->print(&end_data_table_header_row());
1.301     albertel 13818:     foreach my $hash (@$samples) {
1.594     raeburn  13819: 	$r->print(&start_data_table_row());
1.356     albertel 13820: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13821: 	    $r->print('<td>');
1.356     albertel 13822: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13823: 	    $r->print('</td>');
                   13824: 	}
1.594     raeburn  13825: 	$r->print(&end_data_table_row());
1.31      albertel 13826:     }
1.594     raeburn  13827:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13828: }
                   13829: 
1.144     matthew  13830: ######################################################
                   13831: ######################################################
                   13832: 
1.56      matthew  13833: =pod
                   13834: 
1.648     raeburn  13835: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13836: 
                   13837: Prints a table to create associations between values and table columns.
1.144     matthew  13838: 
1.41      ng       13839: $r is an Apache Request ref,
                   13840: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13841: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13842: 
                   13843: =cut
                   13844: 
1.144     matthew  13845: ######################################################
                   13846: ######################################################
1.31      albertel 13847: sub csv_print_select_table {
                   13848:     my ($r,$records,$d) = @_;
1.301     albertel 13849:     my $i=0;
                   13850:     my $samples = &get_samples($records,1);
1.144     matthew  13851:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13852: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13853:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13854:               '<th>'.&mt('Column').'</th>'.
                   13855:               &end_data_table_header_row()."\n");
1.356     albertel 13856:     foreach my $array_ref (@$d) {
                   13857: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13858: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13859: 
1.875     bisitz   13860: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13861: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13862: 	$r->print('<option value="none"></option>');
1.356     albertel 13863: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13864: 	    $r->print('<option value="'.$sample.'"'.
                   13865:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13866:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13867: 	}
1.594     raeburn  13868: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13869: 	$i++;
                   13870:     }
1.594     raeburn  13871:     $r->print(&end_data_table());
1.31      albertel 13872:     $i--;
                   13873:     return $i;
                   13874: }
1.56      matthew  13875: 
1.144     matthew  13876: ######################################################
                   13877: ######################################################
                   13878: 
1.56      matthew  13879: =pod
1.31      albertel 13880: 
1.648     raeburn  13881: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13882: 
                   13883: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13884: 
                   13885: $r is an Apache Request ref,
                   13886: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13887: $d is an array of 2 element arrays (internal name, displayed name)
                   13888: 
                   13889: =cut
                   13890: 
1.144     matthew  13891: ######################################################
                   13892: ######################################################
1.31      albertel 13893: sub csv_samples_select_table {
                   13894:     my ($r,$records,$d) = @_;
                   13895:     my $i=0;
1.144     matthew  13896:     #
1.662     bisitz   13897:     my $max_samples = 5;
                   13898:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13899:     $r->print(&start_data_table().
                   13900:               &start_data_table_header_row().'<th>'.
                   13901:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13902:               &end_data_table_header_row());
1.301     albertel 13903: 
                   13904:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13905: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13906: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13907: 	foreach my $option (@$d) {
                   13908: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13909: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13910:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13911:                       $display.'</option>');
1.31      albertel 13912: 	}
                   13913: 	$r->print('</select></td><td>');
1.662     bisitz   13914: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13915: 	    if (defined($samples->[$line]{$key})) { 
                   13916: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13917: 	    }
                   13918: 	}
1.594     raeburn  13919: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13920: 	$i++;
                   13921:     }
1.594     raeburn  13922:     $r->print(&end_data_table());
1.31      albertel 13923:     $i--;
                   13924:     return($i);
1.115     matthew  13925: }
                   13926: 
1.144     matthew  13927: ######################################################
                   13928: ######################################################
                   13929: 
1.115     matthew  13930: =pod
                   13931: 
1.648     raeburn  13932: =item * &clean_excel_name($name)
1.115     matthew  13933: 
                   13934: Returns a replacement for $name which does not contain any illegal characters.
                   13935: 
                   13936: =cut
                   13937: 
1.144     matthew  13938: ######################################################
                   13939: ######################################################
1.115     matthew  13940: sub clean_excel_name {
                   13941:     my ($name) = @_;
                   13942:     $name =~ s/[:\*\?\/\\]//g;
                   13943:     if (length($name) > 31) {
                   13944:         $name = substr($name,0,31);
                   13945:     }
                   13946:     return $name;
1.25      albertel 13947: }
1.84      albertel 13948: 
1.85      albertel 13949: =pod
                   13950: 
1.648     raeburn  13951: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13952: 
                   13953: Returns either 1 or undef
                   13954: 
                   13955: 1 if the part is to be hidden, undef if it is to be shown
                   13956: 
                   13957: Arguments are:
                   13958: 
                   13959: $id the id of the part to be checked
                   13960: $symb, optional the symb of the resource to check
                   13961: $udom, optional the domain of the user to check for
                   13962: $uname, optional the username of the user to check for
                   13963: 
                   13964: =cut
1.84      albertel 13965: 
                   13966: sub check_if_partid_hidden {
                   13967:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13968:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13969: 					 $symb,$udom,$uname);
1.141     albertel 13970:     my $truth=1;
                   13971:     #if the string starts with !, then the list is the list to show not hide
                   13972:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13973:     my @hiddenlist=split(/,/,$hiddenparts);
                   13974:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13975: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13976:     }
1.141     albertel 13977:     return !$truth;
1.84      albertel 13978: }
1.127     matthew  13979: 
1.138     matthew  13980: 
                   13981: ############################################################
                   13982: ############################################################
                   13983: 
                   13984: =pod
                   13985: 
1.157     matthew  13986: =back 
                   13987: 
1.138     matthew  13988: =head1 cgi-bin script and graphing routines
                   13989: 
1.157     matthew  13990: =over 4
                   13991: 
1.648     raeburn  13992: =item * &get_cgi_id()
1.138     matthew  13993: 
                   13994: Inputs: none
                   13995: 
                   13996: Returns an id which can be used to pass environment variables
                   13997: to various cgi-bin scripts.  These environment variables will
                   13998: be removed from the users environment after a given time by
                   13999: the routine &Apache::lonnet::transfer_profile_to_env.
                   14000: 
                   14001: =cut
                   14002: 
                   14003: ############################################################
                   14004: ############################################################
1.152     albertel 14005: my $uniq=0;
1.136     matthew  14006: sub get_cgi_id {
1.154     albertel 14007:     $uniq=($uniq+1)%100000;
1.280     albertel 14008:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14009: }
                   14010: 
1.127     matthew  14011: ############################################################
                   14012: ############################################################
                   14013: 
                   14014: =pod
                   14015: 
1.648     raeburn  14016: =item * &DrawBarGraph()
1.127     matthew  14017: 
1.138     matthew  14018: Facilitates the plotting of data in a (stacked) bar graph.
                   14019: Puts plot definition data into the users environment in order for 
                   14020: graph.png to plot it.  Returns an <img> tag for the plot.
                   14021: The bars on the plot are labeled '1','2',...,'n'.
                   14022: 
                   14023: Inputs:
                   14024: 
                   14025: =over 4
                   14026: 
                   14027: =item $Title: string, the title of the plot
                   14028: 
                   14029: =item $xlabel: string, text describing the X-axis of the plot
                   14030: 
                   14031: =item $ylabel: string, text describing the Y-axis of the plot
                   14032: 
                   14033: =item $Max: scalar, the maximum Y value to use in the plot
                   14034: If $Max is < any data point, the graph will not be rendered.
                   14035: 
1.140     matthew  14036: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14037: they are plotted.  If undefined, default values will be used.
                   14038: 
1.178     matthew  14039: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14040: 
1.138     matthew  14041: =item @Values: An array of array references.  Each array reference holds data
                   14042: to be plotted in a stacked bar chart.
                   14043: 
1.239     matthew  14044: =item If the final element of @Values is a hash reference the key/value
                   14045: pairs will be added to the graph definition.
                   14046: 
1.138     matthew  14047: =back
                   14048: 
                   14049: Returns:
                   14050: 
                   14051: An <img> tag which references graph.png and the appropriate identifying
                   14052: information for the plot.
                   14053: 
1.127     matthew  14054: =cut
                   14055: 
                   14056: ############################################################
                   14057: ############################################################
1.134     matthew  14058: sub DrawBarGraph {
1.178     matthew  14059:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14060:     #
                   14061:     if (! defined($colors)) {
                   14062:         $colors = ['#33ff00', 
                   14063:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14064:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14065:                   ]; 
                   14066:     }
1.228     matthew  14067:     my $extra_settings = {};
                   14068:     if (ref($Values[-1]) eq 'HASH') {
                   14069:         $extra_settings = pop(@Values);
                   14070:     }
1.127     matthew  14071:     #
1.136     matthew  14072:     my $identifier = &get_cgi_id();
                   14073:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14074:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14075:         return '';
                   14076:     }
1.225     matthew  14077:     #
                   14078:     my @Labels;
                   14079:     if (defined($labels)) {
                   14080:         @Labels = @$labels;
                   14081:     } else {
                   14082:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  14083:             push(@Labels,$i+1);
1.225     matthew  14084:         }
                   14085:     }
                   14086:     #
1.129     matthew  14087:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14088:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14089:     my %ValuesHash;
                   14090:     my $NumSets=1;
                   14091:     foreach my $array (@Values) {
                   14092:         next if (! ref($array));
1.136     matthew  14093:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14094:             join(',',@$array);
1.129     matthew  14095:     }
1.127     matthew  14096:     #
1.136     matthew  14097:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14098:     if ($NumBars < 3) {
                   14099:         $width = 120+$NumBars*32;
1.220     matthew  14100:         $xskip = 1;
1.225     matthew  14101:         $bar_width = 30;
                   14102:     } elsif ($NumBars < 5) {
                   14103:         $width = 120+$NumBars*20;
                   14104:         $xskip = 1;
                   14105:         $bar_width = 20;
1.220     matthew  14106:     } elsif ($NumBars < 10) {
1.136     matthew  14107:         $width = 120+$NumBars*15;
                   14108:         $xskip = 1;
                   14109:         $bar_width = 15;
                   14110:     } elsif ($NumBars <= 25) {
                   14111:         $width = 120+$NumBars*11;
                   14112:         $xskip = 5;
                   14113:         $bar_width = 8;
                   14114:     } elsif ($NumBars <= 50) {
                   14115:         $width = 120+$NumBars*8;
                   14116:         $xskip = 5;
                   14117:         $bar_width = 4;
                   14118:     } else {
                   14119:         $width = 120+$NumBars*8;
                   14120:         $xskip = 5;
                   14121:         $bar_width = 4;
                   14122:     }
                   14123:     #
1.137     matthew  14124:     $Max = 1 if ($Max < 1);
                   14125:     if ( int($Max) < $Max ) {
                   14126:         $Max++;
                   14127:         $Max = int($Max);
                   14128:     }
1.127     matthew  14129:     $Title  = '' if (! defined($Title));
                   14130:     $xlabel = '' if (! defined($xlabel));
                   14131:     $ylabel = '' if (! defined($ylabel));
1.369     www      14132:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14133:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14134:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14135:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14136:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14137:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14138:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14139:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14140:     $ValuesHash{$id.'.height'}   = $height;
                   14141:     $ValuesHash{$id.'.width'}    = $width;
                   14142:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14143:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14144:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14145:     #
1.228     matthew  14146:     # Deal with other parameters
                   14147:     while (my ($key,$value) = each(%$extra_settings)) {
                   14148:         $ValuesHash{$id.'.'.$key} = $value;
                   14149:     }
                   14150:     #
1.646     raeburn  14151:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14152:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14153: }
                   14154: 
                   14155: ############################################################
                   14156: ############################################################
                   14157: 
                   14158: =pod
                   14159: 
1.648     raeburn  14160: =item * &DrawXYGraph()
1.137     matthew  14161: 
1.138     matthew  14162: Facilitates the plotting of data in an XY graph.
                   14163: Puts plot definition data into the users environment in order for 
                   14164: graph.png to plot it.  Returns an <img> tag for the plot.
                   14165: 
                   14166: Inputs:
                   14167: 
                   14168: =over 4
                   14169: 
                   14170: =item $Title: string, the title of the plot
                   14171: 
                   14172: =item $xlabel: string, text describing the X-axis of the plot
                   14173: 
                   14174: =item $ylabel: string, text describing the Y-axis of the plot
                   14175: 
                   14176: =item $Max: scalar, the maximum Y value to use in the plot
                   14177: If $Max is < any data point, the graph will not be rendered.
                   14178: 
                   14179: =item $colors: Array ref containing the hex color codes for the data to be 
                   14180: plotted in.  If undefined, default values will be used.
                   14181: 
                   14182: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14183: 
                   14184: =item $Ydata: Array ref containing Array refs.  
1.185     www      14185: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14186: 
                   14187: =item %Values: hash indicating or overriding any default values which are 
                   14188: passed to graph.png.  
                   14189: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14190: 
                   14191: =back
                   14192: 
                   14193: Returns:
                   14194: 
                   14195: An <img> tag which references graph.png and the appropriate identifying
                   14196: information for the plot.
                   14197: 
1.137     matthew  14198: =cut
                   14199: 
                   14200: ############################################################
                   14201: ############################################################
                   14202: sub DrawXYGraph {
                   14203:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14204:     #
                   14205:     # Create the identifier for the graph
                   14206:     my $identifier = &get_cgi_id();
                   14207:     my $id = 'cgi.'.$identifier;
                   14208:     #
                   14209:     $Title  = '' if (! defined($Title));
                   14210:     $xlabel = '' if (! defined($xlabel));
                   14211:     $ylabel = '' if (! defined($ylabel));
                   14212:     my %ValuesHash = 
                   14213:         (
1.369     www      14214:          $id.'.title'  => &escape($Title),
                   14215:          $id.'.xlabel' => &escape($xlabel),
                   14216:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14217:          $id.'.y_max_value'=> $Max,
                   14218:          $id.'.labels'     => join(',',@$Xlabels),
                   14219:          $id.'.PlotType'   => 'XY',
                   14220:          );
                   14221:     #
                   14222:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14223:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14224:     }
                   14225:     #
                   14226:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14227:         return '';
                   14228:     }
                   14229:     my $NumSets=1;
1.138     matthew  14230:     foreach my $array (@{$Ydata}){
1.137     matthew  14231:         next if (! ref($array));
                   14232:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14233:     }
1.138     matthew  14234:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14235:     #
                   14236:     # Deal with other parameters
                   14237:     while (my ($key,$value) = each(%Values)) {
                   14238:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14239:     }
                   14240:     #
1.646     raeburn  14241:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14242:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14243: }
                   14244: 
                   14245: ############################################################
                   14246: ############################################################
                   14247: 
                   14248: =pod
                   14249: 
1.648     raeburn  14250: =item * &DrawXYYGraph()
1.138     matthew  14251: 
                   14252: Facilitates the plotting of data in an XY graph with two Y axes.
                   14253: Puts plot definition data into the users environment in order for 
                   14254: graph.png to plot it.  Returns an <img> tag for the plot.
                   14255: 
                   14256: Inputs:
                   14257: 
                   14258: =over 4
                   14259: 
                   14260: =item $Title: string, the title of the plot
                   14261: 
                   14262: =item $xlabel: string, text describing the X-axis of the plot
                   14263: 
                   14264: =item $ylabel: string, text describing the Y-axis of the plot
                   14265: 
                   14266: =item $colors: Array ref containing the hex color codes for the data to be 
                   14267: plotted in.  If undefined, default values will be used.
                   14268: 
                   14269: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14270: 
                   14271: =item $Ydata1: The first data set
                   14272: 
                   14273: =item $Min1: The minimum value of the left Y-axis
                   14274: 
                   14275: =item $Max1: The maximum value of the left Y-axis
                   14276: 
                   14277: =item $Ydata2: The second data set
                   14278: 
                   14279: =item $Min2: The minimum value of the right Y-axis
                   14280: 
                   14281: =item $Max2: The maximum value of the left Y-axis
                   14282: 
                   14283: =item %Values: hash indicating or overriding any default values which are 
                   14284: passed to graph.png.  
                   14285: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14286: 
                   14287: =back
                   14288: 
                   14289: Returns:
                   14290: 
                   14291: An <img> tag which references graph.png and the appropriate identifying
                   14292: information for the plot.
1.136     matthew  14293: 
                   14294: =cut
                   14295: 
                   14296: ############################################################
                   14297: ############################################################
1.137     matthew  14298: sub DrawXYYGraph {
                   14299:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14300:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14301:     #
                   14302:     # Create the identifier for the graph
                   14303:     my $identifier = &get_cgi_id();
                   14304:     my $id = 'cgi.'.$identifier;
                   14305:     #
                   14306:     $Title  = '' if (! defined($Title));
                   14307:     $xlabel = '' if (! defined($xlabel));
                   14308:     $ylabel = '' if (! defined($ylabel));
                   14309:     my %ValuesHash = 
                   14310:         (
1.369     www      14311:          $id.'.title'  => &escape($Title),
                   14312:          $id.'.xlabel' => &escape($xlabel),
                   14313:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14314:          $id.'.labels' => join(',',@$Xlabels),
                   14315:          $id.'.PlotType' => 'XY',
                   14316:          $id.'.NumSets' => 2,
1.137     matthew  14317:          $id.'.two_axes' => 1,
                   14318:          $id.'.y1_max_value' => $Max1,
                   14319:          $id.'.y1_min_value' => $Min1,
                   14320:          $id.'.y2_max_value' => $Max2,
                   14321:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14322:          );
                   14323:     #
1.137     matthew  14324:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14325:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14326:     }
                   14327:     #
                   14328:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14329:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14330:         return '';
                   14331:     }
                   14332:     my $NumSets=1;
1.137     matthew  14333:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14334:         next if (! ref($array));
                   14335:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14336:     }
                   14337:     #
                   14338:     # Deal with other parameters
                   14339:     while (my ($key,$value) = each(%Values)) {
                   14340:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14341:     }
                   14342:     #
1.646     raeburn  14343:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14344:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14345: }
                   14346: 
                   14347: ############################################################
                   14348: ############################################################
                   14349: 
                   14350: =pod
                   14351: 
1.157     matthew  14352: =back 
                   14353: 
1.139     matthew  14354: =head1 Statistics helper routines?  
                   14355: 
                   14356: Bad place for them but what the hell.
                   14357: 
1.157     matthew  14358: =over 4
                   14359: 
1.648     raeburn  14360: =item * &chartlink()
1.139     matthew  14361: 
                   14362: Returns a link to the chart for a specific student.  
                   14363: 
                   14364: Inputs:
                   14365: 
                   14366: =over 4
                   14367: 
                   14368: =item $linktext: The text of the link
                   14369: 
                   14370: =item $sname: The students username
                   14371: 
                   14372: =item $sdomain: The students domain
                   14373: 
                   14374: =back
                   14375: 
1.157     matthew  14376: =back
                   14377: 
1.139     matthew  14378: =cut
                   14379: 
                   14380: ############################################################
                   14381: ############################################################
                   14382: sub chartlink {
                   14383:     my ($linktext, $sname, $sdomain) = @_;
                   14384:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14385:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14386:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14387:        '">'.$linktext.'</a>';
1.153     matthew  14388: }
                   14389: 
                   14390: #######################################################
                   14391: #######################################################
                   14392: 
                   14393: =pod
                   14394: 
                   14395: =head1 Course Environment Routines
1.157     matthew  14396: 
                   14397: =over 4
1.153     matthew  14398: 
1.648     raeburn  14399: =item * &restore_course_settings()
1.153     matthew  14400: 
1.648     raeburn  14401: =item * &store_course_settings()
1.153     matthew  14402: 
                   14403: Restores/Store indicated form parameters from the course environment.
                   14404: Will not overwrite existing values of the form parameters.
                   14405: 
                   14406: Inputs: 
                   14407: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14408: 
                   14409: a hash ref describing the data to be stored.  For example:
                   14410:    
                   14411: %Save_Parameters = ('Status' => 'scalar',
                   14412:     'chartoutputmode' => 'scalar',
                   14413:     'chartoutputdata' => 'scalar',
                   14414:     'Section' => 'array',
1.373     raeburn  14415:     'Group' => 'array',
1.153     matthew  14416:     'StudentData' => 'array',
                   14417:     'Maps' => 'array');
                   14418: 
                   14419: Returns: both routines return nothing
                   14420: 
1.631     raeburn  14421: =back
                   14422: 
1.153     matthew  14423: =cut
                   14424: 
                   14425: #######################################################
                   14426: #######################################################
                   14427: sub store_course_settings {
1.496     albertel 14428:     return &store_settings($env{'request.course.id'},@_);
                   14429: }
                   14430: 
                   14431: sub store_settings {
1.153     matthew  14432:     # save to the environment
                   14433:     # appenv the same items, just to be safe
1.300     albertel 14434:     my $udom  = $env{'user.domain'};
                   14435:     my $uname = $env{'user.name'};
1.496     albertel 14436:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14437:     my %SaveHash;
                   14438:     my %AppHash;
                   14439:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14440:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14441:         my $envname = 'environment.'.$basename;
1.258     albertel 14442:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14443:             # Save this value away
                   14444:             if ($type eq 'scalar' &&
1.258     albertel 14445:                 (! exists($env{$envname}) || 
                   14446:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14447:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14448:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14449:             } elsif ($type eq 'array') {
                   14450:                 my $stored_form;
1.258     albertel 14451:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14452:                     $stored_form = join(',',
                   14453:                                         map {
1.369     www      14454:                                             &escape($_);
1.258     albertel 14455:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14456:                 } else {
                   14457:                     $stored_form = 
1.369     www      14458:                         &escape($env{'form.'.$setting});
1.153     matthew  14459:                 }
                   14460:                 # Determine if the array contents are the same.
1.258     albertel 14461:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14462:                     $SaveHash{$basename} = $stored_form;
                   14463:                     $AppHash{$envname}   = $stored_form;
                   14464:                 }
                   14465:             }
                   14466:         }
                   14467:     }
                   14468:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14469:                                           $udom,$uname);
1.153     matthew  14470:     if ($put_result !~ /^(ok|delayed)/) {
                   14471:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14472:                                  'got error:'.$put_result);
                   14473:     }
                   14474:     # Make sure these settings stick around in this session, too
1.646     raeburn  14475:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14476:     return;
                   14477: }
                   14478: 
                   14479: sub restore_course_settings {
1.499     albertel 14480:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14481: }
                   14482: 
                   14483: sub restore_settings {
                   14484:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14485:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14486:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14487:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14488:             '.'.$setting;
1.258     albertel 14489:         if (exists($env{$envname})) {
1.153     matthew  14490:             if ($type eq 'scalar') {
1.258     albertel 14491:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14492:             } elsif ($type eq 'array') {
1.258     albertel 14493:                 $env{'form.'.$setting} = [ 
1.153     matthew  14494:                                            map { 
1.369     www      14495:                                                &unescape($_); 
1.258     albertel 14496:                                            } split(',',$env{$envname})
1.153     matthew  14497:                                            ];
                   14498:             }
                   14499:         }
                   14500:     }
1.127     matthew  14501: }
                   14502: 
1.618     raeburn  14503: #######################################################
                   14504: #######################################################
                   14505: 
                   14506: =pod
                   14507: 
                   14508: =head1 Domain E-mail Routines  
                   14509: 
                   14510: =over 4
                   14511: 
1.648     raeburn  14512: =item * &build_recipient_list()
1.618     raeburn  14513: 
1.1144    raeburn  14514: Build recipient lists for following types of e-mail:
1.766     raeburn  14515: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  14516: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14517: module change checking, student/employee ID conflict checks, as
                   14518: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14519: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14520: 
                   14521: Inputs:
1.619     raeburn  14522: defmail (scalar - email address of default recipient), 
1.1144    raeburn  14523: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14524: requestsmail, updatesmail, or idconflictsmail).
                   14525: 
1.619     raeburn  14526: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  14527: 
1.619     raeburn  14528: origmail (scalar - email address of recipient from loncapa.conf, 
                   14529: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  14530: 
1.655     raeburn  14531: Returns: comma separated list of addresses to which to send e-mail.
                   14532: 
                   14533: =back
1.618     raeburn  14534: 
                   14535: =cut
                   14536: 
                   14537: ############################################################
                   14538: ############################################################
                   14539: sub build_recipient_list {
1.619     raeburn  14540:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  14541:     my @recipients;
1.1270    raeburn  14542:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14543:     my %domconfig =
1.1270    raeburn  14544:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14545:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14546:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14547:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14548:                 my @contacts = ('adminemail','supportemail');
                   14549:                 foreach my $item (@contacts) {
                   14550:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14551:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14552:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14553:                             push(@recipients,$addr);
                   14554:                         }
1.619     raeburn  14555:                     }
1.1270    raeburn  14556:                 }
                   14557:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14558:                 if ($mailing eq 'helpdeskmail') {
                   14559:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14560:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14561:                         my @ok_bccs;
                   14562:                         foreach my $bcc (@bccs) {
                   14563:                             $bcc =~ s/^\s+//g;
                   14564:                             $bcc =~ s/\s+$//g;
                   14565:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14566:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14567:                                     push(@ok_bccs,$bcc);
                   14568:                                 }
                   14569:                             }
                   14570:                         }
                   14571:                         if (@ok_bccs > 0) {
                   14572:                             $allbcc = join(', ',@ok_bccs);
                   14573:                         }
                   14574:                     }
                   14575:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14576:                 }
                   14577:             }
1.766     raeburn  14578:         } elsif ($origmail ne '') {
1.1270    raeburn  14579:             $lastresort = $origmail;
1.618     raeburn  14580:         }
1.619     raeburn  14581:     } elsif ($origmail ne '') {
1.1270    raeburn  14582:         $lastresort = $origmail;
                   14583:     }
                   14584: 
                   14585:     if (($mailing eq 'helpdesk') && ($lastresort ne '')) {
                   14586:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14587:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14588:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14589:             my %what = (
                   14590:                           perlvar => 1,
                   14591:                        );
                   14592:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14593:             if ($primary) {
                   14594:                 my $gotaddr;
                   14595:                 my ($result,$returnhash) =
                   14596:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14597:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14598:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14599:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14600:                         $gotaddr = 1;
                   14601:                     }
                   14602:                 }
                   14603:                 unless ($gotaddr) {
                   14604:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14605:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14606:                     unless ($uintdom eq $intdom) {
                   14607:                         my %domconfig =
                   14608:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14609:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14610:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14611:                                 my @contacts = ('adminemail','supportemail');
                   14612:                                 foreach my $item (@contacts) {
                   14613:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14614:                                         my $addr = $domconfig{'contacts'}{$item};
                   14615:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14616:                                             push(@recipients,$addr);
                   14617:                                         }
                   14618:                                     }
                   14619:                                 }
                   14620:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14621:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14622:                                 }
                   14623:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14624:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14625:                                     my @ok_bccs;
                   14626:                                     foreach my $bcc (@bccs) {
                   14627:                                         $bcc =~ s/^\s+//g;
                   14628:                                         $bcc =~ s/\s+$//g;
                   14629:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14630:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14631:                                                 push(@ok_bccs,$bcc);
                   14632:                                             }
                   14633:                                         }
                   14634:                                     }
                   14635:                                     if (@ok_bccs > 0) {
                   14636:                                         $allbcc = join(', ',@ok_bccs);
                   14637:                                     }
                   14638:                                 }
                   14639:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14640:                             }
                   14641:                         }
                   14642:                     }
                   14643:                 }
                   14644:             }
                   14645:         }
1.618     raeburn  14646:     }
1.688     raeburn  14647:     if (defined($defmail)) {
                   14648:         if ($defmail ne '') {
                   14649:             push(@recipients,$defmail);
                   14650:         }
1.618     raeburn  14651:     }
                   14652:     if ($otheremails) {
1.619     raeburn  14653:         my @others;
                   14654:         if ($otheremails =~ /,/) {
                   14655:             @others = split(/,/,$otheremails);
1.618     raeburn  14656:         } else {
1.619     raeburn  14657:             push(@others,$otheremails);
                   14658:         }
                   14659:         foreach my $addr (@others) {
                   14660:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14661:                 push(@recipients,$addr);
                   14662:             }
1.618     raeburn  14663:         }
                   14664:     }
1.1270    raeburn  14665:     if ($mailing eq 'helpdesk') {
                   14666:         if ((!@recipients) && ($lastresort ne '')) {
                   14667:             push(@recipients,$lastresort);
                   14668:         }
                   14669:     } elsif ($lastresort ne '') {
                   14670:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14671:             push(@recipients,$lastresort);
                   14672:         }
                   14673:     }
1.1271    raeburn  14674:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  14675:     if (wantarray) {
                   14676:         return ($recipientlist,$allbcc,$addtext);
                   14677:     } else {
                   14678:         return $recipientlist;
                   14679:     }
1.618     raeburn  14680: }
                   14681: 
1.127     matthew  14682: ############################################################
                   14683: ############################################################
1.154     albertel 14684: 
1.655     raeburn  14685: =pod
                   14686: 
1.1224    musolffc 14687: =over 4
                   14688: 
1.1223    musolffc 14689: =item * &mime_email()
                   14690: 
                   14691: Sends an email with a possible attachment
                   14692: 
                   14693: Inputs:
                   14694: 
                   14695: =over 4
                   14696: 
                   14697: from -              Sender's email address
                   14698: 
                   14699: to -                Email address of recipient
                   14700: 
                   14701: subject -           Subject of email
                   14702: 
                   14703: body -              Body of email
                   14704: 
                   14705: cc_string -         Carbon copy email address
                   14706: 
                   14707: bcc -               Blind carbon copy email address
                   14708: 
                   14709: type -              File type of attachment
                   14710: 
                   14711: attachment_path -   Path of file to be attached
                   14712: 
                   14713: file_name -         Name of file to be attached
                   14714: 
                   14715: attachment_text -   The body of an attachment of type "TEXT"
                   14716: 
                   14717: =back
                   14718: 
                   14719: =back
                   14720: 
                   14721: =cut
                   14722: 
                   14723: ############################################################
                   14724: ############################################################
                   14725: 
                   14726: sub mime_email {
                   14727:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
                   14728:         $file_name, $attachment_text) = @_;
                   14729:     my $msg = MIME::Lite->new(
                   14730:              From    => $from,
                   14731:              To      => $to,
                   14732:              Subject => $subject,
                   14733:              Type    =>'TEXT',
                   14734:              Data    => $body,
                   14735:              );
                   14736:     if ($cc_string ne '') {
                   14737:         $msg->add("Cc" => $cc_string);
                   14738:     }
                   14739:     if ($bcc ne '') {
                   14740:         $msg->add("Bcc" => $bcc);
                   14741:     }
                   14742:     $msg->attr("content-type"         => "text/plain");
                   14743:     $msg->attr("content-type.charset" => "UTF-8");
                   14744:     # Attach file if given
                   14745:     if ($attachment_path) {
                   14746:         unless ($file_name) {
                   14747:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   14748:         }
                   14749:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   14750:         $msg->attach(Type     => $type,
                   14751:                      Path     => $attachment_path,
                   14752:                      Filename => $file_name
                   14753:                      );
                   14754:     # Otherwise attach text if given
                   14755:     } elsif ($attachment_text) {
                   14756:         $msg->attach(Type => 'TEXT',
                   14757:                      Data => $attachment_text);
                   14758:     }
                   14759:     # Send it
                   14760:     $msg->send('sendmail');
                   14761: }
                   14762: 
                   14763: ############################################################
                   14764: ############################################################
                   14765: 
                   14766: =pod
                   14767: 
1.655     raeburn  14768: =head1 Course Catalog Routines
                   14769: 
                   14770: =over 4
                   14771: 
                   14772: =item * &gather_categories()
                   14773: 
                   14774: Converts category definitions - keys of categories hash stored in  
                   14775: coursecategories in configuration.db on the primary library server in a 
                   14776: domain - to an array.  Also generates javascript and idx hash used to 
                   14777: generate Domain Coordinator interface for editing Course Categories.
                   14778: 
                   14779: Inputs:
1.663     raeburn  14780: 
1.655     raeburn  14781: categories (reference to hash of category definitions).
1.663     raeburn  14782: 
1.655     raeburn  14783: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14784:       categories and subcategories).
1.663     raeburn  14785: 
1.655     raeburn  14786: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14787:       editing Course Categories).
1.663     raeburn  14788: 
1.655     raeburn  14789: jsarray (reference to array of categories used to create Javascript arrays for
                   14790:          Domain Coordinator interface for editing Course Categories).
                   14791: 
                   14792: Returns: nothing
                   14793: 
                   14794: Side effects: populates cats, idx and jsarray. 
                   14795: 
                   14796: =cut
                   14797: 
                   14798: sub gather_categories {
                   14799:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14800:     my %counters;
                   14801:     my $num = 0;
                   14802:     foreach my $item (keys(%{$categories})) {
                   14803:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14804:         if ($container eq '' && $depth == 0) {
                   14805:             $cats->[$depth][$categories->{$item}] = $cat;
                   14806:         } else {
                   14807:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14808:         }
                   14809:         my ($escitem,$tail) = split(/:/,$item,2);
                   14810:         if ($counters{$tail} eq '') {
                   14811:             $counters{$tail} = $num;
                   14812:             $num ++;
                   14813:         }
                   14814:         if (ref($idx) eq 'HASH') {
                   14815:             $idx->{$item} = $counters{$tail};
                   14816:         }
                   14817:         if (ref($jsarray) eq 'ARRAY') {
                   14818:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14819:         }
                   14820:     }
                   14821:     return;
                   14822: }
                   14823: 
                   14824: =pod
                   14825: 
                   14826: =item * &extract_categories()
                   14827: 
                   14828: Used to generate breadcrumb trails for course categories.
                   14829: 
                   14830: Inputs:
1.663     raeburn  14831: 
1.655     raeburn  14832: categories (reference to hash of category definitions).
1.663     raeburn  14833: 
1.655     raeburn  14834: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14835:       categories and subcategories).
1.663     raeburn  14836: 
1.655     raeburn  14837: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14838: 
1.655     raeburn  14839: allitems (reference to hash - key is category key 
                   14840:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14841: 
1.655     raeburn  14842: idx (reference to hash of counters used in Domain Coordinator interface for
                   14843:       editing Course Categories).
1.663     raeburn  14844: 
1.655     raeburn  14845: jsarray (reference to array of categories used to create Javascript arrays for
                   14846:          Domain Coordinator interface for editing Course Categories).
                   14847: 
1.665     raeburn  14848: subcats (reference to hash of arrays containing all subcategories within each 
                   14849:          category, -recursive)
                   14850: 
1.655     raeburn  14851: Returns: nothing
                   14852: 
                   14853: Side effects: populates trails and allitems hash references.
                   14854: 
                   14855: =cut
                   14856: 
                   14857: sub extract_categories {
1.665     raeburn  14858:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  14859:     if (ref($categories) eq 'HASH') {
                   14860:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14861:         if (ref($cats->[0]) eq 'ARRAY') {
                   14862:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14863:                 my $name = $cats->[0][$i];
                   14864:                 my $item = &escape($name).'::0';
                   14865:                 my $trailstr;
                   14866:                 if ($name eq 'instcode') {
                   14867:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14868:                 } elsif ($name eq 'communities') {
                   14869:                     $trailstr = &mt('Communities');
1.1239    raeburn  14870:                 } elsif ($name eq 'placement') {
                   14871:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  14872:                 } else {
                   14873:                     $trailstr = $name;
                   14874:                 }
                   14875:                 if ($allitems->{$item} eq '') {
                   14876:                     push(@{$trails},$trailstr);
                   14877:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14878:                 }
                   14879:                 my @parents = ($name);
                   14880:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14881:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14882:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14883:                         if (ref($subcats) eq 'HASH') {
                   14884:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14885:                         }
                   14886:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   14887:                     }
                   14888:                 } else {
                   14889:                     if (ref($subcats) eq 'HASH') {
                   14890:                         $subcats->{$item} = [];
1.655     raeburn  14891:                     }
                   14892:                 }
                   14893:             }
                   14894:         }
                   14895:     }
                   14896:     return;
                   14897: }
                   14898: 
                   14899: =pod
                   14900: 
1.1162    raeburn  14901: =item * &recurse_categories()
1.655     raeburn  14902: 
                   14903: Recursively used to generate breadcrumb trails for course categories.
                   14904: 
                   14905: Inputs:
1.663     raeburn  14906: 
1.655     raeburn  14907: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14908:       categories and subcategories).
1.663     raeburn  14909: 
1.655     raeburn  14910: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14911: 
                   14912: category (current course category, for which breadcrumb trail is being generated).
                   14913: 
                   14914: trails (reference to array of breadcrumb trails for each category).
                   14915: 
1.655     raeburn  14916: allitems (reference to hash - key is category key
                   14917:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14918: 
1.655     raeburn  14919: parents (array containing containers directories for current category, 
                   14920:          back to top level). 
                   14921: 
                   14922: Returns: nothing
                   14923: 
                   14924: Side effects: populates trails and allitems hash references
                   14925: 
                   14926: =cut
                   14927: 
                   14928: sub recurse_categories {
1.665     raeburn  14929:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  14930:     my $shallower = $depth - 1;
                   14931:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14932:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14933:             my $name = $cats->[$depth]{$category}[$k];
                   14934:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14935:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14936:             if ($allitems->{$item} eq '') {
                   14937:                 push(@{$trails},$trailstr);
                   14938:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14939:             }
                   14940:             my $deeper = $depth+1;
                   14941:             push(@{$parents},$category);
1.665     raeburn  14942:             if (ref($subcats) eq 'HASH') {
                   14943:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14944:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14945:                     my $higher;
                   14946:                     if ($j > 0) {
                   14947:                         $higher = &escape($parents->[$j]).':'.
                   14948:                                   &escape($parents->[$j-1]).':'.$j;
                   14949:                     } else {
                   14950:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14951:                     }
                   14952:                     push(@{$subcats->{$higher}},$subcat);
                   14953:                 }
                   14954:             }
                   14955:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14956:                                 $subcats);
1.655     raeburn  14957:             pop(@{$parents});
                   14958:         }
                   14959:     } else {
                   14960:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14961:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14962:         if ($allitems->{$item} eq '') {
                   14963:             push(@{$trails},$trailstr);
                   14964:             $allitems->{$item} = scalar(@{$trails})-1;
                   14965:         }
                   14966:     }
                   14967:     return;
                   14968: }
                   14969: 
1.663     raeburn  14970: =pod
                   14971: 
1.1162    raeburn  14972: =item * &assign_categories_table()
1.663     raeburn  14973: 
                   14974: Create a datatable for display of hierarchical categories in a domain,
                   14975: with checkboxes to allow a course to be categorized. 
                   14976: 
                   14977: Inputs:
                   14978: 
                   14979: cathash - reference to hash of categories defined for the domain (from
                   14980:           configuration.db)
                   14981: 
                   14982: currcat - scalar with an & separated list of categories assigned to a course. 
                   14983: 
1.919     raeburn  14984: type    - scalar contains course type (Course or Community).
                   14985: 
1.1260    raeburn  14986: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14987:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14988: 
1.663     raeburn  14989: Returns: $output (markup to be displayed) 
                   14990: 
                   14991: =cut
                   14992: 
                   14993: sub assign_categories_table {
1.1259    raeburn  14994:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  14995:     my $output;
                   14996:     if (ref($cathash) eq 'HASH') {
                   14997:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   14998:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   14999:         $maxdepth = scalar(@cats);
                   15000:         if (@cats > 0) {
                   15001:             my $itemcount = 0;
                   15002:             if (ref($cats[0]) eq 'ARRAY') {
                   15003:                 my @currcategories;
                   15004:                 if ($currcat ne '') {
                   15005:                     @currcategories = split('&',$currcat);
                   15006:                 }
1.919     raeburn  15007:                 my $table;
1.663     raeburn  15008:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15009:                     my $parent = $cats[0][$i];
1.919     raeburn  15010:                     next if ($parent eq 'instcode');
                   15011:                     if ($type eq 'Community') {
                   15012:                         next unless ($parent eq 'communities');
1.1239    raeburn  15013:                     } elsif ($type eq 'Placement') {
                   15014:                         next unless ($parent eq 'placement');
1.919     raeburn  15015:                     } else {
1.1239    raeburn  15016:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  15017:                     }
1.663     raeburn  15018:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15019:                     my $item = &escape($parent).'::0';
                   15020:                     my $checked = '';
                   15021:                     if (@currcategories > 0) {
                   15022:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15023:                             $checked = ' checked="checked"';
1.663     raeburn  15024:                         }
                   15025:                     }
1.919     raeburn  15026:                     my $parent_title = $parent;
                   15027:                     if ($parent eq 'communities') {
                   15028:                         $parent_title = &mt('Communities');
1.1239    raeburn  15029:                     } elsif ($parent eq 'placement') {
                   15030:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  15031:                     }
                   15032:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15033:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15034:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15035:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15036:                     my $depth = 1;
                   15037:                     push(@path,$parent);
1.1259    raeburn  15038:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15039:                     pop(@path);
1.919     raeburn  15040:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15041:                     $itemcount ++;
                   15042:                 }
1.919     raeburn  15043:                 if ($itemcount) {
                   15044:                     $output = &Apache::loncommon::start_data_table().
                   15045:                               $table.
                   15046:                               &Apache::loncommon::end_data_table();
                   15047:                 }
1.663     raeburn  15048:             }
                   15049:         }
                   15050:     }
                   15051:     return $output;
                   15052: }
                   15053: 
                   15054: =pod
                   15055: 
1.1162    raeburn  15056: =item * &assign_category_rows()
1.663     raeburn  15057: 
                   15058: Create a datatable row for display of nested categories in a domain,
                   15059: with checkboxes to allow a course to be categorized,called recursively.
                   15060: 
                   15061: Inputs:
                   15062: 
                   15063: itemcount - track row number for alternating colors
                   15064: 
                   15065: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15066:       categories and subcategories.
                   15067: 
                   15068: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15069: 
                   15070: parent - parent of current category item
                   15071: 
                   15072: path - Array containing all categories back up through the hierarchy from the
                   15073:        current category to the top level.
                   15074: 
                   15075: currcategories - reference to array of current categories assigned to the course
                   15076: 
1.1260    raeburn  15077: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15078:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15079: 
1.663     raeburn  15080: Returns: $output (markup to be displayed).
                   15081: 
                   15082: =cut
                   15083: 
                   15084: sub assign_category_rows {
1.1259    raeburn  15085:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15086:     my ($text,$name,$item,$chgstr);
                   15087:     if (ref($cats) eq 'ARRAY') {
                   15088:         my $maxdepth = scalar(@{$cats});
                   15089:         if (ref($cats->[$depth]) eq 'HASH') {
                   15090:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15091:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15092:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  15093:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15094:                 for (my $j=0; $j<$numchildren; $j++) {
                   15095:                     $name = $cats->[$depth]{$parent}[$j];
                   15096:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15097:                     my $deeper = $depth+1;
                   15098:                     my $checked = '';
                   15099:                     if (ref($currcategories) eq 'ARRAY') {
                   15100:                         if (@{$currcategories} > 0) {
                   15101:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15102:                                 $checked = ' checked="checked"';
1.663     raeburn  15103:                             }
                   15104:                         }
                   15105:                     }
1.664     raeburn  15106:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15107:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15108:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15109:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15110:                              '</td><td>';
1.663     raeburn  15111:                     if (ref($path) eq 'ARRAY') {
                   15112:                         push(@{$path},$name);
1.1259    raeburn  15113:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15114:                         pop(@{$path});
                   15115:                     }
                   15116:                     $text .= '</td></tr>';
                   15117:                 }
                   15118:                 $text .= '</table></td>';
                   15119:             }
                   15120:         }
                   15121:     }
                   15122:     return $text;
                   15123: }
                   15124: 
1.1181    raeburn  15125: =pod
                   15126: 
                   15127: =back
                   15128: 
                   15129: =cut
                   15130: 
1.655     raeburn  15131: ############################################################
                   15132: ############################################################
                   15133: 
                   15134: 
1.443     albertel 15135: sub commit_customrole {
1.664     raeburn  15136:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15137:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15138:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15139:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15140:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15141:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15142:                  '</b><br />';
                   15143:     return $output;
                   15144: }
                   15145: 
                   15146: sub commit_standardrole {
1.1116    raeburn  15147:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15148:     my ($output,$logmsg,$linefeed);
                   15149:     if ($context eq 'auto') {
                   15150:         $linefeed = "\n";
                   15151:     } else {
                   15152:         $linefeed = "<br />\n";
                   15153:     }  
1.443     albertel 15154:     if ($three eq 'st') {
1.541     raeburn  15155:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  15156:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15157:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15158:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15159:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15160:         } else {
1.541     raeburn  15161:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15162:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15163:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15164:             if ($context eq 'auto') {
                   15165:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15166:             } else {
                   15167:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15168:                &mt('Add to classlist').': <b>ok</b>';
                   15169:             }
                   15170:             $output .= $linefeed;
1.443     albertel 15171:         }
                   15172:     } else {
                   15173:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15174:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15175:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15176:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15177:         if ($context eq 'auto') {
                   15178:             $output .= $result.$linefeed;
                   15179:         } else {
                   15180:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15181:         }
1.443     albertel 15182:     }
                   15183:     return $output;
                   15184: }
                   15185: 
                   15186: sub commit_studentrole {
1.1116    raeburn  15187:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15188:         $credits) = @_;
1.626     raeburn  15189:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15190:     if ($context eq 'auto') {
                   15191:         $linefeed = "\n";
                   15192:     } else {
                   15193:         $linefeed = '<br />'."\n";
                   15194:     }
1.443     albertel 15195:     if (defined($one) && defined($two)) {
                   15196:         my $cid=$one.'_'.$two;
                   15197:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15198:         my $secchange = 0;
                   15199:         my $expire_role_result;
                   15200:         my $modify_section_result;
1.628     raeburn  15201:         if ($oldsec ne '-1') { 
                   15202:             if ($oldsec ne $sec) {
1.443     albertel 15203:                 $secchange = 1;
1.628     raeburn  15204:                 my $now = time;
1.443     albertel 15205:                 my $uurl='/'.$cid;
                   15206:                 $uurl=~s/\_/\//g;
                   15207:                 if ($oldsec) {
                   15208:                     $uurl.='/'.$oldsec;
                   15209:                 }
1.626     raeburn  15210:                 $oldsecurl = $uurl;
1.628     raeburn  15211:                 $expire_role_result = 
1.652     raeburn  15212:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15213:                 if ($env{'request.course.sec'} ne '') { 
                   15214:                     if ($expire_role_result eq 'refused') {
                   15215:                         my @roles = ('st');
                   15216:                         my @statuses = ('previous');
                   15217:                         my @roledoms = ($one);
                   15218:                         my $withsec = 1;
                   15219:                         my %roleshash = 
                   15220:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15221:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15222:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15223:                             my ($oldstart,$oldend) = 
                   15224:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15225:                             if ($oldend > 0 && $oldend <= $now) {
                   15226:                                 $expire_role_result = 'ok';
                   15227:                             }
                   15228:                         }
                   15229:                     }
                   15230:                 }
1.443     albertel 15231:                 $result = $expire_role_result;
                   15232:             }
                   15233:         }
                   15234:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  15235:             $modify_section_result = 
                   15236:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15237:                                                            undef,undef,undef,$sec,
                   15238:                                                            $end,$start,'','',$cid,
                   15239:                                                            '',$context,$credits);
1.443     albertel 15240:             if ($modify_section_result =~ /^ok/) {
                   15241:                 if ($secchange == 1) {
1.628     raeburn  15242:                     if ($sec eq '') {
                   15243:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15244:                     } else {
                   15245:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15246:                     }
1.443     albertel 15247:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15248:                     if ($sec eq '') {
                   15249:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15250:                     } else {
                   15251:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15252:                     }
1.443     albertel 15253:                 } else {
1.628     raeburn  15254:                     if ($sec eq '') {
                   15255:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15256:                     } else {
                   15257:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15258:                     }
1.443     albertel 15259:                 }
                   15260:             } else {
1.1115    raeburn  15261:                 if ($secchange) { 
1.628     raeburn  15262:                     $$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;
                   15263:                 } else {
                   15264:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15265:                 }
1.443     albertel 15266:             }
                   15267:             $result = $modify_section_result;
                   15268:         } elsif ($secchange == 1) {
1.628     raeburn  15269:             if ($oldsec eq '') {
1.1103    raeburn  15270:                 $$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  15271:             } else {
                   15272:                 $$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;
                   15273:             }
1.626     raeburn  15274:             if ($expire_role_result eq 'refused') {
                   15275:                 my $newsecurl = '/'.$cid;
                   15276:                 $newsecurl =~ s/\_/\//g;
                   15277:                 if ($sec ne '') {
                   15278:                     $newsecurl.='/'.$sec;
                   15279:                 }
                   15280:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15281:                     if ($sec eq '') {
                   15282:                         $$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;
                   15283:                     } else {
                   15284:                         $$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;
                   15285:                     }
                   15286:                 }
                   15287:             }
1.443     albertel 15288:         }
                   15289:     } else {
1.626     raeburn  15290:         $$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 15291:         $result = "error: incomplete course id\n";
                   15292:     }
                   15293:     return $result;
                   15294: }
                   15295: 
1.1108    raeburn  15296: sub show_role_extent {
                   15297:     my ($scope,$context,$role) = @_;
                   15298:     $scope =~ s{^/}{};
                   15299:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15300:     push(@courseroles,'co');
                   15301:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15302:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15303:         $scope =~ s{/}{_};
                   15304:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15305:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15306:         my ($audom,$auname) = split(/\//,$scope);
                   15307:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15308:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15309:     } else {
                   15310:         $scope =~ s{/$}{};
                   15311:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15312:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15313:     }
                   15314: }
                   15315: 
1.443     albertel 15316: ############################################################
                   15317: ############################################################
                   15318: 
1.566     albertel 15319: sub check_clone {
1.578     raeburn  15320:     my ($args,$linefeed) = @_;
1.566     albertel 15321:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15322:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15323:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   15324:     my $clonemsg;
                   15325:     my $can_clone = 0;
1.944     raeburn  15326:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15327:     if ($lctype ne 'community') {
                   15328:         $lctype = 'course';
                   15329:     }
1.566     albertel 15330:     if ($clonehome eq 'no_host') {
1.944     raeburn  15331:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15332:             $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'});
                   15333:         } else {
                   15334:             $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'});
                   15335:         }     
1.566     albertel 15336:     } else {
                   15337: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  15338:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15339:             if ($clonedesc{'type'} ne 'Community') {
1.1262    raeburn  15340:                 $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'});
1.908     raeburn  15341:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15342:             }
                   15343:         }
1.1262    raeburn  15344: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15345:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15346: 	    $can_clone = 1;
                   15347: 	} else {
1.1221    raeburn  15348: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15349: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  15350:             if ($clonehash{'cloners'} eq '') {
                   15351:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15352:                 if ($domdefs{'canclone'}) {
                   15353:                     unless ($domdefs{'canclone'} eq 'none') {
                   15354:                         if ($domdefs{'canclone'} eq 'domain') {
                   15355:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15356:                                 $can_clone = 1;
                   15357:                             }
                   15358:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15359:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15360:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15361:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15362:                                 $can_clone = 1;
                   15363:                             }
                   15364:                         }
                   15365:                     }
                   15366:                 }
1.578     raeburn  15367:             } else {
1.1221    raeburn  15368: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15369:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15370:                     $can_clone = 1;
1.1221    raeburn  15371:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15372:                     $can_clone = 1;
1.1225    raeburn  15373:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15374:                     $can_clone = 1;
1.1221    raeburn  15375:                 }
                   15376:                 unless ($can_clone) {
1.1225    raeburn  15377:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15378:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  15379:                         my (%gotdomdefaults,%gotcodedefaults);
                   15380:                         foreach my $cloner (@cloners) {
                   15381:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15382:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15383:                                 my (%codedefaults,@code_order);
                   15384:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15385:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15386:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15387:                                     }
                   15388:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15389:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15390:                                     }
                   15391:                                 } else {
                   15392:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15393:                                                                             \%codedefaults,
                   15394:                                                                             \@code_order);
                   15395:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15396:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15397:                                 }
                   15398:                                 if (@code_order > 0) {
                   15399:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15400:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15401:                                                                                 $args->{'crscode'})) {
                   15402:                                         $can_clone = 1;
                   15403:                                         last;
                   15404:                                     }
                   15405:                                 }
                   15406:                             }
                   15407:                         }
                   15408:                     }
1.1225    raeburn  15409:                 }
                   15410:             }
                   15411:             unless ($can_clone) {
                   15412:                 my $ccrole = 'cc';
                   15413:                 if ($args->{'crstype'} eq 'Community') {
                   15414:                     $ccrole = 'co';
                   15415:                 }
                   15416: 	        my %roleshash =
                   15417: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15418: 					          $args->{'ccdomain'},
                   15419:                                                   'userroles',['active'],[$ccrole],
                   15420: 					          [$args->{'clonedomain'}]);
                   15421: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15422:                     $can_clone = 1;
                   15423:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15424:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15425:                     $can_clone = 1;
1.1221    raeburn  15426:                 }
                   15427:             }
                   15428:             unless ($can_clone) {
                   15429:                 if ($args->{'crstype'} eq 'Community') {
                   15430:                     $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'});
1.942     raeburn  15431:                 } else {
1.1221    raeburn  15432:                     $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'});
                   15433:                 }
1.566     albertel 15434: 	    }
1.578     raeburn  15435:         }
1.566     albertel 15436:     }
                   15437:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15438: }
                   15439: 
1.444     albertel 15440: sub construct_course {
1.1262    raeburn  15441:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   15442:         $cnum,$category,$coderef) = @_;
1.444     albertel 15443:     my $outcome;
1.541     raeburn  15444:     my $linefeed =  '<br />'."\n";
                   15445:     if ($context eq 'auto') {
                   15446:         $linefeed = "\n";
                   15447:     }
1.566     albertel 15448: 
                   15449: #
                   15450: # Are we cloning?
                   15451: #
                   15452:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15453:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  15454: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 15455: 	if ($context ne 'auto') {
1.578     raeburn  15456:             if ($clonemsg ne '') {
                   15457: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   15458:             }
1.566     albertel 15459: 	}
                   15460: 	$outcome .= $clonemsg.$linefeed;
                   15461: 
                   15462:         if (!$can_clone) {
                   15463: 	    return (0,$outcome);
                   15464: 	}
                   15465:     }
                   15466: 
1.444     albertel 15467: #
                   15468: # Open course
                   15469: #
1.1239    raeburn  15470:     my $showncrstype;
                   15471:     if ($args->{'crstype'} eq 'Placement') {
                   15472:         $showncrstype = 'placement test'; 
                   15473:     } else {  
                   15474:         $showncrstype = lc($args->{'crstype'});
                   15475:     }
1.444     albertel 15476:     my %cenv=();
                   15477:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15478:                                              $args->{'cdescr'},
                   15479:                                              $args->{'curl'},
                   15480:                                              $args->{'course_home'},
                   15481:                                              $args->{'nonstandard'},
                   15482:                                              $args->{'crscode'},
                   15483:                                              $args->{'ccuname'}.':'.
                   15484:                                              $args->{'ccdomain'},
1.882     raeburn  15485:                                              $args->{'crstype'},
1.885     raeburn  15486:                                              $cnum,$context,$category);
1.444     albertel 15487: 
                   15488:     # Note: The testing routines depend on this being output; see 
                   15489:     # Utils::Course. This needs to at least be output as a comment
                   15490:     # if anyone ever decides to not show this, and Utils::Course::new
                   15491:     # will need to be suitably modified.
1.1239    raeburn  15492:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
1.943     raeburn  15493:     if ($$courseid =~ /^error:/) {
                   15494:         return (0,$outcome);
                   15495:     }
                   15496: 
1.444     albertel 15497: #
                   15498: # Check if created correctly
                   15499: #
1.479     albertel 15500:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15501:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15502:     if ($crsuhome eq 'no_host') {
                   15503:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   15504:         return (0,$outcome);
                   15505:     }
1.541     raeburn  15506:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15507: 
1.444     albertel 15508: #
1.566     albertel 15509: # Do the cloning
                   15510: #   
                   15511:     if ($can_clone && $cloneid) {
1.1239    raeburn  15512: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
1.566     albertel 15513: 	if ($context ne 'auto') {
                   15514: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   15515: 	}
                   15516: 	$outcome .= $clonemsg.$linefeed;
                   15517: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15518: # Copy all files
1.637     www      15519: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 15520: # Restore URL
1.566     albertel 15521: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15522: # Restore title
1.566     albertel 15523: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15524: # Restore creation date, creator and creation context.
                   15525:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15526:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15527:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15528: # Mark as cloned
1.566     albertel 15529: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15530: # Need to clone grading mode
                   15531:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15532:         $cenv{'grading'}=$newenv{'grading'};
                   15533: # Do not clone these environment entries
                   15534:         &Apache::lonnet::del('environment',
                   15535:                   ['default_enrollment_start_date',
                   15536:                    'default_enrollment_end_date',
                   15537:                    'question.email',
                   15538:                    'policy.email',
                   15539:                    'comment.email',
                   15540:                    'pch.users.denied',
1.725     raeburn  15541:                    'plc.users.denied',
                   15542:                    'hidefromcat',
1.1121    raeburn  15543:                    'checkforpriv',
1.1166    raeburn  15544:                    'categories',
                   15545:                    'internal.uniquecode'],
1.638     www      15546:                    $$crsudom,$$crsunum);
1.1170    raeburn  15547:         if ($args->{'textbook'}) {
                   15548:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15549:         }
1.444     albertel 15550:     }
1.566     albertel 15551: 
1.444     albertel 15552: #
                   15553: # Set environment (will override cloned, if existing)
                   15554: #
                   15555:     my @sections = ();
                   15556:     my @xlists = ();
                   15557:     if ($args->{'crstype'}) {
                   15558:         $cenv{'type'}=$args->{'crstype'};
                   15559:     }
                   15560:     if ($args->{'crsid'}) {
                   15561:         $cenv{'courseid'}=$args->{'crsid'};
                   15562:     }
                   15563:     if ($args->{'crscode'}) {
                   15564:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15565:     }
                   15566:     if ($args->{'crsquota'} ne '') {
                   15567:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15568:     } else {
                   15569:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15570:     }
                   15571:     if ($args->{'ccuname'}) {
                   15572:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15573:                                         ':'.$args->{'ccdomain'};
                   15574:     } else {
                   15575:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15576:     }
1.1116    raeburn  15577:     if ($args->{'defaultcredits'}) {
                   15578:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15579:     }
1.444     albertel 15580:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15581:     if ($args->{'crssections'}) {
                   15582:         $cenv{'internal.sectionnums'} = '';
                   15583:         if ($args->{'crssections'} =~ m/,/) {
                   15584:             @sections = split/,/,$args->{'crssections'};
                   15585:         } else {
                   15586:             $sections[0] = $args->{'crssections'};
                   15587:         }
                   15588:         if (@sections > 0) {
                   15589:             foreach my $item (@sections) {
                   15590:                 my ($sec,$gp) = split/:/,$item;
                   15591:                 my $class = $args->{'crscode'}.$sec;
                   15592:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15593:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15594:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  15595:                     push(@badclasses,$class);
1.444     albertel 15596:                 }
                   15597:             }
                   15598:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15599:         }
                   15600:     }
                   15601: # do not hide course coordinator from staff listing, 
                   15602: # even if privileged
                   15603:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  15604: # add course coordinator's domain to domains to check for privileged users
                   15605: # if different to course domain
                   15606:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15607:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15608:     }
1.444     albertel 15609: # add crosslistings
                   15610:     if ($args->{'crsxlist'}) {
                   15611:         $cenv{'internal.crosslistings'}='';
                   15612:         if ($args->{'crsxlist'} =~ m/,/) {
                   15613:             @xlists = split/,/,$args->{'crsxlist'};
                   15614:         } else {
                   15615:             $xlists[0] = $args->{'crsxlist'};
                   15616:         }
                   15617:         if (@xlists > 0) {
                   15618:             foreach my $item (@xlists) {
                   15619:                 my ($xl,$gp) = split/:/,$item;
                   15620:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15621:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15622:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  15623:                     push(@badclasses,$xl);
1.444     albertel 15624:                 }
                   15625:             }
                   15626:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15627:         }
                   15628:     }
                   15629:     if ($args->{'autoadds'}) {
                   15630:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15631:     }
                   15632:     if ($args->{'autodrops'}) {
                   15633:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15634:     }
                   15635: # check for notification of enrollment changes
                   15636:     my @notified = ();
                   15637:     if ($args->{'notify_owner'}) {
                   15638:         if ($args->{'ccuname'} ne '') {
                   15639:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15640:         }
                   15641:     }
                   15642:     if ($args->{'notify_dc'}) {
                   15643:         if ($uname ne '') { 
1.630     raeburn  15644:             push(@notified,$uname.':'.$udom);
1.444     albertel 15645:         }
                   15646:     }
                   15647:     if (@notified > 0) {
                   15648:         my $notifylist;
                   15649:         if (@notified > 1) {
                   15650:             $notifylist = join(',',@notified);
                   15651:         } else {
                   15652:             $notifylist = $notified[0];
                   15653:         }
                   15654:         $cenv{'internal.notifylist'} = $notifylist;
                   15655:     }
                   15656:     if (@badclasses > 0) {
                   15657:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  15658:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15659:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15660:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15661:         );
1.1264    raeburn  15662:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15663:                            &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  15664:         if ($context eq 'auto') {
                   15665:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  15666:         } else {
1.566     albertel 15667:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  15668:         }
                   15669:         foreach my $item (@badclasses) {
1.541     raeburn  15670:             if ($context eq 'auto') {
1.1261    raeburn  15671:                 $outcome .= " - $item\n";
1.541     raeburn  15672:             } else {
1.1261    raeburn  15673:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15674:             }
1.1261    raeburn  15675:         }
                   15676:         if ($context eq 'auto') {
                   15677:             $outcome .= $linefeed;
                   15678:         } else {
                   15679:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  15680:         } 
1.444     albertel 15681:     }
                   15682:     if ($args->{'no_end_date'}) {
                   15683:         $args->{'endaccess'} = 0;
                   15684:     }
                   15685:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15686:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15687:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15688:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15689:     if ($args->{'showphotos'}) {
                   15690:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15691:     }
                   15692:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15693:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15694:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15695:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15696:             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'); 
                   15697:             if ($context eq 'auto') {
                   15698:                 $outcome .= $krb_msg;
                   15699:             } else {
1.566     albertel 15700:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15701:             }
                   15702:             $outcome .= $linefeed;
1.444     albertel 15703:         }
                   15704:     }
                   15705:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15706:        if ($args->{'setpolicy'}) {
                   15707:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15708:        }
                   15709:        if ($args->{'setcontent'}) {
                   15710:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15711:        }
1.1251    raeburn  15712:        if ($args->{'setcomment'}) {
                   15713:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15714:        }
1.444     albertel 15715:     }
                   15716:     if ($args->{'reshome'}) {
                   15717: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15718: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15719:     }
                   15720: #
                   15721: # course has keyed access
                   15722: #
                   15723:     if ($args->{'setkeys'}) {
                   15724:        $cenv{'keyaccess'}='yes';
                   15725:     }
                   15726: # if specified, key authority is not course, but user
                   15727: # only active if keyaccess is yes
                   15728:     if ($args->{'keyauth'}) {
1.487     albertel 15729: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15730: 	$user = &LONCAPA::clean_username($user);
                   15731: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15732: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15733: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15734: 	}
                   15735:     }
                   15736: 
1.1166    raeburn  15737: #
1.1167    raeburn  15738: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  15739: #
                   15740:     if ($args->{'uniquecode'}) {
                   15741:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15742:         if ($code) {
                   15743:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  15744:             my %crsinfo =
                   15745:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15746:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15747:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15748:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15749:             } 
1.1166    raeburn  15750:             if (ref($coderef)) {
                   15751:                 $$coderef = $code;
                   15752:             }
                   15753:         }
                   15754:     }
                   15755: 
1.444     albertel 15756:     if ($args->{'disresdis'}) {
                   15757:         $cenv{'pch.roles.denied'}='st';
                   15758:     }
                   15759:     if ($args->{'disablechat'}) {
                   15760:         $cenv{'plc.roles.denied'}='st';
                   15761:     }
                   15762: 
                   15763:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15764:     # course
                   15765:     $cenv{'course.helper.not.run'} = 1;
                   15766:     #
                   15767:     # Use new Randomseed
                   15768:     #
                   15769:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15770:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15771:     #
                   15772:     # The encryption code and receipt prefix for this course
                   15773:     #
                   15774:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15775:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15776:     #
                   15777:     # By default, use standard grading
                   15778:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15779: 
1.541     raeburn  15780:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15781:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15782: #
                   15783: # Open all assignments
                   15784: #
                   15785:     if ($args->{'openall'}) {
                   15786:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   15787:        my %storecontent = ($storeunder         => time,
                   15788:                            $storeunder.'.type' => 'date_start');
                   15789:        
                   15790:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  15791:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15792:    }
                   15793: #
                   15794: # Set first page
                   15795: #
                   15796:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15797: 	    || ($cloneid)) {
1.445     albertel 15798: 	use LONCAPA::map;
1.444     albertel 15799: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15800: 
                   15801: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15802:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15803: 
1.444     albertel 15804:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15805:         my $title; my $url;
                   15806:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15807: 	    $title=&mt('Syllabus');
1.444     albertel 15808:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15809:         } else {
1.963     raeburn  15810:             $title=&mt('Table of Contents');
1.444     albertel 15811:             $url='/adm/navmaps';
                   15812:         }
1.445     albertel 15813: 
                   15814:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15815: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15816: 
                   15817: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15818:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15819:     }
1.566     albertel 15820: 
1.1237    raeburn  15821: # 
                   15822: # Set params for Placement Tests
                   15823: #
1.1239    raeburn  15824:     if ($args->{'crstype'} eq 'Placement') {
                   15825:        my %storecontent; 
                   15826:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   15827:        my %defaults = (
                   15828:                         buttonshide   => { value => 'yes',
                   15829:                                            type => 'string_yesno',},
                   15830:                         type          => { value => 'randomizetry',
                   15831:                                            type  => 'string_questiontype',},
                   15832:                         maxtries      => { value => 1,
                   15833:                                            type => 'int_pos',},
                   15834:                         problemstatus => { value => 'no',
                   15835:                                            type  => 'string_problemstatus',},
                   15836:                       );
                   15837:        foreach my $key (keys(%defaults)) {
                   15838:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   15839:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   15840:        }
1.1237    raeburn  15841:        &Apache::lonnet::cput
                   15842:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   15843:     }
                   15844: 
1.566     albertel 15845:     return (1,$outcome);
1.444     albertel 15846: }
                   15847: 
1.1166    raeburn  15848: sub make_unique_code {
                   15849:     my ($cdom,$cnum) = @_;
                   15850:     # get lock on uniquecodes db
                   15851:     my $lockhash = {
                   15852:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15853:                                                   ':'.$env{'user.domain'},
                   15854:                    };
                   15855:     my $tries = 0;
                   15856:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15857:     my ($code,$error);
                   15858:   
                   15859:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15860:         $tries ++;
                   15861:         sleep 1;
                   15862:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15863:     }
                   15864:     if ($gotlock eq 'ok') {
                   15865:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15866:         my $gotcode;
                   15867:         my $attempts = 0;
                   15868:         while ((!$gotcode) && ($attempts < 100)) {
                   15869:             $code = &generate_code();
                   15870:             if (!exists($currcodes{$code})) {
                   15871:                 $gotcode = 1;
                   15872:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15873:                     $error = 'nostore';
                   15874:                 }
                   15875:             }
                   15876:             $attempts ++;
                   15877:         }
                   15878:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15879:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15880:     } else {
                   15881:         $error = 'nolock';
                   15882:     }
                   15883:     return ($code,$error);
                   15884: }
                   15885: 
                   15886: sub generate_code {
                   15887:     my $code;
                   15888:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15889:     for (my $i=0; $i<6; $i++) {
                   15890:         my $lettnum = int (rand 2);
                   15891:         my $item = '';
                   15892:         if ($lettnum) {
                   15893:             $item = $letts[int( rand(18) )];
                   15894:         } else {
                   15895:             $item = 1+int( rand(8) );
                   15896:         }
                   15897:         $code .= $item;
                   15898:     }
                   15899:     return $code;
                   15900: }
                   15901: 
1.444     albertel 15902: ############################################################
                   15903: ############################################################
                   15904: 
1.1237    raeburn  15905: # Community, Course and Placement Test
1.378     raeburn  15906: sub course_type {
                   15907:     my ($cid) = @_;
                   15908:     if (!defined($cid)) {
                   15909:         $cid = $env{'request.course.id'};
                   15910:     }
1.404     albertel 15911:     if (defined($env{'course.'.$cid.'.type'})) {
                   15912:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15913:     } else {
                   15914:         return 'Course';
1.377     raeburn  15915:     }
                   15916: }
1.156     albertel 15917: 
1.406     raeburn  15918: sub group_term {
                   15919:     my $crstype = &course_type();
                   15920:     my %names = (
                   15921:                   'Course' => 'group',
1.865     raeburn  15922:                   'Community' => 'group',
1.1237    raeburn  15923:                   'Placement' => 'group',
1.406     raeburn  15924:                 );
                   15925:     return $names{$crstype};
                   15926: }
                   15927: 
1.902     raeburn  15928: sub course_types {
1.1237    raeburn  15929:     my @types = ('official','unofficial','community','textbook','placement');
1.902     raeburn  15930:     my %typename = (
                   15931:                          official   => 'Official course',
                   15932:                          unofficial => 'Unofficial course',
                   15933:                          community  => 'Community',
1.1165    raeburn  15934:                          textbook   => 'Textbook course',
1.1237    raeburn  15935:                          placement  => 'Placement test',
1.902     raeburn  15936:                    );
                   15937:     return (\@types,\%typename);
                   15938: }
                   15939: 
1.156     albertel 15940: sub icon {
                   15941:     my ($file)=@_;
1.505     albertel 15942:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15943:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15944:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15945:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15946: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15947: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15948: 	            $curfext.".gif") {
                   15949: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15950: 		$curfext.".gif";
                   15951: 	}
                   15952:     }
1.249     albertel 15953:     return &lonhttpdurl($iconname);
1.154     albertel 15954: } 
1.84      albertel 15955: 
1.575     albertel 15956: sub lonhttpdurl {
1.692     www      15957: #
                   15958: # Had been used for "small fry" static images on separate port 8080.
                   15959: # Modify here if lightweight http functionality desired again.
                   15960: # Currently eliminated due to increasing firewall issues.
                   15961: #
1.575     albertel 15962:     my ($url)=@_;
1.692     www      15963:     return $url;
1.215     albertel 15964: }
                   15965: 
1.213     albertel 15966: sub connection_aborted {
                   15967:     my ($r)=@_;
                   15968:     $r->print(" ");$r->rflush();
                   15969:     my $c = $r->connection;
                   15970:     return $c->aborted();
                   15971: }
                   15972: 
1.221     foxr     15973: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15974: #    strings as 'strings'.
                   15975: sub escape_single {
1.221     foxr     15976:     my ($input) = @_;
1.223     albertel 15977:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15978:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15979:     return $input;
                   15980: }
1.223     albertel 15981: 
1.222     foxr     15982: #  Same as escape_single, but escape's "'s  This 
                   15983: #  can be used for  "strings"
                   15984: sub escape_double {
                   15985:     my ($input) = @_;
                   15986:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15987:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15988:     return $input;
                   15989: }
1.223     albertel 15990:  
1.222     foxr     15991: #   Escapes the last element of a full URL.
                   15992: sub escape_url {
                   15993:     my ($url)   = @_;
1.238     raeburn  15994:     my @urlslices = split(/\//, $url,-1);
1.369     www      15995:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  15996:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15997: }
1.462     albertel 15998: 
1.820     raeburn  15999: sub compare_arrays {
                   16000:     my ($arrayref1,$arrayref2) = @_;
                   16001:     my (@difference,%count);
                   16002:     @difference = ();
                   16003:     %count = ();
                   16004:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16005:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16006:         foreach my $element (keys(%count)) {
                   16007:             if ($count{$element} == 1) {
                   16008:                 push(@difference,$element);
                   16009:             }
                   16010:         }
                   16011:     }
                   16012:     return @difference;
                   16013: }
                   16014: 
1.817     bisitz   16015: # -------------------------------------------------------- Initialize user login
1.462     albertel 16016: sub init_user_environment {
1.463     albertel 16017:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 16018:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   16019: 
                   16020:     my $public=($username eq 'public' && $domain eq 'public');
                   16021: 
1.1062    raeburn  16022:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 16023:     my $now=time;
                   16024: 
                   16025:     if ($public) {
                   16026: 	my $max_public=100;
                   16027: 	my $oldest;
                   16028: 	my $oldest_time=0;
                   16029: 	for(my $next=1;$next<=$max_public;$next++) {
                   16030: 	    if (-e $lonids."/publicuser_$next.id") {
                   16031: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   16032: 		if ($mtime<$oldest_time || !$oldest_time) {
                   16033: 		    $oldest_time=$mtime;
                   16034: 		    $oldest=$next;
                   16035: 		}
                   16036: 	    } else {
                   16037: 		$cookie="publicuser_$next";
                   16038: 		last;
                   16039: 	    }
                   16040: 	}
                   16041: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16042:     } else {
1.1275    raeburn  16043: 	# See if old ID present, if so, remove if this isn't a robot,
                   16044: 	# killing any existing non-robot sessions
1.463     albertel 16045: 	if (!$args->{'robot'}) {
                   16046: 	    opendir(DIR,$lonids);
                   16047: 	    while ($filename=readdir(DIR)) {
                   16048: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   16049: 		    unlink($lonids.'/'.$filename);
                   16050: 		}
1.462     albertel 16051: 	    }
1.463     albertel 16052: 	    closedir(DIR);
1.1204    raeburn  16053: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16054:             my $namespace = 'nohist_courseeditor';
                   16055:             my $lockingkey = 'paste'."\0".'locked_num';
                   16056:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16057:                                                 $domain,$username);
                   16058:             if (exists($lockhash{$lockingkey})) {
                   16059:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16060:                 unless ($delresult eq 'ok') {
                   16061:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16062:                 }
                   16063:             }
1.462     albertel 16064: 	}
                   16065: # Give them a new cookie
1.463     albertel 16066: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16067: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16068: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16069:     
                   16070: # Initialize roles
                   16071: 
1.1062    raeburn  16072: 	($userroles,$firstaccenv,$timerintenv) = 
                   16073:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16074:     }
                   16075: # ------------------------------------ Check browser type and MathML capability
                   16076: 
1.1194    raeburn  16077:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   16078:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 16079: 
                   16080: # ------------------------------------------------------------- Get environment
                   16081: 
                   16082:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   16083:     my ($tmp) = keys(%userenv);
1.1275    raeburn  16084:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 16085: 	undef(%userenv);
                   16086:     }
                   16087:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   16088: 	$form->{'interface'}=$userenv{'interface'};
                   16089:     }
                   16090:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   16091: 
                   16092: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   16093:     foreach my $option ('interface','localpath','localres') {
                   16094:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 16095:     }
                   16096: # --------------------------------------------------------- Write first profile
                   16097: 
                   16098:     {
                   16099: 	my %initial_env = 
                   16100: 	    ("user.name"          => $username,
                   16101: 	     "user.domain"        => $domain,
                   16102: 	     "user.home"          => $authhost,
                   16103: 	     "browser.type"       => $clientbrowser,
                   16104: 	     "browser.version"    => $clientversion,
                   16105: 	     "browser.mathml"     => $clientmathml,
                   16106: 	     "browser.unicode"    => $clientunicode,
                   16107: 	     "browser.os"         => $clientos,
1.1137    raeburn  16108:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  16109:              "browser.info"       => $clientinfo,
1.1194    raeburn  16110:              "browser.osversion"  => $clientosversion,
1.462     albertel 16111: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   16112: 	     "request.course.fn"  => '',
                   16113: 	     "request.course.uri" => '',
                   16114: 	     "request.course.sec" => '',
                   16115: 	     "request.role"       => 'cm',
                   16116: 	     "request.role.adv"   => $env{'user.adv'},
                   16117: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   16118: 
                   16119:         if ($form->{'localpath'}) {
                   16120: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   16121: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   16122:         }
                   16123: 	
                   16124: 	if ($form->{'interface'}) {
                   16125: 	    $form->{'interface'}=~s/\W//gs;
                   16126: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   16127: 	    $env{'browser.interface'}=$form->{'interface'};
                   16128: 	}
                   16129: 
1.1157    raeburn  16130:         if ($form->{'iptoken'}) {
                   16131:             my $lonhost = $r->dir_config('lonHostID');
                   16132:             $initial_env{"user.noloadbalance"} = $lonhost;
                   16133:             $env{'user.noloadbalance'} = $lonhost;
                   16134:         }
                   16135: 
1.1268    raeburn  16136:         if ($form->{'noloadbalance'}) {
                   16137:             my @hosts = &Apache::lonnet::current_machine_ids();
                   16138:             my $hosthere = $form->{'noloadbalance'};
                   16139:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   16140:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   16141:                 $env{'user.noloadbalance'} = $hosthere;
                   16142:             }
                   16143:         }
                   16144: 
1.1016    raeburn  16145:         unless ($domain eq 'public') {
1.1273    raeburn  16146:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   16147:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   16148: 
                   16149:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   16150:                 $userenv{'availabletools.'.$tool} = 
                   16151:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16152:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   16153:             }
1.980     raeburn  16154: 
1.1273    raeburn  16155:             foreach my $crstype ('official','unofficial','community','textbook','placement') {
                   16156:                 $userenv{'canrequest.'.$crstype} =
                   16157:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   16158:                                                       'reload','requestcourses',
                   16159:                                                       \%userenv,\%domdef,\%is_adv);
                   16160:             }
1.724     raeburn  16161: 
1.1273    raeburn  16162:             $userenv{'canrequest.author'} =
                   16163:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16164:                                                   'reload','requestauthor',
1.980     raeburn  16165:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  16166:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16167:                                                  $domain,$username);
                   16168:             my $reqstatus = $reqauthor{'author_status'};
                   16169:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   16170:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   16171:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16172:                                                       $reqauthor{'author'}{'timestamp'};
                   16173:                 }
1.1092    raeburn  16174:             }
                   16175:         }
                   16176: 
1.462     albertel 16177: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16178: 
1.462     albertel 16179: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16180: 		 &GDBM_WRCREAT(),0640)) {
                   16181: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16182: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16183: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16184:             if (ref($firstaccenv) eq 'HASH') {
                   16185:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16186:             }
                   16187:             if (ref($timerintenv) eq 'HASH') {
                   16188:                 &_add_to_env(\%disk_env,$timerintenv);
                   16189:             }
1.463     albertel 16190: 	    if (ref($args->{'extra_env'})) {
                   16191: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16192: 	    }
1.462     albertel 16193: 	    untie(%disk_env);
                   16194: 	} else {
1.705     tempelho 16195: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16196: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16197: 	    return 'error: '.$!;
                   16198: 	}
                   16199:     }
                   16200:     $env{'request.role'}='cm';
                   16201:     $env{'request.role.adv'}=$env{'user.adv'};
                   16202:     $env{'browser.type'}=$clientbrowser;
                   16203: 
                   16204:     return $cookie;
                   16205: 
                   16206: }
                   16207: 
                   16208: sub _add_to_env {
                   16209:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16210:     if (ref($env_data) eq 'HASH') {
                   16211:         while (my ($key,$value) = each(%$env_data)) {
                   16212: 	    $idf->{$prefix.$key} = $value;
                   16213: 	    $env{$prefix.$key}   = $value;
                   16214:         }
1.462     albertel 16215:     }
                   16216: }
                   16217: 
1.685     tempelho 16218: # --- Get the symbolic name of a problem and the url
                   16219: sub get_symb {
                   16220:     my ($request,$silent) = @_;
1.726     raeburn  16221:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16222:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16223:     if ($symb eq '') {
                   16224:         if (!$silent) {
1.1071    raeburn  16225:             if (ref($request)) { 
                   16226:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16227:             }
1.685     tempelho 16228:             return ();
                   16229:         }
                   16230:     }
                   16231:     &Apache::lonenc::check_decrypt(\$symb);
                   16232:     return ($symb);
                   16233: }
                   16234: 
                   16235: # --------------------------------------------------------------Get annotation
                   16236: 
                   16237: sub get_annotation {
                   16238:     my ($symb,$enc) = @_;
                   16239: 
                   16240:     my $key = $symb;
                   16241:     if (!$enc) {
                   16242:         $key =
                   16243:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16244:     }
                   16245:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16246:     return $annotation{$key};
                   16247: }
                   16248: 
                   16249: sub clean_symb {
1.731     raeburn  16250:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16251: 
                   16252:     &Apache::lonenc::check_decrypt(\$symb);
                   16253:     my $enc = $env{'request.enc'};
1.731     raeburn  16254:     if ($delete_enc) {
1.730     raeburn  16255:         delete($env{'request.enc'});
                   16256:     }
1.685     tempelho 16257: 
                   16258:     return ($symb,$enc);
                   16259: }
1.462     albertel 16260: 
1.1181    raeburn  16261: ############################################################
                   16262: ############################################################
                   16263: 
                   16264: =pod
                   16265: 
                   16266: =head1 Routines for building display used to search for courses
                   16267: 
                   16268: 
                   16269: =over 4
                   16270: 
                   16271: =item * &build_filters()
                   16272: 
                   16273: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  16274: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16275: and quotacheck.pl
                   16276: 
1.1181    raeburn  16277: 
                   16278: Inputs:
                   16279: 
                   16280: filterlist - anonymous array of fields to include as potential filters 
                   16281: 
                   16282: crstype - course type
                   16283: 
                   16284: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16285:               to pop-open a course selector (will contain "extra element"). 
                   16286: 
                   16287: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16288: 
                   16289: filter - anonymous hash of criteria and their values
                   16290: 
                   16291: action - form action
                   16292: 
                   16293: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16294: 
1.1182    raeburn  16295: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  16296: 
                   16297: cloneruname - username of owner of new course who wants to clone
                   16298: 
                   16299: clonerudom - domain of owner of new course who wants to clone
                   16300: 
                   16301: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   16302: 
                   16303: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16304: 
                   16305: codedom - domain
                   16306: 
                   16307: formname - value of form element named "form". 
                   16308: 
                   16309: fixeddom - domain, if fixed.
                   16310: 
                   16311: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   16312: 
                   16313: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   16314: 
                   16315: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16316: 
                   16317: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16318: 
                   16319: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16320: 
                   16321: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16322: 
                   16323: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16324: 
1.1182    raeburn  16325: 
1.1181    raeburn  16326: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16327: 
1.1182    raeburn  16328: 
1.1181    raeburn  16329: Side Effects: None
                   16330: 
                   16331: =cut
                   16332: 
                   16333: # ---------------------------------------------- search for courses based on last activity etc.
                   16334: 
                   16335: sub build_filters {
                   16336:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16337:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16338:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16339:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16340:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  16341:     my ($list,$jscript);
1.1181    raeburn  16342:     my $onchange = 'javascript:updateFilters(this)';
                   16343:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16344:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16345:         $typeselectform,$instcodetitle);
                   16346:     if ($formname eq '') {
                   16347:         $formname = $caller;
                   16348:     }
                   16349:     foreach my $item (@{$filterlist}) {
                   16350:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16351:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16352:             if ($item eq 'domainfilter') {
                   16353:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16354:             } elsif ($item eq 'coursefilter') {
                   16355:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16356:             } elsif ($item eq 'ownerfilter') {
                   16357:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16358:             } elsif ($item eq 'ownerdomfilter') {
                   16359:                 $filter->{'ownerdomfilter'} =
                   16360:                     &LONCAPA::clean_domain($filter->{$item});
                   16361:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16362:                                                        'ownerdomfilter',1);
                   16363:             } elsif ($item eq 'personfilter') {
                   16364:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16365:             } elsif ($item eq 'persondomfilter') {
                   16366:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16367:                                                         'persondomfilter',1);
                   16368:             } else {
                   16369:                 $filter->{$item} =~ s/\W//g;
                   16370:             }
                   16371:             if (!$filter->{$item}) {
                   16372:                 $filter->{$item} = '';
                   16373:             }
                   16374:         }
                   16375:         if ($item eq 'domainfilter') {
                   16376:             my $allow_blank = 1;
                   16377:             if ($formname eq 'portform') {
                   16378:                 $allow_blank=0;
                   16379:             } elsif ($formname eq 'studentform') {
                   16380:                 $allow_blank=0;
                   16381:             }
                   16382:             if ($fixeddom) {
                   16383:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16384:                                     ' value="'.$codedom.'" />'.
                   16385:                                     &Apache::lonnet::domain($codedom,'description');
                   16386:             } else {
                   16387:                 $domainselectform = &select_dom_form($filter->{$item},
                   16388:                                                      'domainfilter',
                   16389:                                                       $allow_blank,'',$onchange);
                   16390:             }
                   16391:         } else {
                   16392:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16393:         }
                   16394:     }
                   16395: 
                   16396:     # last course activity filter and selection
                   16397:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16398: 
                   16399:     # course created filter and selection
                   16400:     if (exists($filter->{'createdfilter'})) {
                   16401:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16402:     }
                   16403: 
1.1239    raeburn  16404:     my $prefix = $crstype;
                   16405:     if ($crstype eq 'Placement') {
                   16406:         $prefix = 'Placement Test'
                   16407:     }
1.1181    raeburn  16408:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  16409:                 'cac' => "$prefix Activity",
                   16410:                 'ccr' => "$prefix Created",
                   16411:                 'cde' => "$prefix Title",
                   16412:                 'cdo' => "$prefix Domain",
1.1181    raeburn  16413:                 'ins' => 'Institutional Code',
                   16414:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  16415:                 'cow' => "$prefix Owner/Co-owner",
                   16416:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  16417:                 'cog' => 'Type',
                   16418:              );
                   16419: 
                   16420:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16421:         my $typeval = 'Course';
                   16422:         if ($crstype eq 'Community') {
                   16423:             $typeval = 'Community';
1.1239    raeburn  16424:         } elsif ($crstype eq 'Placement') {
                   16425:             $typeval = 'Placement';
1.1181    raeburn  16426:         }
                   16427:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16428:     } else {
                   16429:         $typeselectform =  '<select name="type" size="1"';
                   16430:         if ($onchange) {
                   16431:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16432:         }
                   16433:         $typeselectform .= '>'."\n";
1.1237    raeburn  16434:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  16435:             my $shown;
                   16436:             if ($posstype eq 'Placement') {
                   16437:                 $shown = &mt('Placement Test');
                   16438:             } else {
                   16439:                 $shown = &mt($posstype);
                   16440:             }
1.1181    raeburn  16441:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  16442:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  16443:         }
                   16444:         $typeselectform.="</select>";
                   16445:     }
                   16446: 
                   16447:     my ($cloneableonlyform,$cloneabletitle);
                   16448:     if (exists($filter->{'cloneableonly'})) {
                   16449:         my $cloneableon = '';
                   16450:         my $cloneableoff = ' checked="checked"';
                   16451:         if ($filter->{'cloneableonly'}) {
                   16452:             $cloneableon = $cloneableoff;
                   16453:             $cloneableoff = '';
                   16454:         }
                   16455:         $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>';
                   16456:         if ($formname eq 'ccrs') {
1.1187    bisitz   16457:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  16458:         } else {
                   16459:             $cloneabletitle = &mt('Cloneable by you');
                   16460:         }
                   16461:     }
                   16462:     my $officialjs;
                   16463:     if ($crstype eq 'Course') {
                   16464:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  16465: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16466: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16467:             if ($codedom) { 
1.1181    raeburn  16468:                 $officialjs = 1;
                   16469:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16470:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16471:                                                                   $officialjs,$codetitlesref);
                   16472:                 if ($jscript) {
1.1182    raeburn  16473:                     $jscript = '<script type="text/javascript">'."\n".
                   16474:                                '// <![CDATA['."\n".
                   16475:                                $jscript."\n".
                   16476:                                '// ]]>'."\n".
                   16477:                                '</script>'."\n";
1.1181    raeburn  16478:                 }
                   16479:             }
                   16480:             if ($instcodeform eq '') {
                   16481:                 $instcodeform =
                   16482:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16483:                     $list->{'instcodefilter'}.'" />';
                   16484:                 $instcodetitle = $lt{'ins'};
                   16485:             } else {
                   16486:                 $instcodetitle = $lt{'inc'};
                   16487:             }
                   16488:             if ($fixeddom) {
                   16489:                 $instcodetitle .= '<br />('.$codedom.')';
                   16490:             }
                   16491:         }
                   16492:     }
                   16493:     my $output = qq|
                   16494: <form method="post" name="filterpicker" action="$action">
                   16495: <input type="hidden" name="form" value="$formname" />
                   16496: |;
                   16497:     if ($formname eq 'modifycourse') {
                   16498:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16499:                    '<input type="hidden" name="prevphase" value="'.
                   16500:                    $prevphase.'" />'."\n";
1.1198    musolffc 16501:     } elsif ($formname eq 'quotacheck') {
                   16502:         $output .= qq|
                   16503: <input type="hidden" name="sortby" value="" />
                   16504: <input type="hidden" name="sortorder" value="" />
                   16505: |;
                   16506:     } else {
1.1181    raeburn  16507:         my $name_input;
                   16508:         if ($cnameelement ne '') {
                   16509:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16510:                           $cnameelement.'" />';
                   16511:         }
                   16512:         $output .= qq|
1.1182    raeburn  16513: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16514: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  16515: $name_input
                   16516: $roleelement
                   16517: $multelement
                   16518: $typeelement
                   16519: |;
                   16520:         if ($formname eq 'portform') {
                   16521:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16522:         }
                   16523:     }
                   16524:     if ($fixeddom) {
                   16525:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16526:     }
                   16527:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16528:     if ($sincefilterform) {
                   16529:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16530:                   .$sincefilterform
                   16531:                   .&Apache::lonhtmlcommon::row_closure();
                   16532:     }
                   16533:     if ($createdfilterform) {
                   16534:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16535:                   .$createdfilterform
                   16536:                   .&Apache::lonhtmlcommon::row_closure();
                   16537:     }
                   16538:     if ($domainselectform) {
                   16539:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16540:                   .$domainselectform
                   16541:                   .&Apache::lonhtmlcommon::row_closure();
                   16542:     }
                   16543:     if ($typeselectform) {
                   16544:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16545:             $output .= $typeselectform;
                   16546:         } else {
                   16547:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16548:                       .$typeselectform
                   16549:                       .&Apache::lonhtmlcommon::row_closure();
                   16550:         }
                   16551:     }
                   16552:     if ($instcodeform) {
                   16553:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16554:                   .$instcodeform
                   16555:                   .&Apache::lonhtmlcommon::row_closure();
                   16556:     }
                   16557:     if (exists($filter->{'ownerfilter'})) {
                   16558:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16559:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16560:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16561:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16562:                    $ownerdomselectform.'</td></tr></table>'.
                   16563:                    &Apache::lonhtmlcommon::row_closure();
                   16564:     }
                   16565:     if (exists($filter->{'personfilter'})) {
                   16566:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16567:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16568:                    '<input type="text" name="personfilter" size="20" value="'.
                   16569:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16570:                    $persondomselectform.'</td></tr></table>'.
                   16571:                    &Apache::lonhtmlcommon::row_closure();
                   16572:     }
                   16573:     if (exists($filter->{'coursefilter'})) {
                   16574:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16575:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16576:                   .$list->{'coursefilter'}.'" />'
                   16577:                   .&Apache::lonhtmlcommon::row_closure();
                   16578:     }
                   16579:     if ($cloneableonlyform) {
                   16580:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16581:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16582:     }
                   16583:     if (exists($filter->{'descriptfilter'})) {
                   16584:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16585:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16586:                   .$list->{'descriptfilter'}.'" />'
                   16587:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16588:     }
                   16589:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16590:                '<input type="hidden" name="updater" value="" />'."\n".
                   16591:                '<input type="submit" name="gosearch" value="'.
                   16592:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16593:     return $jscript.$clonewarning.$output;
                   16594: }
                   16595: 
                   16596: =pod 
                   16597: 
                   16598: =item * &timebased_select_form()
                   16599: 
1.1182    raeburn  16600: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  16601: filter e.g., Course Activity, Course Created, when searching for courses
                   16602: or communities
                   16603: 
                   16604: Inputs:
                   16605: 
                   16606: item - name of form element (sincefilter or createdfilter)
                   16607: 
                   16608: filter - anonymous hash of criteria and their values
                   16609: 
                   16610: Returns: HTML for a select box contained a blank, then six time selections,
                   16611:          with value set in incoming form variables currently selected. 
                   16612: 
                   16613: Side Effects: None
                   16614: 
                   16615: =cut
                   16616: 
                   16617: sub timebased_select_form {
                   16618:     my ($item,$filter) = @_;
                   16619:     if (ref($filter) eq 'HASH') {
                   16620:         $filter->{$item} =~ s/[^\d-]//g;
                   16621:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16622:         return &select_form(
                   16623:                             $filter->{$item},
                   16624:                             $item,
                   16625:                             {      '-1' => '',
                   16626:                                 '86400' => &mt('today'),
                   16627:                                '604800' => &mt('last week'),
                   16628:                               '2592000' => &mt('last month'),
                   16629:                               '7776000' => &mt('last three months'),
                   16630:                              '15552000' => &mt('last six months'),
                   16631:                              '31104000' => &mt('last year'),
                   16632:                     'select_form_order' =>
                   16633:                            ['-1','86400','604800','2592000','7776000',
                   16634:                             '15552000','31104000']});
                   16635:     }
                   16636: }
                   16637: 
                   16638: =pod
                   16639: 
                   16640: =item * &js_changer()
                   16641: 
                   16642: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  16643: when course type or domain is changed, and also to hide 'Searching ...' on
                   16644: page load completion for page showing search result.
1.1181    raeburn  16645: 
                   16646: Inputs: None
                   16647: 
1.1183    raeburn  16648: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  16649: 
                   16650: Side Effects: None
                   16651: 
                   16652: =cut
                   16653: 
                   16654: sub js_changer {
                   16655:     return <<ENDJS;
                   16656: <script type="text/javascript">
                   16657: // <![CDATA[
                   16658: function updateFilters(caller) {
                   16659:     if (typeof(caller) != "undefined") {
                   16660:         document.filterpicker.updater.value = caller.name;
                   16661:     }
                   16662:     document.filterpicker.submit();
                   16663: }
1.1183    raeburn  16664: 
                   16665: function hideSearching() {
                   16666:     if (document.getElementById('searching')) {
                   16667:         document.getElementById('searching').style.display = 'none';
                   16668:     }
                   16669:     return;
                   16670: }
                   16671: 
1.1181    raeburn  16672: // ]]>
                   16673: </script>
                   16674: 
                   16675: ENDJS
                   16676: }
                   16677: 
                   16678: =pod
                   16679: 
1.1182    raeburn  16680: =item * &search_courses()
                   16681: 
                   16682: Process selected filters form course search form and pass to lonnet::courseiddump
                   16683: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16684: 
                   16685: Inputs:
                   16686: 
                   16687: dom - domain being searched 
                   16688: 
                   16689: type - course type ('Course' or 'Community' or '.' if any).
                   16690: 
                   16691: filter - anonymous hash of criteria and their values
                   16692: 
                   16693: numtitles - for institutional codes - number of categories
                   16694: 
                   16695: cloneruname - optional username of new course owner
                   16696: 
                   16697: clonerudom - optional domain of new course owner
                   16698: 
1.1221    raeburn  16699: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  16700:             (used when DC is using course creation form)
                   16701: 
                   16702: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16703: 
1.1221    raeburn  16704: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16705:            (and so can clone automatically)
                   16706: 
                   16707: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16708: 
                   16709: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   16710:               courses to clone 
1.1182    raeburn  16711: 
                   16712: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16713: 
                   16714: 
                   16715: Side Effects: None
                   16716: 
                   16717: =cut
                   16718: 
                   16719: 
                   16720: sub search_courses {
1.1221    raeburn  16721:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16722:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  16723:     my (%courses,%showcourses,$cloner);
                   16724:     if (($filter->{'ownerfilter'} ne '') ||
                   16725:         ($filter->{'ownerdomfilter'} ne '')) {
                   16726:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16727:                                        $filter->{'ownerdomfilter'};
                   16728:     }
                   16729:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16730:         if (!$filter->{$item}) {
                   16731:             $filter->{$item}='.';
                   16732:         }
                   16733:     }
                   16734:     my $now = time;
                   16735:     my $timefilter =
                   16736:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16737:     my ($createdbefore,$createdafter);
                   16738:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16739:         $createdbefore = $now;
                   16740:         $createdafter = $now-$filter->{'createdfilter'};
                   16741:     }
                   16742:     my ($instcodefilter,$regexpok);
                   16743:     if ($numtitles) {
                   16744:         if ($env{'form.official'} eq 'on') {
                   16745:             $instcodefilter =
                   16746:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16747:             $regexpok = 1;
                   16748:         } elsif ($env{'form.official'} eq 'off') {
                   16749:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16750:             unless ($instcodefilter eq '') {
                   16751:                 $regexpok = -1;
                   16752:             }
                   16753:         }
                   16754:     } else {
                   16755:         $instcodefilter = $filter->{'instcodefilter'};
                   16756:     }
                   16757:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16758:     if ($type eq '') { $type = '.'; }
                   16759: 
                   16760:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16761:         $cloner = $cloneruname.':'.$clonerudom;
                   16762:     }
                   16763:     %courses = &Apache::lonnet::courseiddump($dom,
                   16764:                                              $filter->{'descriptfilter'},
                   16765:                                              $timefilter,
                   16766:                                              $instcodefilter,
                   16767:                                              $filter->{'combownerfilter'},
                   16768:                                              $filter->{'coursefilter'},
                   16769:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  16770:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  16771:                                              $filter->{'cloneableonly'},
                   16772:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  16773:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  16774:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16775:         my $ccrole;
                   16776:         if ($type eq 'Community') {
                   16777:             $ccrole = 'co';
                   16778:         } else {
                   16779:             $ccrole = 'cc';
                   16780:         }
                   16781:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16782:                                                      $filter->{'persondomfilter'},
                   16783:                                                      'userroles',undef,
                   16784:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16785:                                                      $dom);
                   16786:         foreach my $role (keys(%rolehash)) {
                   16787:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16788:             my $cid = $cdom.'_'.$cnum;
                   16789:             if (exists($courses{$cid})) {
                   16790:                 if (ref($courses{$cid}) eq 'HASH') {
                   16791:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16792:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  16793:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  16794:                         }
                   16795:                     } else {
                   16796:                         $courses{$cid}{roles} = [$courserole];
                   16797:                     }
                   16798:                     $showcourses{$cid} = $courses{$cid};
                   16799:                 }
                   16800:             }
                   16801:         }
                   16802:         %courses = %showcourses;
                   16803:     }
                   16804:     return %courses;
                   16805: }
                   16806: 
                   16807: =pod
                   16808: 
1.1181    raeburn  16809: =back
                   16810: 
1.1207    raeburn  16811: =head1 Routines for version requirements for current course.
                   16812: 
                   16813: =over 4
                   16814: 
                   16815: =item * &check_release_required()
                   16816: 
                   16817: Compares required LON-CAPA version with version on server, and
                   16818: if required version is newer looks for a server with the required version.
                   16819: 
                   16820: Looks first at servers in user's owen domain; if none suitable, looks at
                   16821: servers in course's domain are permitted to host sessions for user's domain.
                   16822: 
                   16823: Inputs:
                   16824: 
                   16825: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16826: 
                   16827: $courseid - Course ID of current course
                   16828: 
                   16829: $rolecode - User's current role in course (for switchserver query string).
                   16830: 
                   16831: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16832: 
                   16833: 
                   16834: Returns:
                   16835: 
                   16836: $switchserver - query string tp append to /adm/switchserver call (if 
                   16837:                 current server's LON-CAPA version is too old. 
                   16838: 
                   16839: $warning - Message is displayed if no suitable server could be found.
                   16840: 
                   16841: =cut
                   16842: 
                   16843: sub check_release_required {
                   16844:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16845:     my ($switchserver,$warning);
                   16846:     if ($required ne '') {
                   16847:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16848:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16849:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16850:             my $otherserver;
                   16851:             if (($major eq '' && $minor eq '') ||
                   16852:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16853:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16854:                 my $switchlcrev =
                   16855:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16856:                                                            $userdomserver);
                   16857:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16858:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16859:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16860:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16861:                     if ($cdom ne $env{'user.domain'}) {
                   16862:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16863:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16864:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16865:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16866:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16867:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16868:                         my $canhost =
                   16869:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16870:                                                               $coursedomserver,
                   16871:                                                               $remoterev,
                   16872:                                                               $udomdefaults{'remotesessions'},
                   16873:                                                               $defdomdefaults{'hostedsessions'});
                   16874: 
                   16875:                         if ($canhost) {
                   16876:                             $otherserver = $coursedomserver;
                   16877:                         } else {
                   16878:                             $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.");
                   16879:                         }
                   16880:                     } else {
                   16881:                         $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).");
                   16882:                     }
                   16883:                 } else {
                   16884:                     $otherserver = $userdomserver;
                   16885:                 }
                   16886:             }
                   16887:             if ($otherserver ne '') {
                   16888:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16889:             }
                   16890:         }
                   16891:     }
                   16892:     return ($switchserver,$warning);
                   16893: }
                   16894: 
                   16895: =pod
                   16896: 
                   16897: =item * &check_release_result()
                   16898: 
                   16899: Inputs:
                   16900: 
                   16901: $switchwarning - Warning message if no suitable server found to host session.
                   16902: 
                   16903: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16904:                 and current role.
                   16905: 
                   16906: Returns: HTML to display with information about requirement to switch server.
                   16907:          Either displaying warning with link to Roles/Courses screen or
                   16908:          display link to switchserver.
                   16909: 
1.1181    raeburn  16910: =cut
                   16911: 
1.1207    raeburn  16912: sub check_release_result {
                   16913:     my ($switchwarning,$switchserver) = @_;
                   16914:     my $output = &start_page('Selected course unavailable on this server').
                   16915:                  '<p class="LC_warning">';
                   16916:     if ($switchwarning) {
                   16917:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16918:         if (&show_course()) {
                   16919:             $output .= &mt('Display courses');
                   16920:         } else {
                   16921:             $output .= &mt('Display roles');
                   16922:         }
                   16923:         $output .= '</a>';
                   16924:     } elsif ($switchserver) {
                   16925:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16926:                    '<br />'.
                   16927:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16928:                    &mt('Switch Server').
                   16929:                    '</a>';
                   16930:     }
                   16931:     $output .= '</p>'.&end_page();
                   16932:     return $output;
                   16933: }
                   16934: 
                   16935: =pod
                   16936: 
                   16937: =item * &needs_coursereinit()
                   16938: 
                   16939: Determine if course contents stored for user's session needs to be
                   16940: refreshed, because content has changed since "Big Hash" last tied.
                   16941: 
                   16942: Check for change is made if time last checked is more than 10 minutes ago
                   16943: (by default).
                   16944: 
                   16945: Inputs:
                   16946: 
                   16947: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16948: 
                   16949: $interval (optional) - Time which may elapse (in s) between last check for content
                   16950:                        change in current course. (default: 600 s).  
                   16951: 
                   16952: Returns: an array; first element is:
                   16953: 
                   16954: =over 4
                   16955: 
                   16956: 'switch' - if content updates mean user's session
                   16957:            needs to be switched to a server running a newer LON-CAPA version
                   16958:  
                   16959: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16960:            on current server hosting user's session                
                   16961: 
                   16962: ''       - if no action required.
                   16963: 
                   16964: =back
                   16965: 
                   16966: If first item element is 'switch':
                   16967: 
                   16968: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   16969: 
                   16970: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16971:                               and current role. 
                   16972: 
                   16973: otherwise: no other elements returned.
                   16974: 
                   16975: =back
                   16976: 
                   16977: =cut
                   16978: 
                   16979: sub needs_coursereinit {
                   16980:     my ($loncaparev,$interval) = @_;
                   16981:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16982:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16983:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16984:     my $now = time;
                   16985:     if ($interval eq '') {
                   16986:         $interval = 600;
                   16987:     }
                   16988:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16989:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16990:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16991:         if ($lastchange > $env{'request.course.tied'}) {
                   16992:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16993:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16994:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16995:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16996:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16997:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16998:                     my ($switchserver,$switchwarning) =
                   16999:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   17000:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   17001:                     if ($switchwarning ne '' || $switchserver ne '') {
                   17002:                         return ('switch',$switchwarning,$switchserver);
                   17003:                     }
                   17004:                 }
                   17005:             }
                   17006:             return ('update');
                   17007:         }
                   17008:     }
                   17009:     return ();
                   17010: }
1.1181    raeburn  17011: 
1.1083    raeburn  17012: sub update_content_constraints {
                   17013:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17014:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17015:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   17016:     my %checkresponsetypes;
                   17017:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  17018:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  17019:         if ($item eq 'resourcetag') {
                   17020:             if ($name eq 'responsetype') {
                   17021:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   17022:             }
                   17023:         }
                   17024:     }
                   17025:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17026:     if (defined($navmap)) {
                   17027:         my %allresponses;
                   17028:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   17029:             my %responses = $res->responseTypes();
                   17030:             foreach my $key (keys(%responses)) {
                   17031:                 next unless(exists($checkresponsetypes{$key}));
                   17032:                 $allresponses{$key} += $responses{$key};
                   17033:             }
                   17034:         }
                   17035:         foreach my $key (keys(%allresponses)) {
                   17036:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   17037:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17038:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17039:             }
                   17040:         }
                   17041:         undef($navmap);
                   17042:     }
                   17043:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   17044:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   17045:     }
                   17046:     return;
                   17047: }
                   17048: 
1.1110    raeburn  17049: sub allmaps_incourse {
                   17050:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17051:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   17052:         $cid = $env{'request.course.id'};
                   17053:         $cdom = $env{'course.'.$cid.'.domain'};
                   17054:         $cnum = $env{'course.'.$cid.'.num'};
                   17055:         $chome = $env{'course.'.$cid.'.home'};
                   17056:     }
                   17057:     my %allmaps = ();
                   17058:     my $lastchange =
                   17059:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17060:     if ($lastchange > $env{'request.course.tied'}) {
                   17061:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   17062:         unless ($ferr) {
                   17063:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   17064:         }
                   17065:     }
                   17066:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17067:     if (defined($navmap)) {
                   17068:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   17069:             $allmaps{$res->src()} = 1;
                   17070:         }
                   17071:     }
                   17072:     return \%allmaps;
                   17073: }
                   17074: 
1.1083    raeburn  17075: sub parse_supplemental_title {
                   17076:     my ($title) = @_;
                   17077: 
                   17078:     my ($foldertitle,$renametitle);
                   17079:     if ($title =~ /&amp;&amp;&amp;/) {
                   17080:         $title = &HTML::Entites::decode($title);
                   17081:     }
                   17082:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   17083:         $renametitle=$4;
                   17084:         my ($time,$uname,$udom) = ($1,$2,$3);
                   17085:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   17086:         my $name =  &plainname($uname,$udom);
                   17087:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   17088:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   17089:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   17090:             $name.': <br />'.$foldertitle;
                   17091:     }
                   17092:     if (wantarray) {
                   17093:         return ($title,$foldertitle,$renametitle);
                   17094:     }
                   17095:     return $title;
                   17096: }
                   17097: 
1.1143    raeburn  17098: sub recurse_supplemental {
                   17099:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   17100:     if ($suppmap) {
                   17101:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   17102:         if ($fatal) {
                   17103:             $errors ++;
                   17104:         } else {
                   17105:             if ($#LONCAPA::map::resources > 0) {
                   17106:                 foreach my $res (@LONCAPA::map::resources) {
                   17107:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   17108:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  17109:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   17110:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1143    raeburn  17111:                         } else {
                   17112:                             $numfiles ++;
                   17113:                         }
                   17114:                     }
                   17115:                 }
                   17116:             }
                   17117:         }
                   17118:     }
                   17119:     return ($numfiles,$errors);
                   17120: }
                   17121: 
1.1101    raeburn  17122: sub symb_to_docspath {
1.1267    raeburn  17123:     my ($symb,$navmapref) = @_;
                   17124:     return unless ($symb && ref($navmapref));
1.1101    raeburn  17125:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   17126:     if ($resurl=~/\.(sequence|page)$/) {
                   17127:         $mapurl=$resurl;
                   17128:     } elsif ($resurl eq 'adm/navmaps') {
                   17129:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   17130:     }
                   17131:     my $mapresobj;
1.1267    raeburn  17132:     unless (ref($$navmapref)) {
                   17133:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   17134:     }
                   17135:     if (ref($$navmapref)) {
                   17136:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  17137:     }
                   17138:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   17139:     my $type=$2;
                   17140:     my $path;
                   17141:     if (ref($mapresobj)) {
                   17142:         my $pcslist = $mapresobj->map_hierarchy();
                   17143:         if ($pcslist ne '') {
                   17144:             foreach my $pc (split(/,/,$pcslist)) {
                   17145:                 next if ($pc <= 1);
1.1267    raeburn  17146:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  17147:                 if (ref($res)) {
                   17148:                     my $thisurl = $res->src();
                   17149:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   17150:                     my $thistitle = $res->title();
                   17151:                     $path .= '&'.
                   17152:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  17153:                              &escape($thistitle).
1.1101    raeburn  17154:                              ':'.$res->randompick().
                   17155:                              ':'.$res->randomout().
                   17156:                              ':'.$res->encrypted().
                   17157:                              ':'.$res->randomorder().
                   17158:                              ':'.$res->is_page();
                   17159:                 }
                   17160:             }
                   17161:         }
                   17162:         $path =~ s/^\&//;
                   17163:         my $maptitle = $mapresobj->title();
                   17164:         if ($mapurl eq 'default') {
1.1129    raeburn  17165:             $maptitle = 'Main Content';
1.1101    raeburn  17166:         }
                   17167:         $path .= (($path ne '')? '&' : '').
                   17168:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17169:                  &escape($maptitle).
1.1101    raeburn  17170:                  ':'.$mapresobj->randompick().
                   17171:                  ':'.$mapresobj->randomout().
                   17172:                  ':'.$mapresobj->encrypted().
                   17173:                  ':'.$mapresobj->randomorder().
                   17174:                  ':'.$mapresobj->is_page();
                   17175:     } else {
                   17176:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17177:         my $ispage = (($type eq 'page')? 1 : '');
                   17178:         if ($mapurl eq 'default') {
1.1129    raeburn  17179:             $maptitle = 'Main Content';
1.1101    raeburn  17180:         }
                   17181:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17182:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  17183:     }
                   17184:     unless ($mapurl eq 'default') {
                   17185:         $path = 'default&'.
1.1146    raeburn  17186:                 &escape('Main Content').
1.1101    raeburn  17187:                 ':::::&'.$path;
                   17188:     }
                   17189:     return $path;
                   17190: }
                   17191: 
1.1094    raeburn  17192: sub captcha_display {
                   17193:     my ($context,$lonhost) = @_;
                   17194:     my ($output,$error);
1.1234    raeburn  17195:     my ($captcha,$pubkey,$privkey,$version) = 
                   17196:         &get_captcha_config($context,$lonhost);
1.1095    raeburn  17197:     if ($captcha eq 'original') {
1.1094    raeburn  17198:         $output = &create_captcha();
                   17199:         unless ($output) {
1.1172    raeburn  17200:             $error = 'captcha';
1.1094    raeburn  17201:         }
                   17202:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17203:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  17204:         unless ($output) {
1.1172    raeburn  17205:             $error = 'recaptcha';
1.1094    raeburn  17206:         }
                   17207:     }
1.1234    raeburn  17208:     return ($output,$error,$captcha,$version);
1.1094    raeburn  17209: }
                   17210: 
                   17211: sub captcha_response {
                   17212:     my ($context,$lonhost) = @_;
                   17213:     my ($captcha_chk,$captcha_error);
1.1234    raeburn  17214:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  17215:     if ($captcha eq 'original') {
1.1094    raeburn  17216:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17217:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17218:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  17219:     } else {
                   17220:         $captcha_chk = 1;
                   17221:     }
                   17222:     return ($captcha_chk,$captcha_error);
                   17223: }
                   17224: 
                   17225: sub get_captcha_config {
                   17226:     my ($context,$lonhost) = @_;
1.1234    raeburn  17227:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  17228:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17229:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17230:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  17231:     if ($context eq 'usercreation') {
                   17232:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17233:         if (ref($domconfig{$context}) eq 'HASH') {
                   17234:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17235:             if (ref($hashtocheck) eq 'HASH') {
                   17236:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17237:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17238:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17239:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17240:                     }
                   17241:                     if ($privkey && $pubkey) {
                   17242:                         $captcha = 'recaptcha';
1.1234    raeburn  17243:                         $version = $hashtocheck->{'recaptchaversion'};
                   17244:                         if ($version ne '2') {
                   17245:                             $version = 1;
                   17246:                         }
1.1095    raeburn  17247:                     } else {
                   17248:                         $captcha = 'original';
                   17249:                     }
                   17250:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17251:                     $captcha = 'original';
                   17252:                 }
1.1094    raeburn  17253:             }
1.1095    raeburn  17254:         } else {
                   17255:             $captcha = 'captcha';
                   17256:         }
                   17257:     } elsif ($context eq 'login') {
                   17258:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17259:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17260:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17261:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  17262:             if ($privkey && $pubkey) {
                   17263:                 $captcha = 'recaptcha';
1.1234    raeburn  17264:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17265:                 if ($version ne '2') {
                   17266:                     $version = 1; 
                   17267:                 }
1.1095    raeburn  17268:             } else {
                   17269:                 $captcha = 'original';
1.1094    raeburn  17270:             }
1.1095    raeburn  17271:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17272:             $captcha = 'original';
1.1094    raeburn  17273:         }
                   17274:     }
1.1234    raeburn  17275:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  17276: }
                   17277: 
                   17278: sub create_captcha {
                   17279:     my %captcha_params = &captcha_settings();
                   17280:     my ($output,$maxtries,$tries) = ('',10,0);
                   17281:     while ($tries < $maxtries) {
                   17282:         $tries ++;
                   17283:         my $captcha = Authen::Captcha->new (
                   17284:                                            output_folder => $captcha_params{'output_dir'},
                   17285:                                            data_folder   => $captcha_params{'db_dir'},
                   17286:                                           );
                   17287:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17288: 
                   17289:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17290:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17291:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  17292:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17293:                       '<br />'.
                   17294:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  17295:             last;
                   17296:         }
                   17297:     }
                   17298:     return $output;
                   17299: }
                   17300: 
                   17301: sub captcha_settings {
                   17302:     my %captcha_params = (
                   17303:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17304:                            www_output_dir => "/captchaspool",
                   17305:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17306:                            numchars       => '5',
                   17307:                          );
                   17308:     return %captcha_params;
                   17309: }
                   17310: 
                   17311: sub check_captcha {
                   17312:     my ($captcha_chk,$captcha_error);
                   17313:     my $code = $env{'form.code'};
                   17314:     my $md5sum = $env{'form.crypt'};
                   17315:     my %captcha_params = &captcha_settings();
                   17316:     my $captcha = Authen::Captcha->new(
                   17317:                       output_folder => $captcha_params{'output_dir'},
                   17318:                       data_folder   => $captcha_params{'db_dir'},
                   17319:                   );
1.1109    raeburn  17320:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  17321:     my %captcha_hash = (
                   17322:                         0       => 'Code not checked (file error)',
                   17323:                        -1      => 'Failed: code expired',
                   17324:                        -2      => 'Failed: invalid code (not in database)',
                   17325:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17326:     );
                   17327:     if ($captcha_chk != 1) {
                   17328:         $captcha_error = $captcha_hash{$captcha_chk}
                   17329:     }
                   17330:     return ($captcha_chk,$captcha_error);
                   17331: }
                   17332: 
                   17333: sub create_recaptcha {
1.1234    raeburn  17334:     my ($pubkey,$version) = @_;
                   17335:     if ($version >= 2) {
                   17336:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17337:     } else {
                   17338:         my $use_ssl;
                   17339:         if ($ENV{'SERVER_PORT'} == 443) {
                   17340:             $use_ssl = 1;
                   17341:         }
                   17342:         my $captcha = Captcha::reCAPTCHA->new;
                   17343:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17344:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17345:                &mt('If the text is hard to read, [_1] will replace them.',
                   17346:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17347:                '<br /><br />';
                   17348:     }
1.1094    raeburn  17349: }
                   17350: 
                   17351: sub check_recaptcha {
1.1234    raeburn  17352:     my ($privkey,$version) = @_;
1.1094    raeburn  17353:     my $captcha_chk;
1.1234    raeburn  17354:     if ($version >= 2) {
                   17355:         my $ua = LWP::UserAgent->new;
                   17356:         $ua->timeout(10);
                   17357:         my %info = (
                   17358:                      secret   => $privkey, 
                   17359:                      response => $env{'form.g-recaptcha-response'},
                   17360:                      remoteip => $ENV{'REMOTE_ADDR'},
                   17361:                    );
                   17362:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   17363:         if ($response->is_success)  {
                   17364:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17365:             if (ref($data) eq 'HASH') {
                   17366:                 if ($data->{'success'}) {
                   17367:                     $captcha_chk = 1;
                   17368:                 }
                   17369:             }
                   17370:         }
                   17371:     } else {
                   17372:         my $captcha = Captcha::reCAPTCHA->new;
                   17373:         my $captcha_result =
                   17374:             $captcha->check_answer(
                   17375:                                     $privkey,
                   17376:                                     $ENV{'REMOTE_ADDR'},
                   17377:                                     $env{'form.recaptcha_challenge_field'},
                   17378:                                     $env{'form.recaptcha_response_field'},
                   17379:                                   );
                   17380:         if ($captcha_result->{is_valid}) {
                   17381:             $captcha_chk = 1;
                   17382:         }
1.1094    raeburn  17383:     }
                   17384:     return $captcha_chk;
                   17385: }
                   17386: 
1.1174    raeburn  17387: sub emailusername_info {
1.1244    raeburn  17388:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  17389:     my %titles = &Apache::lonlocal::texthash (
                   17390:                      lastname      => 'Last Name',
                   17391:                      firstname     => 'First Name',
                   17392:                      institution   => 'School/college/university',
                   17393:                      location      => "School's city, state/province, country",
                   17394:                      web           => "School's web address",
                   17395:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  17396:                      id            => 'Student/Employee ID',
1.1174    raeburn  17397:                  );
                   17398:     return (\@fields,\%titles);
                   17399: }
                   17400: 
1.1161    raeburn  17401: sub cleanup_html {
                   17402:     my ($incoming) = @_;
                   17403:     my $outgoing;
                   17404:     if ($incoming ne '') {
                   17405:         $outgoing = $incoming;
                   17406:         $outgoing =~ s/;/&#059;/g;
                   17407:         $outgoing =~ s/\#/&#035;/g;
                   17408:         $outgoing =~ s/\&/&#038;/g;
                   17409:         $outgoing =~ s/</&#060;/g;
                   17410:         $outgoing =~ s/>/&#062;/g;
                   17411:         $outgoing =~ s/\(/&#040/g;
                   17412:         $outgoing =~ s/\)/&#041;/g;
                   17413:         $outgoing =~ s/"/&#034;/g;
                   17414:         $outgoing =~ s/'/&#039;/g;
                   17415:         $outgoing =~ s/\$/&#036;/g;
                   17416:         $outgoing =~ s{/}{&#047;}g;
                   17417:         $outgoing =~ s/=/&#061;/g;
                   17418:         $outgoing =~ s/\\/&#092;/g
                   17419:     }
                   17420:     return $outgoing;
                   17421: }
                   17422: 
1.1190    musolffc 17423: # Checks for critical messages and returns a redirect url if one exists.
                   17424: # $interval indicates how often to check for messages.
                   17425: sub critical_redirect {
                   17426:     my ($interval) = @_;
                   17427:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   17428:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   17429:                                         $env{'user.name'});
                   17430:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  17431:         my $redirecturl;
1.1190    musolffc 17432:         if ($what[0]) {
                   17433: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   17434: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  17435: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17436:                 return (1, $url);
1.1190    musolffc 17437:             }
1.1191    raeburn  17438:         }
                   17439:     } 
                   17440:     return ();
1.1190    musolffc 17441: }
                   17442: 
1.1174    raeburn  17443: # Use:
                   17444: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17445: #
                   17446: ##################################################
                   17447: #          password associated functions         #
                   17448: ##################################################
                   17449: sub des_keys {
                   17450:     # Make a new key for DES encryption.
                   17451:     # Each key has two parts which are returned separately.
                   17452:     # Please note:  Each key must be passed through the &hex function
                   17453:     # before it is output to the web browser.  The hex versions cannot
                   17454:     # be used to decrypt.
                   17455:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17456:                 '8','9','a','b','c','d','e','f');
                   17457:     my $lkey='';
                   17458:     for (0..7) {
                   17459:         $lkey.=$hexstr[rand(15)];
                   17460:     }
                   17461:     my $ukey='';
                   17462:     for (0..7) {
                   17463:         $ukey.=$hexstr[rand(15)];
                   17464:     }
                   17465:     return ($lkey,$ukey);
                   17466: }
                   17467: 
                   17468: sub des_decrypt {
                   17469:     my ($key,$cyphertext) = @_;
                   17470:     my $keybin=pack("H16",$key);
                   17471:     my $cypher;
                   17472:     if ($Crypt::DES::VERSION>=2.03) {
                   17473:         $cypher=new Crypt::DES $keybin;
                   17474:     } else {
                   17475:         $cypher=new DES $keybin;
                   17476:     }
1.1233    raeburn  17477:     my $plaintext='';
                   17478:     my $cypherlength = length($cyphertext);
                   17479:     my $numchunks = int($cypherlength/32);
                   17480:     for (my $j=0; $j<$numchunks; $j++) {
                   17481:         my $start = $j*32;
                   17482:         my $cypherblock = substr($cyphertext,$start,32);
                   17483:         my $chunk =
                   17484:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17485:         $chunk .=
                   17486:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17487:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17488:         $plaintext .= $chunk;
                   17489:     }
1.1174    raeburn  17490:     return $plaintext;
                   17491: }
                   17492: 
1.112     bowersj2 17493: 1;
                   17494: __END__;
1.41      ng       17495: 

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