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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1253  ! raeburn     4: # $Id: loncommon.pm,v 1.1252 2016/08/31 19:08:19 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.158     raeburn   270:                 push @{$category_extensions{lc($category)}},$extension;
                    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.659     raeburn   946:    my ($name,$selected,$onchange,$includeempty)=@_;
                    947:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    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 {
                    968:     my ($name,$selected,$onchange,$includeempty)=@_;
                    969:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    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 {
                   1021:     my ($name,$selected,$includeempty) = @_;
                   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.970     raeburn  1033:     return &select_form($selected,$name,\%langchoices);
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);
                   1057: 	    push (@lang_choices, [$selector, $description]);
                   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) {
                   1179:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   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 {
                   2188:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix) = @_;
                   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.970     raeburn  2551: =item * &select_form($defdom,$name,$hashref,$onchange)
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
                   2556: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   2557: 
1.88      www      2558: See lonrights.pm for an example invocation and use.
                   2559: 
                   2560: =cut
                   2561: 
                   2562: #-------------------------------------------
                   2563: sub select_form {
1.1228    raeburn  2564:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2565:     return unless (ref($hashref) eq 'HASH');
                   2566:     if ($onchange) {
                   2567:         $onchange = ' onchange="'.$onchange.'"';
                   2568:     }
1.1228    raeburn  2569:     my $disabled;
                   2570:     if ($readonly) {
                   2571:         $disabled = ' disabled="disabled"';
                   2572:     }
                   2573:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2574:     my @keys;
1.970     raeburn  2575:     if (exists($hashref->{'select_form_order'})) {
                   2576: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2577:     } else {
1.970     raeburn  2578: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2579:     }
1.356     albertel 2580:     foreach my $key (@keys) {
                   2581:         $selectform.=
                   2582: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2583:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2584:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2585:     }
                   2586:     $selectform.="</select>";
                   2587:     return $selectform;
                   2588: }
                   2589: 
1.475     www      2590: # For display filters
                   2591: 
                   2592: sub display_filter {
1.1074    raeburn  2593:     my ($context) = @_;
1.475     www      2594:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2595:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2596:     my $phraseinput = 'hidden';
                   2597:     my $includeinput = 'hidden';
                   2598:     my ($checked,$includetypestext);
                   2599:     if ($env{'form.displayfilter'} eq 'containing') {
                   2600:         $phraseinput = 'text'; 
                   2601:         if ($context eq 'parmslog') {
                   2602:             $includeinput = 'checkbox';
                   2603:             if ($env{'form.includetypes'}) {
                   2604:                 $checked = ' checked="checked"';
                   2605:             }
                   2606:             $includetypestext = &mt('Include parameter types');
                   2607:         }
                   2608:     } else {
                   2609:         $includetypestext = '&nbsp;';
                   2610:     }
                   2611:     my ($additional,$secondid,$thirdid);
                   2612:     if ($context eq 'parmslog') {
                   2613:         $additional = 
                   2614:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2615:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2616:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2617:             '</label>';
                   2618:         $secondid = 'includetypes';
                   2619:         $thirdid = 'includetypestext';
                   2620:     }
                   2621:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2622:                                                     '$secondid','$thirdid')";
                   2623:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2624: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2625: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2626: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2627:            &mt('Filter: [_1]',
1.477     www      2628: 	   &select_form($env{'form.displayfilter'},
                   2629: 			'displayfilter',
1.970     raeburn  2630: 			{'currentfolder' => 'Current folder/page',
1.477     www      2631: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2632: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2633: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2634:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2635:                          '" />'.$additional;
                   2636: }
                   2637: 
                   2638: sub display_filter_js {
                   2639:     my $includetext = &mt('Include parameter types');
                   2640:     return <<"ENDJS";
                   2641:   
                   2642: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2643:     var firstType = 'hidden';
                   2644:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2645:         firstType = 'text';
                   2646:     }
                   2647:     firstObject = document.getElementById(firstid);
                   2648:     if (typeof(firstObject) == 'object') {
                   2649:         if (firstObject.type != firstType) {
                   2650:             changeInputType(firstObject,firstType);
                   2651:         }
                   2652:     }
                   2653:     if (context == 'parmslog') {
                   2654:         var secondType = 'hidden';
                   2655:         if (firstType == 'text') {
                   2656:             secondType = 'checkbox';
                   2657:         }
                   2658:         secondObject = document.getElementById(secondid);  
                   2659:         if (typeof(secondObject) == 'object') {
                   2660:             if (secondObject.type != secondType) {
                   2661:                 changeInputType(secondObject,secondType);
                   2662:             }
                   2663:         }
                   2664:         var textItem = document.getElementById(thirdid);
                   2665:         var currtext = textItem.innerHTML;
                   2666:         var newtext;
                   2667:         if (firstType == 'text') {
                   2668:             newtext = '$includetext';
                   2669:         } else {
                   2670:             newtext = '&nbsp;';
                   2671:         }
                   2672:         if (currtext != newtext) {
                   2673:             textItem.innerHTML = newtext;
                   2674:         }
                   2675:     }
                   2676:     return;
                   2677: }
                   2678: 
                   2679: function changeInputType(oldObject,newType) {
                   2680:     var newObject = document.createElement('input');
                   2681:     newObject.type = newType;
                   2682:     if (oldObject.size) {
                   2683:         newObject.size = oldObject.size;
                   2684:     }
                   2685:     if (oldObject.value) {
                   2686:         newObject.value = oldObject.value;
                   2687:     }
                   2688:     if (oldObject.name) {
                   2689:         newObject.name = oldObject.name;
                   2690:     }
                   2691:     if (oldObject.id) {
                   2692:         newObject.id = oldObject.id;
                   2693:     }
                   2694:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2695:     return;
                   2696: }
                   2697: 
                   2698: ENDJS
1.475     www      2699: }
                   2700: 
1.167     www      2701: sub gradeleveldescription {
                   2702:     my $gradelevel=shift;
                   2703:     my %gradelevels=(0 => 'Not specified',
                   2704: 		     1 => 'Grade 1',
                   2705: 		     2 => 'Grade 2',
                   2706: 		     3 => 'Grade 3',
                   2707: 		     4 => 'Grade 4',
                   2708: 		     5 => 'Grade 5',
                   2709: 		     6 => 'Grade 6',
                   2710: 		     7 => 'Grade 7',
                   2711: 		     8 => 'Grade 8',
                   2712: 		     9 => 'Grade 9',
                   2713: 		     10 => 'Grade 10',
                   2714: 		     11 => 'Grade 11',
                   2715: 		     12 => 'Grade 12',
                   2716: 		     13 => 'Grade 13',
                   2717: 		     14 => '100 Level',
                   2718: 		     15 => '200 Level',
                   2719: 		     16 => '300 Level',
                   2720: 		     17 => '400 Level',
                   2721: 		     18 => 'Graduate Level');
                   2722:     return &mt($gradelevels{$gradelevel});
                   2723: }
                   2724: 
1.163     www      2725: sub select_level_form {
                   2726:     my ($deflevel,$name)=@_;
                   2727:     unless ($deflevel) { $deflevel=0; }
1.167     www      2728:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2729:     for (my $i=0; $i<=18; $i++) {
                   2730:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2731:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2732:                 ">".&gradeleveldescription($i)."</option>\n";
                   2733:     }
                   2734:     $selectform.="</select>";
                   2735:     return $selectform;
1.163     www      2736: }
1.167     www      2737: 
1.35      matthew  2738: #-------------------------------------------
                   2739: 
1.45      matthew  2740: =pod
                   2741: 
1.1121    raeburn  2742: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
1.35      matthew  2743: 
                   2744: Returns a string containing a <select name='$name' size='1'> form to 
                   2745: allow a user to select the domain to preform an operation in.  
                   2746: See loncreateuser.pm for an example invocation and use.
                   2747: 
1.90      www      2748: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2749: selected");
                   2750: 
1.743     raeburn  2751: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2752: 
1.910     raeburn  2753: 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.
                   2754: 
1.1121    raeburn  2755: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2756: 
                   2757: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2758: 
1.35      matthew  2759: =cut
                   2760: 
                   2761: #-------------------------------------------
1.34      matthew  2762: sub select_dom_form {
1.1121    raeburn  2763:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
1.872     raeburn  2764:     if ($onchange) {
1.874     raeburn  2765:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2766:     }
1.1121    raeburn  2767:     my (@domains,%exclude);
1.910     raeburn  2768:     if (ref($incdoms) eq 'ARRAY') {
                   2769:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2770:     } else {
                   2771:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2772:     }
1.90      www      2773:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2774:     if (ref($excdoms) eq 'ARRAY') {
                   2775:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2776:     }
1.743     raeburn  2777:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2778:     foreach my $dom (@domains) {
1.1121    raeburn  2779:         next if ($exclude{$dom});
1.356     albertel 2780:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2781:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2782:         if ($showdomdesc) {
                   2783:             if ($dom ne '') {
                   2784:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2785:                 if ($domdesc ne '') {
                   2786:                     $selectdomain .= ' ('.$domdesc.')';
                   2787:                 }
                   2788:             } 
                   2789:         }
                   2790:         $selectdomain .= "</option>\n";
1.34      matthew  2791:     }
                   2792:     $selectdomain.="</select>";
                   2793:     return $selectdomain;
                   2794: }
                   2795: 
1.35      matthew  2796: #-------------------------------------------
                   2797: 
1.45      matthew  2798: =pod
                   2799: 
1.648     raeburn  2800: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2801: 
1.586     raeburn  2802: input: 4 arguments (two required, two optional) - 
                   2803:     $domain - domain of new user
                   2804:     $name - name of form element
                   2805:     $default - Value of 'default' causes a default item to be first 
                   2806:                             option, and selected by default. 
                   2807:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2808:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2809: output: returns 2 items: 
1.586     raeburn  2810: (a) form element which contains either:
                   2811:    (i) <select name="$name">
                   2812:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2813:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2814:        </select>
                   2815:        form item if there are multiple library servers in $domain, or
                   2816:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2817:        if there is only one library server in $domain.
                   2818: 
                   2819: (b) number of library servers found.
                   2820: 
                   2821: See loncreateuser.pm for example of use.
1.35      matthew  2822: 
                   2823: =cut
                   2824: 
                   2825: #-------------------------------------------
1.586     raeburn  2826: sub home_server_form_item {
                   2827:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2828:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2829:     my $result;
                   2830:     my $numlib = keys(%servers);
                   2831:     if ($numlib > 1) {
                   2832:         $result .= '<select name="'.$name.'" />'."\n";
                   2833:         if ($default) {
1.804     bisitz   2834:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2835:                        '</option>'."\n";
                   2836:         }
                   2837:         foreach my $hostid (sort(keys(%servers))) {
                   2838:             $result.= '<option value="'.$hostid.'">'.
                   2839: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2840:         }
                   2841:         $result .= '</select>'."\n";
                   2842:     } elsif ($numlib == 1) {
                   2843:         my $hostid;
                   2844:         foreach my $item (keys(%servers)) {
                   2845:             $hostid = $item;
                   2846:         }
                   2847:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2848:                    $hostid.'" />';
                   2849:                    if (!$hide) {
                   2850:                        $result .= $hostid.' '.$servers{$hostid};
                   2851:                    }
                   2852:                    $result .= "\n";
                   2853:     } elsif ($default) {
                   2854:         $result .= '<input type="hidden" name="'.$name.
                   2855:                    '" value="default" />';
                   2856:                    if (!$hide) {
                   2857:                        $result .= &mt('default');
                   2858:                    }
                   2859:                    $result .= "\n";
1.33      matthew  2860:     }
1.586     raeburn  2861:     return ($result,$numlib);
1.33      matthew  2862: }
1.112     bowersj2 2863: 
                   2864: =pod
                   2865: 
1.534     albertel 2866: =back 
                   2867: 
1.112     bowersj2 2868: =cut
1.87      matthew  2869: 
                   2870: ###############################################################
1.112     bowersj2 2871: ##                  Decoding User Agent                      ##
1.87      matthew  2872: ###############################################################
                   2873: 
                   2874: =pod
                   2875: 
1.112     bowersj2 2876: =head1 Decoding the User Agent
                   2877: 
                   2878: =over 4
                   2879: 
                   2880: =item * &decode_user_agent()
1.87      matthew  2881: 
                   2882: Inputs: $r
                   2883: 
                   2884: Outputs:
                   2885: 
                   2886: =over 4
                   2887: 
1.112     bowersj2 2888: =item * $httpbrowser
1.87      matthew  2889: 
1.112     bowersj2 2890: =item * $clientbrowser
1.87      matthew  2891: 
1.112     bowersj2 2892: =item * $clientversion
1.87      matthew  2893: 
1.112     bowersj2 2894: =item * $clientmathml
1.87      matthew  2895: 
1.112     bowersj2 2896: =item * $clientunicode
1.87      matthew  2897: 
1.112     bowersj2 2898: =item * $clientos
1.87      matthew  2899: 
1.1137    raeburn  2900: =item * $clientmobile
                   2901: 
1.1141    raeburn  2902: =item * $clientinfo
                   2903: 
1.1194    raeburn  2904: =item * $clientosversion
                   2905: 
1.87      matthew  2906: =back
                   2907: 
1.157     matthew  2908: =back 
                   2909: 
1.87      matthew  2910: =cut
                   2911: 
                   2912: ###############################################################
                   2913: ###############################################################
                   2914: sub decode_user_agent {
1.247     albertel 2915:     my ($r)=@_;
1.87      matthew  2916:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2917:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2918:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2919:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2920:     my $clientbrowser='unknown';
                   2921:     my $clientversion='0';
                   2922:     my $clientmathml='';
                   2923:     my $clientunicode='0';
1.1137    raeburn  2924:     my $clientmobile=0;
1.1194    raeburn  2925:     my $clientosversion='';
1.87      matthew  2926:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2927:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2928: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2929: 	    $clientbrowser=$bname;
                   2930:             $httpbrowser=~/$vreg/i;
                   2931: 	    $clientversion=$1;
                   2932:             $clientmathml=($clientversion>=$minv);
                   2933:             $clientunicode=($clientversion>=$univ);
                   2934: 	}
                   2935:     }
                   2936:     my $clientos='unknown';
1.1141    raeburn  2937:     my $clientinfo;
1.87      matthew  2938:     if (($httpbrowser=~/linux/i) ||
                   2939:         ($httpbrowser=~/unix/i) ||
                   2940:         ($httpbrowser=~/ux/i) ||
                   2941:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2942:     if (($httpbrowser=~/vax/i) ||
                   2943:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2944:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2945:     if (($httpbrowser=~/mac/i) ||
                   2946:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2947:     if ($httpbrowser=~/win/i) {
                   2948:         $clientos='win';
                   2949:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2950:             $clientosversion = $1;
                   2951:         }
                   2952:     }
1.87      matthew  2953:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  2954:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2955:         $clientmobile=lc($1);
                   2956:     }
1.1141    raeburn  2957:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2958:         $clientinfo = 'firefox-'.$1;
                   2959:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2960:         $clientinfo = 'chromeframe-'.$1;
                   2961:     }
1.87      matthew  2962:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  2963:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2964:             $clientosversion);
1.87      matthew  2965: }
                   2966: 
1.32      matthew  2967: ###############################################################
                   2968: ##    Authentication changing form generation subroutines    ##
                   2969: ###############################################################
                   2970: ##
                   2971: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2972: ## hash, and have reasonable default values.
                   2973: ##
                   2974: ##    formname = the name given in the <form> tag.
1.35      matthew  2975: #-------------------------------------------
                   2976: 
1.45      matthew  2977: =pod
                   2978: 
1.112     bowersj2 2979: =head1 Authentication Routines
                   2980: 
                   2981: =over 4
                   2982: 
1.648     raeburn  2983: =item * &authform_xxxxxx()
1.35      matthew  2984: 
                   2985: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2986: handle some of the conveniences required for authentication forms.  
                   2987: This is not an optimal method, but it works.  
                   2988: 
                   2989: =over 4
                   2990: 
1.112     bowersj2 2991: =item * authform_header
1.35      matthew  2992: 
1.112     bowersj2 2993: =item * authform_authorwarning
1.35      matthew  2994: 
1.112     bowersj2 2995: =item * authform_nochange
1.35      matthew  2996: 
1.112     bowersj2 2997: =item * authform_kerberos
1.35      matthew  2998: 
1.112     bowersj2 2999: =item * authform_internal
1.35      matthew  3000: 
1.112     bowersj2 3001: =item * authform_filesystem
1.35      matthew  3002: 
                   3003: =back
                   3004: 
1.648     raeburn  3005: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3006: 
1.35      matthew  3007: =cut
                   3008: 
                   3009: #-------------------------------------------
1.32      matthew  3010: sub authform_header{  
                   3011:     my %in = (
                   3012:         formname => 'cu',
1.80      albertel 3013:         kerb_def_dom => '',
1.32      matthew  3014:         @_,
                   3015:     );
                   3016:     $in{'formname'} = 'document.' . $in{'formname'};
                   3017:     my $result='';
1.80      albertel 3018: 
                   3019: #---------------------------------------------- Code for upper case translation
                   3020:     my $Javascript_toUpperCase;
                   3021:     unless ($in{kerb_def_dom}) {
                   3022:         $Javascript_toUpperCase =<<"END";
                   3023:         switch (choice) {
                   3024:            case 'krb': currentform.elements[choicearg].value =
                   3025:                currentform.elements[choicearg].value.toUpperCase();
                   3026:                break;
                   3027:            default:
                   3028:         }
                   3029: END
                   3030:     } else {
                   3031:         $Javascript_toUpperCase = "";
                   3032:     }
                   3033: 
1.165     raeburn  3034:     my $radioval = "'nochange'";
1.591     raeburn  3035:     if (defined($in{'curr_authtype'})) {
                   3036:         if ($in{'curr_authtype'} ne '') {
                   3037:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3038:         }
1.174     matthew  3039:     }
1.165     raeburn  3040:     my $argfield = 'null';
1.591     raeburn  3041:     if (defined($in{'mode'})) {
1.165     raeburn  3042:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3043:             if (defined($in{'curr_autharg'})) {
                   3044:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3045:                     $argfield = "'$in{'curr_autharg'}'";
                   3046:                 }
                   3047:             }
                   3048:         }
                   3049:     }
                   3050: 
1.32      matthew  3051:     $result.=<<"END";
                   3052: var current = new Object();
1.165     raeburn  3053: current.radiovalue = $radioval;
                   3054: current.argfield = $argfield;
1.32      matthew  3055: 
                   3056: function changed_radio(choice,currentform) {
                   3057:     var choicearg = choice + 'arg';
                   3058:     // If a radio button in changed, we need to change the argfield
                   3059:     if (current.radiovalue != choice) {
                   3060:         current.radiovalue = choice;
                   3061:         if (current.argfield != null) {
                   3062:             currentform.elements[current.argfield].value = '';
                   3063:         }
                   3064:         if (choice == 'nochange') {
                   3065:             current.argfield = null;
                   3066:         } else {
                   3067:             current.argfield = choicearg;
                   3068:             switch(choice) {
                   3069:                 case 'krb': 
                   3070:                     currentform.elements[current.argfield].value = 
                   3071:                         "$in{'kerb_def_dom'}";
                   3072:                 break;
                   3073:               default:
                   3074:                 break;
                   3075:             }
                   3076:         }
                   3077:     }
                   3078:     return;
                   3079: }
1.22      www      3080: 
1.32      matthew  3081: function changed_text(choice,currentform) {
                   3082:     var choicearg = choice + 'arg';
                   3083:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3084:         $Javascript_toUpperCase
1.32      matthew  3085:         // clear old field
                   3086:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3087:             currentform.elements[current.argfield].value = '';
                   3088:         }
                   3089:         current.argfield = choicearg;
                   3090:     }
                   3091:     set_auth_radio_buttons(choice,currentform);
                   3092:     return;
1.20      www      3093: }
1.32      matthew  3094: 
                   3095: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3096:     var numauthchoices = currentform.login.length;
                   3097:     if (typeof numauthchoices  == "undefined") {
                   3098:         return;
                   3099:     } 
1.32      matthew  3100:     var i=0;
1.986     raeburn  3101:     while (i < numauthchoices) {
1.32      matthew  3102:         if (currentform.login[i].value == newvalue) { break; }
                   3103:         i++;
                   3104:     }
1.986     raeburn  3105:     if (i == numauthchoices) {
1.32      matthew  3106:         return;
                   3107:     }
                   3108:     current.radiovalue = newvalue;
                   3109:     currentform.login[i].checked = true;
                   3110:     return;
                   3111: }
                   3112: END
                   3113:     return $result;
                   3114: }
                   3115: 
1.1106    raeburn  3116: sub authform_authorwarning {
1.32      matthew  3117:     my $result='';
1.144     matthew  3118:     $result='<i>'.
                   3119:         &mt('As a general rule, only authors or co-authors should be '.
                   3120:             'filesystem authenticated '.
                   3121:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3122:     return $result;
                   3123: }
                   3124: 
1.1106    raeburn  3125: sub authform_nochange {
1.32      matthew  3126:     my %in = (
                   3127:               formname => 'document.cu',
                   3128:               kerb_def_dom => 'MSU.EDU',
                   3129:               @_,
                   3130:           );
1.1106    raeburn  3131:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3132:     my $result;
1.1104    raeburn  3133:     if (!$authnum) {
1.1105    raeburn  3134:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3135:     } else {
                   3136:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3137:                   '<input type="radio" name="login" value="nochange" '.
                   3138:                   'checked="checked" onclick="'.
1.281     albertel 3139:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3140: 	    '</label>';
1.586     raeburn  3141:     }
1.32      matthew  3142:     return $result;
                   3143: }
                   3144: 
1.591     raeburn  3145: sub authform_kerberos {
1.32      matthew  3146:     my %in = (
                   3147:               formname => 'document.cu',
                   3148:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3149:               kerb_def_auth => 'krb4',
1.32      matthew  3150:               @_,
                   3151:               );
1.586     raeburn  3152:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   3153:         $autharg,$jscall);
1.1106    raeburn  3154:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3155:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3156:        $check5 = ' checked="checked"';
1.80      albertel 3157:     } else {
1.772     bisitz   3158:        $check4 = ' checked="checked"';
1.80      albertel 3159:     }
1.165     raeburn  3160:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3161:     if (defined($in{'curr_authtype'})) {
                   3162:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3163:             $krbcheck = ' checked="checked"';
1.623     raeburn  3164:             if (defined($in{'mode'})) {
                   3165:                 if ($in{'mode'} eq 'modifyuser') {
                   3166:                     $krbcheck = '';
                   3167:                 }
                   3168:             }
1.591     raeburn  3169:             if (defined($in{'curr_kerb_ver'})) {
                   3170:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3171:                     $check5 = ' checked="checked"';
1.591     raeburn  3172:                     $check4 = '';
                   3173:                 } else {
1.772     bisitz   3174:                     $check4 = ' checked="checked"';
1.591     raeburn  3175:                     $check5 = '';
                   3176:                 }
1.586     raeburn  3177:             }
1.591     raeburn  3178:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3179:                 $krbarg = $in{'curr_autharg'};
                   3180:             }
1.586     raeburn  3181:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3182:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3183:                     $result = 
                   3184:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3185:         $in{'curr_autharg'},$krbver);
                   3186:                 } else {
                   3187:                     $result =
                   3188:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3189:                 }
                   3190:                 return $result; 
                   3191:             }
                   3192:         }
                   3193:     } else {
                   3194:         if ($authnum == 1) {
1.784     bisitz   3195:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3196:         }
                   3197:     }
1.586     raeburn  3198:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3199:         return;
1.587     raeburn  3200:     } elsif ($authtype eq '') {
1.591     raeburn  3201:         if (defined($in{'mode'})) {
1.587     raeburn  3202:             if ($in{'mode'} eq 'modifycourse') {
                   3203:                 if ($authnum == 1) {
1.1104    raeburn  3204:                     $authtype = '<input type="radio" name="login" value="krb" />';
1.587     raeburn  3205:                 }
                   3206:             }
                   3207:         }
1.586     raeburn  3208:     }
                   3209:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3210:     if ($authtype eq '') {
                   3211:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3212:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   3213:                     $krbcheck.' />';
                   3214:     }
                   3215:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3216:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3217:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3218:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3219:          $in{'curr_authtype'} eq 'krb4')) {
                   3220:         $result .= &mt
1.144     matthew  3221:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3222:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3223:          '<label>'.$authtype,
1.281     albertel 3224:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3225:              'value="'.$krbarg.'" '.
1.144     matthew  3226:              'onchange="'.$jscall.'" />',
1.281     albertel 3227:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   3228:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   3229: 	 '</label>');
1.586     raeburn  3230:     } elsif ($can_assign{'krb4'}) {
                   3231:         $result .= &mt
                   3232:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3233:          '[_3] Version 4 [_4]',
                   3234:          '<label>'.$authtype,
                   3235:          '</label><input type="text" size="10" name="krbarg" '.
                   3236:              'value="'.$krbarg.'" '.
                   3237:              'onchange="'.$jscall.'" />',
                   3238:          '<label><input type="hidden" name="krbver" value="4" />',
                   3239:          '</label>');
                   3240:     } elsif ($can_assign{'krb5'}) {
                   3241:         $result .= &mt
                   3242:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3243:          '[_3] Version 5 [_4]',
                   3244:          '<label>'.$authtype,
                   3245:          '</label><input type="text" size="10" name="krbarg" '.
                   3246:              'value="'.$krbarg.'" '.
                   3247:              'onchange="'.$jscall.'" />',
                   3248:          '<label><input type="hidden" name="krbver" value="5" />',
                   3249:          '</label>');
                   3250:     }
1.32      matthew  3251:     return $result;
                   3252: }
                   3253: 
1.1106    raeburn  3254: sub authform_internal {
1.586     raeburn  3255:     my %in = (
1.32      matthew  3256:                 formname => 'document.cu',
                   3257:                 kerb_def_dom => 'MSU.EDU',
                   3258:                 @_,
                   3259:                 );
1.586     raeburn  3260:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  3261:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  3262:     if (defined($in{'curr_authtype'})) {
                   3263:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3264:             if ($can_assign{'int'}) {
1.772     bisitz   3265:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3266:                 if (defined($in{'mode'})) {
                   3267:                     if ($in{'mode'} eq 'modifyuser') {
                   3268:                         $intcheck = '';
                   3269:                     }
                   3270:                 }
1.591     raeburn  3271:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3272:                     $intarg = $in{'curr_autharg'};
                   3273:                 }
                   3274:             } else {
                   3275:                 $result = &mt('Currently internally authenticated.');
                   3276:                 return $result;
1.165     raeburn  3277:             }
                   3278:         }
1.586     raeburn  3279:     } else {
                   3280:         if ($authnum == 1) {
1.784     bisitz   3281:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3282:         }
                   3283:     }
                   3284:     if (!$can_assign{'int'}) {
                   3285:         return;
1.587     raeburn  3286:     } elsif ($authtype eq '') {
1.591     raeburn  3287:         if (defined($in{'mode'})) {
1.587     raeburn  3288:             if ($in{'mode'} eq 'modifycourse') {
                   3289:                 if ($authnum == 1) {
1.1104    raeburn  3290:                     $authtype = '<input type="radio" name="login" value="int" />';
1.587     raeburn  3291:                 }
                   3292:             }
                   3293:         }
1.165     raeburn  3294:     }
1.586     raeburn  3295:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3296:     if ($authtype eq '') {
                   3297:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   3298:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   3299:     }
1.605     bisitz   3300:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  3301:                $intarg.'" onchange="'.$jscall.'" />';
                   3302:     $result = &mt
1.144     matthew  3303:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3304:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   3305:     $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
1.32      matthew  3306:     return $result;
                   3307: }
                   3308: 
1.1104    raeburn  3309: sub authform_local {
1.32      matthew  3310:     my %in = (
                   3311:               formname => 'document.cu',
                   3312:               kerb_def_dom => 'MSU.EDU',
                   3313:               @_,
                   3314:               );
1.586     raeburn  3315:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  3316:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  3317:     if (defined($in{'curr_authtype'})) {
                   3318:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3319:             if ($can_assign{'loc'}) {
1.772     bisitz   3320:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3321:                 if (defined($in{'mode'})) {
                   3322:                     if ($in{'mode'} eq 'modifyuser') {
                   3323:                         $loccheck = '';
                   3324:                     }
                   3325:                 }
1.591     raeburn  3326:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3327:                     $locarg = $in{'curr_autharg'};
                   3328:                 }
                   3329:             } else {
                   3330:                 $result = &mt('Currently using local (institutional) authentication.');
                   3331:                 return $result;
1.165     raeburn  3332:             }
                   3333:         }
1.586     raeburn  3334:     } else {
                   3335:         if ($authnum == 1) {
1.784     bisitz   3336:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3337:         }
                   3338:     }
                   3339:     if (!$can_assign{'loc'}) {
                   3340:         return;
1.587     raeburn  3341:     } elsif ($authtype eq '') {
1.591     raeburn  3342:         if (defined($in{'mode'})) {
1.587     raeburn  3343:             if ($in{'mode'} eq 'modifycourse') {
                   3344:                 if ($authnum == 1) {
1.1104    raeburn  3345:                     $authtype = '<input type="radio" name="login" value="loc" />';
1.587     raeburn  3346:                 }
                   3347:             }
                   3348:         }
1.165     raeburn  3349:     }
1.586     raeburn  3350:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3351:     if ($authtype eq '') {
                   3352:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3353:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   3354:                     $jscall.'" />';
                   3355:     }
                   3356:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   3357:                $locarg.'" onchange="'.$jscall.'" />';
                   3358:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3359:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3360:     return $result;
                   3361: }
                   3362: 
1.1106    raeburn  3363: sub authform_filesystem {
1.32      matthew  3364:     my %in = (
                   3365:               formname => 'document.cu',
                   3366:               kerb_def_dom => 'MSU.EDU',
                   3367:               @_,
                   3368:               );
1.586     raeburn  3369:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  3370:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  3371:     if (defined($in{'curr_authtype'})) {
                   3372:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3373:             if ($can_assign{'fsys'}) {
1.772     bisitz   3374:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3375:                 if (defined($in{'mode'})) {
                   3376:                     if ($in{'mode'} eq 'modifyuser') {
                   3377:                         $fsyscheck = '';
                   3378:                     }
                   3379:                 }
1.586     raeburn  3380:             } else {
                   3381:                 $result = &mt('Currently Filesystem Authenticated.');
                   3382:                 return $result;
                   3383:             }           
                   3384:         }
                   3385:     } else {
                   3386:         if ($authnum == 1) {
1.784     bisitz   3387:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3388:         }
                   3389:     }
                   3390:     if (!$can_assign{'fsys'}) {
                   3391:         return;
1.587     raeburn  3392:     } elsif ($authtype eq '') {
1.591     raeburn  3393:         if (defined($in{'mode'})) {
1.587     raeburn  3394:             if ($in{'mode'} eq 'modifycourse') {
                   3395:                 if ($authnum == 1) {
1.1104    raeburn  3396:                     $authtype = '<input type="radio" name="login" value="fsys" />';
1.587     raeburn  3397:                 }
                   3398:             }
                   3399:         }
1.586     raeburn  3400:     }
                   3401:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3402:     if ($authtype eq '') {
                   3403:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3404:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   3405:                     $jscall.'" />';
                   3406:     }
                   3407:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   3408:                ' onchange="'.$jscall.'" />';
                   3409:     $result = &mt
1.144     matthew  3410:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3411:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  3412:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   3413:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  3414:                   'onchange="'.$jscall.'" />');
1.32      matthew  3415:     return $result;
                   3416: }
                   3417: 
1.586     raeburn  3418: sub get_assignable_auth {
                   3419:     my ($dom) = @_;
                   3420:     if ($dom eq '') {
                   3421:         $dom = $env{'request.role.domain'};
                   3422:     }
                   3423:     my %can_assign = (
                   3424:                           krb4 => 1,
                   3425:                           krb5 => 1,
                   3426:                           int  => 1,
                   3427:                           loc  => 1,
                   3428:                      );
                   3429:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3430:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3431:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3432:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3433:             my $context;
                   3434:             if ($env{'request.role'} =~ /^au/) {
                   3435:                 $context = 'author';
                   3436:             } elsif ($env{'request.role'} =~ /^dc/) {
                   3437:                 $context = 'domain';
                   3438:             } elsif ($env{'request.course.id'}) {
                   3439:                 $context = 'course';
                   3440:             }
                   3441:             if ($context) {
                   3442:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3443:                    %can_assign = %{$authhash->{$context}}; 
                   3444:                 }
                   3445:             }
                   3446:         }
                   3447:     }
                   3448:     my $authnum = 0;
                   3449:     foreach my $key (keys(%can_assign)) {
                   3450:         if ($can_assign{$key}) {
                   3451:             $authnum ++;
                   3452:         }
                   3453:     }
                   3454:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3455:         $authnum --;
                   3456:     }
                   3457:     return ($authnum,%can_assign);
                   3458: }
                   3459: 
1.80      albertel 3460: ###############################################################
                   3461: ##    Get Kerberos Defaults for Domain                 ##
                   3462: ###############################################################
                   3463: ##
                   3464: ## Returns default kerberos version and an associated argument
                   3465: ## as listed in file domain.tab. If not listed, provides
                   3466: ## appropriate default domain and kerberos version.
                   3467: ##
                   3468: #-------------------------------------------
                   3469: 
                   3470: =pod
                   3471: 
1.648     raeburn  3472: =item * &get_kerberos_defaults()
1.80      albertel 3473: 
                   3474: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3475: version and domain. If not found, it defaults to version 4 and the 
                   3476: domain of the server.
1.80      albertel 3477: 
1.648     raeburn  3478: =over 4
                   3479: 
1.80      albertel 3480: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3481: 
1.648     raeburn  3482: =back
                   3483: 
                   3484: =back
                   3485: 
1.80      albertel 3486: =cut
                   3487: 
                   3488: #-------------------------------------------
                   3489: sub get_kerberos_defaults {
                   3490:     my $domain=shift;
1.641     raeburn  3491:     my ($krbdef,$krbdefdom);
                   3492:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3493:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3494:         $krbdef = $domdefaults{'auth_def'};
                   3495:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3496:     } else {
1.80      albertel 3497:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3498:         my $krbdefdom=$1;
                   3499:         $krbdefdom=~tr/a-z/A-Z/;
                   3500:         $krbdef = "krb4";
                   3501:     }
                   3502:     return ($krbdef,$krbdefdom);
                   3503: }
1.112     bowersj2 3504: 
1.32      matthew  3505: 
1.46      matthew  3506: ###############################################################
                   3507: ##                Thesaurus Functions                        ##
                   3508: ###############################################################
1.20      www      3509: 
1.46      matthew  3510: =pod
1.20      www      3511: 
1.112     bowersj2 3512: =head1 Thesaurus Functions
                   3513: 
                   3514: =over 4
                   3515: 
1.648     raeburn  3516: =item * &initialize_keywords()
1.46      matthew  3517: 
                   3518: Initializes the package variable %Keywords if it is empty.  Uses the
                   3519: package variable $thesaurus_db_file.
                   3520: 
                   3521: =cut
                   3522: 
                   3523: ###################################################
                   3524: 
                   3525: sub initialize_keywords {
                   3526:     return 1 if (scalar keys(%Keywords));
                   3527:     # If we are here, %Keywords is empty, so fill it up
                   3528:     #   Make sure the file we need exists...
                   3529:     if (! -e $thesaurus_db_file) {
                   3530:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3531:                                  " failed because it does not exist");
                   3532:         return 0;
                   3533:     }
                   3534:     #   Set up the hash as a database
                   3535:     my %thesaurus_db;
                   3536:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3537:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3538:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3539:                                  $thesaurus_db_file);
                   3540:         return 0;
                   3541:     } 
                   3542:     #  Get the average number of appearances of a word.
                   3543:     my $avecount = $thesaurus_db{'average.count'};
                   3544:     #  Put keywords (those that appear > average) into %Keywords
                   3545:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3546:         my ($count,undef) = split /:/,$data;
                   3547:         $Keywords{$word}++ if ($count > $avecount);
                   3548:     }
                   3549:     untie %thesaurus_db;
                   3550:     # Remove special values from %Keywords.
1.356     albertel 3551:     foreach my $value ('total.count','average.count') {
                   3552:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3553:   }
1.46      matthew  3554:     return 1;
                   3555: }
                   3556: 
                   3557: ###################################################
                   3558: 
                   3559: =pod
                   3560: 
1.648     raeburn  3561: =item * &keyword($word)
1.46      matthew  3562: 
                   3563: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3564: than the average number of times in the thesaurus database.  Calls 
                   3565: &initialize_keywords
                   3566: 
                   3567: =cut
                   3568: 
                   3569: ###################################################
1.20      www      3570: 
                   3571: sub keyword {
1.46      matthew  3572:     return if (!&initialize_keywords());
                   3573:     my $word=lc(shift());
                   3574:     $word=~s/\W//g;
                   3575:     return exists($Keywords{$word});
1.20      www      3576: }
1.46      matthew  3577: 
                   3578: ###############################################################
                   3579: 
                   3580: =pod 
1.20      www      3581: 
1.648     raeburn  3582: =item * &get_related_words()
1.46      matthew  3583: 
1.160     matthew  3584: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3585: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3586: will be returned.  The order of the words returned is determined by the
                   3587: database which holds them.
                   3588: 
                   3589: Uses global $thesaurus_db_file.
                   3590: 
1.1057    foxr     3591: 
1.46      matthew  3592: =cut
                   3593: 
                   3594: ###############################################################
                   3595: sub get_related_words {
                   3596:     my $keyword = shift;
                   3597:     my %thesaurus_db;
                   3598:     if (! -e $thesaurus_db_file) {
                   3599:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3600:                                  "failed because the file does not exist");
                   3601:         return ();
                   3602:     }
                   3603:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3604:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3605:         return ();
                   3606:     } 
                   3607:     my @Words=();
1.429     www      3608:     my $count=0;
1.46      matthew  3609:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3610: 	# The first element is the number of times
                   3611: 	# the word appears.  We do not need it now.
1.429     www      3612: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3613: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3614: 	my $threshold=$mostfrequentcount/10;
                   3615:         foreach my $possibleword (@RelatedWords) {
                   3616:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3617:             if ($wordcount>$threshold) {
                   3618: 		push(@Words,$word);
                   3619:                 $count++;
                   3620:                 if ($count>10) { last; }
                   3621: 	    }
1.20      www      3622:         }
                   3623:     }
1.46      matthew  3624:     untie %thesaurus_db;
                   3625:     return @Words;
1.14      harris41 3626: }
1.1090    foxr     3627: ###############################################################
                   3628: #
                   3629: #  Spell checking
                   3630: #
                   3631: 
                   3632: =pod
                   3633: 
1.1142    raeburn  3634: =back
                   3635: 
1.1090    foxr     3636: =head1 Spell checking
                   3637: 
                   3638: =over 4
                   3639: 
                   3640: =item * &check_spelling($wordlist $language)
                   3641: 
                   3642: Takes a string containing words and feeds it to an external
                   3643: spellcheck program via a pipeline. Returns a string containing
                   3644: them mis-spelled words.
                   3645: 
                   3646: Parameters:
                   3647: 
                   3648: =over 4
                   3649: 
                   3650: =item - $wordlist
                   3651: 
                   3652: String that will be fed into the spellcheck program.
                   3653: 
                   3654: =item - $language
                   3655: 
                   3656: Language string that specifies the language for which the spell
                   3657: check will be performed.
                   3658: 
                   3659: =back
                   3660: 
                   3661: =back
                   3662: 
                   3663: Note: This sub assumes that aspell is installed.
                   3664: 
                   3665: 
                   3666: =cut
                   3667: 
1.46      matthew  3668: 
1.1090    foxr     3669: sub check_spelling {
                   3670:     my ($wordlist, $language) = @_;
1.1091    foxr     3671:     my @misspellings;
                   3672:     
                   3673:     # Generate the speller and set the langauge.
                   3674:     # if explicitly selected:
1.1090    foxr     3675: 
1.1091    foxr     3676:     my $speller = Text::Aspell->new;
1.1090    foxr     3677:     if ($language) {
1.1091    foxr     3678: 	$speller->set_option('lang', $language);
1.1090    foxr     3679:     }
                   3680: 
1.1091    foxr     3681:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3682: 
1.1091    foxr     3683:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3684: 
1.1091    foxr     3685:     foreach my $word (@words) {
                   3686: 	if(! $speller->check($word)) {
                   3687: 	    push(@misspellings, $word);
1.1090    foxr     3688: 	}
                   3689:     }
1.1091    foxr     3690:     return join(' ', @misspellings);
                   3691:     
1.1090    foxr     3692: }
                   3693: 
1.61      www      3694: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3695: =pod
                   3696: 
1.112     bowersj2 3697: =head1 User Name Functions
                   3698: 
                   3699: =over 4
                   3700: 
1.648     raeburn  3701: =item * &plainname($uname,$udom,$first)
1.81      albertel 3702: 
1.112     bowersj2 3703: Takes a users logon name and returns it as a string in
1.226     albertel 3704: "first middle last generation" form 
                   3705: if $first is set to 'lastname' then it returns it as
                   3706: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3707: 
                   3708: =cut
1.61      www      3709: 
1.295     www      3710: 
1.81      albertel 3711: ###############################################################
1.61      www      3712: sub plainname {
1.226     albertel 3713:     my ($uname,$udom,$first)=@_;
1.537     albertel 3714:     return if (!defined($uname) || !defined($udom));
1.295     www      3715:     my %names=&getnames($uname,$udom);
1.226     albertel 3716:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3717: 					  $names{'middlename'},
                   3718: 					  $names{'lastname'},
                   3719: 					  $names{'generation'},$first);
                   3720:     $name=~s/^\s+//;
1.62      www      3721:     $name=~s/\s+$//;
                   3722:     $name=~s/\s+/ /g;
1.353     albertel 3723:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3724:     return $name;
1.61      www      3725: }
1.66      www      3726: 
                   3727: # -------------------------------------------------------------------- Nickname
1.81      albertel 3728: =pod
                   3729: 
1.648     raeburn  3730: =item * &nickname($uname,$udom)
1.81      albertel 3731: 
                   3732: Gets a users name and returns it as a string as
                   3733: 
                   3734: "&quot;nickname&quot;"
1.66      www      3735: 
1.81      albertel 3736: if the user has a nickname or
                   3737: 
                   3738: "first middle last generation"
                   3739: 
                   3740: if the user does not
                   3741: 
                   3742: =cut
1.66      www      3743: 
                   3744: sub nickname {
                   3745:     my ($uname,$udom)=@_;
1.537     albertel 3746:     return if (!defined($uname) || !defined($udom));
1.295     www      3747:     my %names=&getnames($uname,$udom);
1.68      albertel 3748:     my $name=$names{'nickname'};
1.66      www      3749:     if ($name) {
                   3750:        $name='&quot;'.$name.'&quot;'; 
                   3751:     } else {
                   3752:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3753: 	     $names{'lastname'}.' '.$names{'generation'};
                   3754:        $name=~s/\s+$//;
                   3755:        $name=~s/\s+/ /g;
                   3756:     }
                   3757:     return $name;
                   3758: }
                   3759: 
1.295     www      3760: sub getnames {
                   3761:     my ($uname,$udom)=@_;
1.537     albertel 3762:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3763:     if ($udom eq 'public' && $uname eq 'public') {
                   3764: 	return ('lastname' => &mt('Public'));
                   3765:     }
1.295     www      3766:     my $id=$uname.':'.$udom;
                   3767:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3768:     if ($cached) {
                   3769: 	return %{$names};
                   3770:     } else {
                   3771: 	my %loadnames=&Apache::lonnet::get('environment',
                   3772:                     ['firstname','middlename','lastname','generation','nickname'],
                   3773: 					 $udom,$uname);
                   3774: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3775: 	return %loadnames;
                   3776:     }
                   3777: }
1.61      www      3778: 
1.542     raeburn  3779: # -------------------------------------------------------------------- getemails
1.648     raeburn  3780: 
1.542     raeburn  3781: =pod
                   3782: 
1.648     raeburn  3783: =item * &getemails($uname,$udom)
1.542     raeburn  3784: 
                   3785: Gets a user's email information and returns it as a hash with keys:
                   3786: notification, critnotification, permanentemail
                   3787: 
                   3788: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3789: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3790:  
1.648     raeburn  3791: 
1.542     raeburn  3792: =cut
                   3793: 
1.648     raeburn  3794: 
1.466     albertel 3795: sub getemails {
                   3796:     my ($uname,$udom)=@_;
                   3797:     if ($udom eq 'public' && $uname eq 'public') {
                   3798: 	return;
                   3799:     }
1.467     www      3800:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3801:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3802:     my $id=$uname.':'.$udom;
                   3803:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3804:     if ($cached) {
                   3805: 	return %{$names};
                   3806:     } else {
                   3807: 	my %loadnames=&Apache::lonnet::get('environment',
                   3808:                     			   ['notification','critnotification',
                   3809: 					    'permanentemail'],
                   3810: 					   $udom,$uname);
                   3811: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3812: 	return %loadnames;
                   3813:     }
                   3814: }
                   3815: 
1.551     albertel 3816: sub flush_email_cache {
                   3817:     my ($uname,$udom)=@_;
                   3818:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3819:     if (!$uname) { $uname=$env{'user.name'};   }
                   3820:     return if ($udom eq 'public' && $uname eq 'public');
                   3821:     my $id=$uname.':'.$udom;
                   3822:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3823: }
                   3824: 
1.728     raeburn  3825: # -------------------------------------------------------------------- getlangs
                   3826: 
                   3827: =pod
                   3828: 
                   3829: =item * &getlangs($uname,$udom)
                   3830: 
                   3831: Gets a user's language preference and returns it as a hash with key:
                   3832: language.
                   3833: 
                   3834: =cut
                   3835: 
                   3836: 
                   3837: sub getlangs {
                   3838:     my ($uname,$udom) = @_;
                   3839:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3840:     if (!$uname) { $uname=$env{'user.name'};   }
                   3841:     my $id=$uname.':'.$udom;
                   3842:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3843:     if ($cached) {
                   3844:         return %{$langs};
                   3845:     } else {
                   3846:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3847:                                            $udom,$uname);
                   3848:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3849:         return %loadlangs;
                   3850:     }
                   3851: }
                   3852: 
                   3853: sub flush_langs_cache {
                   3854:     my ($uname,$udom)=@_;
                   3855:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3856:     if (!$uname) { $uname=$env{'user.name'};   }
                   3857:     return if ($udom eq 'public' && $uname eq 'public');
                   3858:     my $id=$uname.':'.$udom;
                   3859:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3860: }
                   3861: 
1.61      www      3862: # ------------------------------------------------------------------ Screenname
1.81      albertel 3863: 
                   3864: =pod
                   3865: 
1.648     raeburn  3866: =item * &screenname($uname,$udom)
1.81      albertel 3867: 
                   3868: Gets a users screenname and returns it as a string
                   3869: 
                   3870: =cut
1.61      www      3871: 
                   3872: sub screenname {
                   3873:     my ($uname,$udom)=@_;
1.258     albertel 3874:     if ($uname eq $env{'user.name'} &&
                   3875: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3876:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3877:     return $names{'screenname'};
1.62      www      3878: }
                   3879: 
1.212     albertel 3880: 
1.802     bisitz   3881: # ------------------------------------------------------------- Confirm Wrapper
                   3882: =pod
                   3883: 
1.1142    raeburn  3884: =item * &confirmwrapper($message)
1.802     bisitz   3885: 
                   3886: Wrap messages about completion of operation in box
                   3887: 
                   3888: =cut
                   3889: 
                   3890: sub confirmwrapper {
                   3891:     my ($message)=@_;
                   3892:     if ($message) {
                   3893:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3894:                .$message."\n"
                   3895:                .'</div>'."\n";
                   3896:     } else {
                   3897:         return $message;
                   3898:     }
                   3899: }
                   3900: 
1.62      www      3901: # ------------------------------------------------------------- Message Wrapper
                   3902: 
                   3903: sub messagewrapper {
1.369     www      3904:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3905:     return 
1.441     albertel 3906:         '<a href="/adm/email?compose=individual&amp;'.
                   3907:         'recname='.$username.'&amp;recdom='.$domain.
                   3908: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3909:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3910: }
1.802     bisitz   3911: 
1.74      www      3912: # --------------------------------------------------------------- Notes Wrapper
                   3913: 
                   3914: sub noteswrapper {
                   3915:     my ($link,$un,$do)=@_;
                   3916:     return 
1.896     amueller 3917: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3918: }
1.802     bisitz   3919: 
1.62      www      3920: # ------------------------------------------------------------- Aboutme Wrapper
                   3921: 
                   3922: sub aboutmewrapper {
1.1070    raeburn  3923:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3924:     if (!defined($username)  && !defined($domain)) {
                   3925:         return;
                   3926:     }
1.1096    raeburn  3927:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3928: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3929: }
                   3930: 
                   3931: # ------------------------------------------------------------ Syllabus Wrapper
                   3932: 
                   3933: sub syllabuswrapper {
1.707     bisitz   3934:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3935:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3936: }
1.14      harris41 3937: 
1.802     bisitz   3938: # -----------------------------------------------------------------------------
                   3939: 
1.208     matthew  3940: sub track_student_link {
1.887     raeburn  3941:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3942:     my $link ="/adm/trackstudent?";
1.208     matthew  3943:     my $title = 'View recent activity';
                   3944:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3945:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3946:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3947:         $title .= ' of this student';
1.268     albertel 3948:     } 
1.208     matthew  3949:     if (defined($target) && $target !~ /^\s*$/) {
                   3950:         $target = qq{target="$target"};
                   3951:     } else {
                   3952:         $target = '';
                   3953:     }
1.268     albertel 3954:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3955:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3956:     $title = &mt($title);
                   3957:     $linktext = &mt($linktext);
1.448     albertel 3958:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3959: 	&help_open_topic('View_recent_activity');
1.208     matthew  3960: }
                   3961: 
1.781     raeburn  3962: sub slot_reservations_link {
                   3963:     my ($linktext,$sname,$sdom,$target) = @_;
                   3964:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3965:     my $title = 'View slot reservation history';
                   3966:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3967:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3968:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3969:         $title .= ' of this student';
                   3970:     }
                   3971:     if (defined($target) && $target !~ /^\s*$/) {
                   3972:         $target = qq{target="$target"};
                   3973:     } else {
                   3974:         $target = '';
                   3975:     }
                   3976:     $title = &mt($title);
                   3977:     $linktext = &mt($linktext);
                   3978:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3979: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3980: 
                   3981: }
                   3982: 
1.508     www      3983: # ===================================================== Display a student photo
                   3984: 
                   3985: 
1.509     albertel 3986: sub student_image_tag {
1.508     www      3987:     my ($domain,$user)=@_;
                   3988:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3989:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3990: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3991:     } else {
                   3992: 	return '';
                   3993:     }
                   3994: }
                   3995: 
1.112     bowersj2 3996: =pod
                   3997: 
                   3998: =back
                   3999: 
                   4000: =head1 Access .tab File Data
                   4001: 
                   4002: =over 4
                   4003: 
1.648     raeburn  4004: =item * &languageids() 
1.112     bowersj2 4005: 
                   4006: returns list of all language ids
                   4007: 
                   4008: =cut
                   4009: 
1.14      harris41 4010: sub languageids {
1.16      harris41 4011:     return sort(keys(%language));
1.14      harris41 4012: }
                   4013: 
1.112     bowersj2 4014: =pod
                   4015: 
1.648     raeburn  4016: =item * &languagedescription() 
1.112     bowersj2 4017: 
                   4018: returns description of a specified language id
                   4019: 
                   4020: =cut
                   4021: 
1.14      harris41 4022: sub languagedescription {
1.125     www      4023:     my $code=shift;
                   4024:     return  ($supported_language{$code}?'* ':'').
                   4025:             $language{$code}.
1.126     www      4026: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4027: }
                   4028: 
1.1048    foxr     4029: =pod
                   4030: 
                   4031: =item * &plainlanguagedescription
                   4032: 
                   4033: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4034: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4035: 
                   4036: =cut
                   4037: 
1.145     www      4038: sub plainlanguagedescription {
                   4039:     my $code=shift;
                   4040:     return $language{$code};
                   4041: }
                   4042: 
1.1048    foxr     4043: =pod
                   4044: 
                   4045: =item * &supportedlanguagecode
                   4046: 
                   4047: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4048: code.
                   4049: 
                   4050: =cut
                   4051: 
1.145     www      4052: sub supportedlanguagecode {
                   4053:     my $code=shift;
                   4054:     return $supported_language{$code};
1.97      www      4055: }
                   4056: 
1.112     bowersj2 4057: =pod
                   4058: 
1.1048    foxr     4059: =item * &latexlanguage()
                   4060: 
                   4061: Given a language key code returns the correspondnig language to use
                   4062: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4063: is no supported hyphenation for the language code.
                   4064: 
                   4065: =cut
                   4066: 
                   4067: sub latexlanguage {
                   4068:     my $code = shift;
                   4069:     return $latex_language{$code};
                   4070: }
                   4071: 
                   4072: =pod
                   4073: 
                   4074: =item * &latexhyphenation()
                   4075: 
                   4076: Same as above but what's supplied is the language as it might be stored
                   4077: in the metadata.
                   4078: 
                   4079: =cut
                   4080: 
                   4081: sub latexhyphenation {
                   4082:     my $key = shift;
                   4083:     return $latex_language_bykey{$key};
                   4084: }
                   4085: 
                   4086: =pod
                   4087: 
1.648     raeburn  4088: =item * &copyrightids() 
1.112     bowersj2 4089: 
                   4090: returns list of all copyrights
                   4091: 
                   4092: =cut
                   4093: 
                   4094: sub copyrightids {
                   4095:     return sort(keys(%cprtag));
                   4096: }
                   4097: 
                   4098: =pod
                   4099: 
1.648     raeburn  4100: =item * &copyrightdescription() 
1.112     bowersj2 4101: 
                   4102: returns description of a specified copyright id
                   4103: 
                   4104: =cut
                   4105: 
                   4106: sub copyrightdescription {
1.166     www      4107:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4108: }
1.197     matthew  4109: 
                   4110: =pod
                   4111: 
1.648     raeburn  4112: =item * &source_copyrightids() 
1.192     taceyjo1 4113: 
                   4114: returns list of all source copyrights
                   4115: 
                   4116: =cut
                   4117: 
                   4118: sub source_copyrightids {
                   4119:     return sort(keys(%scprtag));
                   4120: }
                   4121: 
                   4122: =pod
                   4123: 
1.648     raeburn  4124: =item * &source_copyrightdescription() 
1.192     taceyjo1 4125: 
                   4126: returns description of a specified source copyright id
                   4127: 
                   4128: =cut
                   4129: 
                   4130: sub source_copyrightdescription {
                   4131:     return &mt($scprtag{shift(@_)});
                   4132: }
1.112     bowersj2 4133: 
                   4134: =pod
                   4135: 
1.648     raeburn  4136: =item * &filecategories() 
1.112     bowersj2 4137: 
                   4138: returns list of all file categories
                   4139: 
                   4140: =cut
                   4141: 
                   4142: sub filecategories {
                   4143:     return sort(keys(%category_extensions));
                   4144: }
                   4145: 
                   4146: =pod
                   4147: 
1.648     raeburn  4148: =item * &filecategorytypes() 
1.112     bowersj2 4149: 
                   4150: returns list of file types belonging to a given file
                   4151: category
                   4152: 
                   4153: =cut
                   4154: 
                   4155: sub filecategorytypes {
1.356     albertel 4156:     my ($cat) = @_;
1.1248    raeburn  4157:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4158:         return @{$category_extensions{lc($cat)}};
                   4159:     } else {
                   4160:         return ();
                   4161:     }
1.112     bowersj2 4162: }
                   4163: 
                   4164: =pod
                   4165: 
1.648     raeburn  4166: =item * &fileembstyle() 
1.112     bowersj2 4167: 
                   4168: returns embedding style for a specified file type
                   4169: 
                   4170: =cut
                   4171: 
                   4172: sub fileembstyle {
                   4173:     return $fe{lc(shift(@_))};
1.169     www      4174: }
                   4175: 
1.351     www      4176: sub filemimetype {
                   4177:     return $fm{lc(shift(@_))};
                   4178: }
                   4179: 
1.169     www      4180: 
                   4181: sub filecategoryselect {
                   4182:     my ($name,$value)=@_;
1.189     matthew  4183:     return &select_form($value,$name,
1.970     raeburn  4184:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4185: }
                   4186: 
                   4187: =pod
                   4188: 
1.648     raeburn  4189: =item * &filedescription() 
1.112     bowersj2 4190: 
                   4191: returns description for a specified file type
                   4192: 
                   4193: =cut
                   4194: 
                   4195: sub filedescription {
1.188     matthew  4196:     my $file_description = $fd{lc(shift())};
                   4197:     $file_description =~ s:([\[\]]):~$1:g;
                   4198:     return &mt($file_description);
1.112     bowersj2 4199: }
                   4200: 
                   4201: =pod
                   4202: 
1.648     raeburn  4203: =item * &filedescriptionex() 
1.112     bowersj2 4204: 
                   4205: returns description for a specified file type with
                   4206: extra formatting
                   4207: 
                   4208: =cut
                   4209: 
                   4210: sub filedescriptionex {
                   4211:     my $ex=shift;
1.188     matthew  4212:     my $file_description = $fd{lc($ex)};
                   4213:     $file_description =~ s:([\[\]]):~$1:g;
                   4214:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4215: }
                   4216: 
                   4217: # End of .tab access
                   4218: =pod
                   4219: 
                   4220: =back
                   4221: 
                   4222: =cut
                   4223: 
                   4224: # ------------------------------------------------------------------ File Types
                   4225: sub fileextensions {
                   4226:     return sort(keys(%fe));
                   4227: }
                   4228: 
1.97      www      4229: # ----------------------------------------------------------- Display Languages
                   4230: # returns a hash with all desired display languages
                   4231: #
                   4232: 
                   4233: sub display_languages {
                   4234:     my %languages=();
1.695     raeburn  4235:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4236: 	$languages{$lang}=1;
1.97      www      4237:     }
                   4238:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4239:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4240: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4241: 	    $languages{$lang}=1;
1.97      www      4242:         }
                   4243:     }
                   4244:     return %languages;
1.14      harris41 4245: }
                   4246: 
1.582     albertel 4247: sub languages {
                   4248:     my ($possible_langs) = @_;
1.695     raeburn  4249:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4250:     if (!ref($possible_langs)) {
                   4251: 	if( wantarray ) {
                   4252: 	    return @preferred_langs;
                   4253: 	} else {
                   4254: 	    return $preferred_langs[0];
                   4255: 	}
                   4256:     }
                   4257:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4258:     my @preferred_possibilities;
                   4259:     foreach my $preferred_lang (@preferred_langs) {
                   4260: 	if (exists($possibilities{$preferred_lang})) {
                   4261: 	    push(@preferred_possibilities, $preferred_lang);
                   4262: 	}
                   4263:     }
                   4264:     if( wantarray ) {
                   4265: 	return @preferred_possibilities;
                   4266:     }
                   4267:     return $preferred_possibilities[0];
                   4268: }
                   4269: 
1.742     raeburn  4270: sub user_lang {
                   4271:     my ($touname,$toudom,$fromcid) = @_;
                   4272:     my @userlangs;
                   4273:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4274:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4275:                     $env{'course.'.$fromcid.'.languages'}));
                   4276:     } else {
                   4277:         my %langhash = &getlangs($touname,$toudom);
                   4278:         if ($langhash{'languages'} ne '') {
                   4279:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4280:         } else {
                   4281:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4282:             if ($domdefs{'lang_def'} ne '') {
                   4283:                 @userlangs = ($domdefs{'lang_def'});
                   4284:             }
                   4285:         }
                   4286:     }
                   4287:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4288:     my $user_lh = Apache::localize->get_handle(@languages);
                   4289:     return $user_lh;
                   4290: }
                   4291: 
                   4292: 
1.112     bowersj2 4293: ###############################################################
                   4294: ##               Student Answer Attempts                     ##
                   4295: ###############################################################
                   4296: 
                   4297: =pod
                   4298: 
                   4299: =head1 Alternate Problem Views
                   4300: 
                   4301: =over 4
                   4302: 
1.648     raeburn  4303: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4304:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4305: 
                   4306: Return string with previous attempt on problem. Arguments:
                   4307: 
                   4308: =over 4
                   4309: 
                   4310: =item * $symb: Problem, including path
                   4311: 
                   4312: =item * $username: username of the desired student
                   4313: 
                   4314: =item * $domain: domain of the desired student
1.14      harris41 4315: 
1.112     bowersj2 4316: =item * $course: Course ID
1.14      harris41 4317: 
1.112     bowersj2 4318: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4319:     something
1.14      harris41 4320: 
1.112     bowersj2 4321: =item * $regexp: if string matches this regexp, the string will be
                   4322:     sent to $gradesub
1.14      harris41 4323: 
1.112     bowersj2 4324: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4325: 
1.1199    raeburn  4326: =item * $usec: section of the desired student
                   4327: 
                   4328: =item * $identifier: counter for student (multiple students one problem) or 
                   4329:     problem (one student; whole sequence).
                   4330: 
1.112     bowersj2 4331: =back
1.14      harris41 4332: 
1.112     bowersj2 4333: The output string is a table containing all desired attempts, if any.
1.16      harris41 4334: 
1.112     bowersj2 4335: =cut
1.1       albertel 4336: 
                   4337: sub get_previous_attempt {
1.1199    raeburn  4338:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4339:   my $prevattempts='';
1.43      ng       4340:   no strict 'refs';
1.1       albertel 4341:   if ($symb) {
1.3       albertel 4342:     my (%returnhash)=
                   4343:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4344:     if ($returnhash{'version'}) {
                   4345:       my %lasthash=();
                   4346:       my $version;
                   4347:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4348:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4349:             if ($key =~ /\.rawrndseed$/) {
                   4350:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4351:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4352:             } else {
                   4353:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4354:             }
1.19      harris41 4355:         }
1.1       albertel 4356:       }
1.596     albertel 4357:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4358:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4359:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4360:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4361:       foreach my $key (sort(keys(%lasthash))) {
                   4362: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4363: 	if ($#parts > 0) {
1.31      albertel 4364: 	  my $data=$parts[-1];
1.989     raeburn  4365:           next if ($data eq 'foilorder');
1.31      albertel 4366: 	  pop(@parts);
1.1010    www      4367:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4368:           if ($data eq 'type') {
                   4369:               unless ($showsurv) {
                   4370:                   my $id = join(',',@parts);
                   4371:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4372:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4373:                       $lasthidden{$ign.'.'.$id} = 1;
                   4374:                   }
1.945     raeburn  4375:               }
1.1199    raeburn  4376:               if ($identifier ne '') {
                   4377:                   my $id = join(',',@parts);
                   4378:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4379:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4380:                       $hidestatus{$ign.'.'.$id} = 1;
                   4381:                   }
                   4382:               }
                   4383:           } elsif ($data eq 'regrader') {
                   4384:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4385:                   my $id = join(',',@parts);
                   4386:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4387:               }
1.1010    www      4388:           } 
1.31      albertel 4389: 	} else {
1.41      ng       4390: 	  if ($#parts == 0) {
                   4391: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4392: 	  } else {
                   4393: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4394: 	  }
1.31      albertel 4395: 	}
1.16      harris41 4396:       }
1.596     albertel 4397:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4398:       if ($getattempt eq '') {
1.1199    raeburn  4399:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4400:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4401:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4402:                 foreach my $id (keys(%regraded)) {
                   4403:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4404:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4405:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4406:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4407:                     }
                   4408:                 }
                   4409:             }
1.1200    raeburn  4410:         }
                   4411: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4412:             my (@hidden,@unsolved);
1.945     raeburn  4413:             if (%typeparts) {
                   4414:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4415:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4416:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4417:                         push(@hidden,$id);
1.1199    raeburn  4418:                     } elsif ($identifier ne '') {
                   4419:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4420:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4421:                                 ($hidestatus{$id})) {
1.1200    raeburn  4422:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4423:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4424:                                 push(@{$solved{$id}},$version);
                   4425:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4426:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4427:                                 my $skip;
                   4428:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4429:                                     foreach my $reset (@{$resets{$id}}) {
                   4430:                                         if ($reset > $solved{$id}[-1]) {
                   4431:                                             $skip=1;
                   4432:                                             last;
                   4433:                                         }
                   4434:                                     }
                   4435:                                 }
                   4436:                                 unless ($skip) {
                   4437:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4438:                                     push(@unsolved,$partslist);
                   4439:                                 }
                   4440:                             }
                   4441:                         }
1.945     raeburn  4442:                     }
                   4443:                 }
                   4444:             }
                   4445:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4446:                            '<td>'.&mt('Transaction [_1]',$version);
                   4447:             if (@unsolved) {
                   4448:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4449:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4450:                                  &mt('Hide').'</label></span>';
                   4451:             }
                   4452:             $prevattempts .= '</td>';
1.945     raeburn  4453:             if (@hidden) {
                   4454:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4455:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4456:                     my $hide;
                   4457:                     foreach my $id (@hidden) {
                   4458:                         if ($key =~ /^\Q$id\E/) {
                   4459:                             $hide = 1;
                   4460:                             last;
                   4461:                         }
                   4462:                     }
                   4463:                     if ($hide) {
                   4464:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4465:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4466:                             my $value = &format_previous_attempt_value($key,
                   4467:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4468:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4469:                         } else {
                   4470:                             $prevattempts.='<td>&nbsp;</td>';
                   4471:                         }
                   4472:                     } else {
                   4473:                         if ($key =~ /\./) {
1.1212    raeburn  4474:                             my $value = $returnhash{$version.':'.$key};
                   4475:                             if ($key =~ /\.rndseed$/) {
                   4476:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4477:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4478:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4479:                                 }
                   4480:                             }
                   4481:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4482:                                            '&nbsp;</td>';
1.945     raeburn  4483:                         } else {
                   4484:                             $prevattempts.='<td>&nbsp;</td>';
                   4485:                         }
                   4486:                     }
                   4487:                 }
                   4488:             } else {
                   4489: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4490:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4491:                     my $value = $returnhash{$version.':'.$key};
                   4492:                     if ($key =~ /\.rndseed$/) {
                   4493:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4494:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4495:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4496:                         }
                   4497:                     }
                   4498:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4499:                                    '&nbsp;</td>';
1.945     raeburn  4500: 	        }
                   4501:             }
                   4502: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4503: 	 }
1.1       albertel 4504:       }
1.945     raeburn  4505:       my @currhidden = keys(%lasthidden);
1.596     albertel 4506:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4507:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4508:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4509:           if (%typeparts) {
                   4510:               my $hidden;
                   4511:               foreach my $id (@currhidden) {
                   4512:                   if ($key =~ /^\Q$id\E/) {
                   4513:                       $hidden = 1;
                   4514:                       last;
                   4515:                   }
                   4516:               }
                   4517:               if ($hidden) {
                   4518:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4519:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4520:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4521:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4522:                           $value = &$gradesub($value);
                   4523:                       }
1.1173    kruse    4524:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4525:                   } else {
                   4526:                       $prevattempts.='<td>&nbsp;</td>';
                   4527:                   }
                   4528:               } else {
                   4529:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4530:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4531:                       $value = &$gradesub($value);
                   4532:                   }
1.1173    kruse    4533:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4534:               }
                   4535:           } else {
                   4536: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4537: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4538:                   $value = &$gradesub($value);
                   4539:               }
1.1173    kruse    4540: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4541:           }
1.16      harris41 4542:       }
1.596     albertel 4543:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4544:     } else {
1.596     albertel 4545:       $prevattempts=
                   4546: 	  &start_data_table().&start_data_table_row().
                   4547: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4548: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4549:     }
                   4550:   } else {
1.596     albertel 4551:     $prevattempts=
                   4552: 	  &start_data_table().&start_data_table_row().
                   4553: 	  '<td>'.&mt('No data.').'</td>'.
                   4554: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4555:   }
1.10      albertel 4556: }
                   4557: 
1.581     albertel 4558: sub format_previous_attempt_value {
                   4559:     my ($key,$value) = @_;
1.1011    www      4560:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4561:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4562:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4563:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4564:     } elsif ($key =~ /answerstring$/) {
                   4565:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4566:         my @answer = %answers;
                   4567:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4568:         my @anskeys = sort(keys(%answers));
                   4569:         if (@anskeys == 1) {
                   4570:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4571:             if ($answer =~ m{\0}) {
                   4572:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4573:             }
                   4574:             my $tag_internal_answer_name = 'INTERNAL';
                   4575:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4576:                 $value = $answer; 
                   4577:             } else {
                   4578:                 $value = $anskeys[0].'='.$answer;
                   4579:             }
                   4580:         } else {
                   4581:             foreach my $ans (@anskeys) {
                   4582:                 my $answer = $answers{$ans};
1.1001    raeburn  4583:                 if ($answer =~ m{\0}) {
                   4584:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4585:                 }
                   4586:                 $value .=  $ans.'='.$answer.'<br />';;
                   4587:             } 
                   4588:         }
1.581     albertel 4589:     } else {
1.1173    kruse    4590:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4591:     }
                   4592:     return $value;
                   4593: }
                   4594: 
                   4595: 
1.107     albertel 4596: sub relative_to_absolute {
                   4597:     my ($url,$output)=@_;
                   4598:     my $parser=HTML::TokeParser->new(\$output);
                   4599:     my $token;
                   4600:     my $thisdir=$url;
                   4601:     my @rlinks=();
                   4602:     while ($token=$parser->get_token) {
                   4603: 	if ($token->[0] eq 'S') {
                   4604: 	    if ($token->[1] eq 'a') {
                   4605: 		if ($token->[2]->{'href'}) {
                   4606: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4607: 		}
                   4608: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4609: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4610: 	    } elsif ($token->[1] eq 'base') {
                   4611: 		$thisdir=$token->[2]->{'href'};
                   4612: 	    }
                   4613: 	}
                   4614:     }
                   4615:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4616:     foreach my $link (@rlinks) {
1.726     raeburn  4617: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4618: 		($link=~/^\//) ||
                   4619: 		($link=~/^javascript:/i) ||
                   4620: 		($link=~/^mailto:/i) ||
                   4621: 		($link=~/^\#/)) {
                   4622: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4623: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4624: 	}
                   4625:     }
                   4626: # -------------------------------------------------- Deal with Applet codebases
                   4627:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4628:     return $output;
                   4629: }
                   4630: 
1.112     bowersj2 4631: =pod
                   4632: 
1.648     raeburn  4633: =item * &get_student_view()
1.112     bowersj2 4634: 
                   4635: show a snapshot of what student was looking at
                   4636: 
                   4637: =cut
                   4638: 
1.10      albertel 4639: sub get_student_view {
1.186     albertel 4640:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4641:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4642:   my (%form);
1.10      albertel 4643:   my @elements=('symb','courseid','domain','username');
                   4644:   foreach my $element (@elements) {
1.186     albertel 4645:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4646:   }
1.186     albertel 4647:   if (defined($moreenv)) {
                   4648:       %form=(%form,%{$moreenv});
                   4649:   }
1.236     albertel 4650:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4651:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4652:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4653:   $userview=~s/\<body[^\>]*\>//gi;
                   4654:   $userview=~s/\<\/body\>//gi;
                   4655:   $userview=~s/\<html\>//gi;
                   4656:   $userview=~s/\<\/html\>//gi;
                   4657:   $userview=~s/\<head\>//gi;
                   4658:   $userview=~s/\<\/head\>//gi;
                   4659:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4660:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4661:   if (wantarray) {
                   4662:      return ($userview,$response);
                   4663:   } else {
                   4664:      return $userview;
                   4665:   }
                   4666: }
                   4667: 
                   4668: sub get_student_view_with_retries {
                   4669:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4670: 
                   4671:     my $ok = 0;                 # True if we got a good response.
                   4672:     my $content;
                   4673:     my $response;
                   4674: 
                   4675:     # Try to get the student_view done. within the retries count:
                   4676:     
                   4677:     do {
                   4678:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4679:          $ok      = $response->is_success;
                   4680:          if (!$ok) {
                   4681:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4682:          }
                   4683:          $retries--;
                   4684:     } while (!$ok && ($retries > 0));
                   4685:     
                   4686:     if (!$ok) {
                   4687:        $content = '';          # On error return an empty content.
                   4688:     }
1.651     www      4689:     if (wantarray) {
                   4690:        return ($content, $response);
                   4691:     } else {
                   4692:        return $content;
                   4693:     }
1.11      albertel 4694: }
                   4695: 
1.112     bowersj2 4696: =pod
                   4697: 
1.648     raeburn  4698: =item * &get_student_answers() 
1.112     bowersj2 4699: 
                   4700: show a snapshot of how student was answering problem
                   4701: 
                   4702: =cut
                   4703: 
1.11      albertel 4704: sub get_student_answers {
1.100     sakharuk 4705:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4706:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4707:   my (%moreenv);
1.11      albertel 4708:   my @elements=('symb','courseid','domain','username');
                   4709:   foreach my $element (@elements) {
1.186     albertel 4710:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4711:   }
1.186     albertel 4712:   $moreenv{'grade_target'}='answer';
                   4713:   %moreenv=(%form,%moreenv);
1.497     raeburn  4714:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4715:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4716:   return $userview;
1.1       albertel 4717: }
1.116     albertel 4718: 
                   4719: =pod
                   4720: 
                   4721: =item * &submlink()
                   4722: 
1.242     albertel 4723: Inputs: $text $uname $udom $symb $target
1.116     albertel 4724: 
                   4725: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4726: 
                   4727: =cut
                   4728: 
                   4729: ###############################################
                   4730: sub submlink {
1.242     albertel 4731:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4732:     if (!($uname && $udom)) {
                   4733: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4734: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4735: 	if (!$symb) { $symb=$cursymb; }
                   4736:     }
1.254     matthew  4737:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4738:     $symb=&escape($symb);
1.960     bisitz   4739:     if ($target) { $target=" target=\"$target\""; }
                   4740:     return
                   4741:         '<a href="/adm/grades?command=submission'.
                   4742:         '&amp;symb='.$symb.
                   4743:         '&amp;student='.$uname.
                   4744:         '&amp;userdom='.$udom.'"'.
                   4745:         $target.'>'.$text.'</a>';
1.242     albertel 4746: }
                   4747: ##############################################
                   4748: 
                   4749: =pod
                   4750: 
                   4751: =item * &pgrdlink()
                   4752: 
                   4753: Inputs: $text $uname $udom $symb $target
                   4754: 
                   4755: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4756: 
                   4757: =cut
                   4758: 
                   4759: ###############################################
                   4760: sub pgrdlink {
                   4761:     my $link=&submlink(@_);
                   4762:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4763:     return $link;
                   4764: }
                   4765: ##############################################
                   4766: 
                   4767: =pod
                   4768: 
                   4769: =item * &pprmlink()
                   4770: 
                   4771: Inputs: $text $uname $udom $symb $target
                   4772: 
                   4773: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4774: student and a specific resource
1.242     albertel 4775: 
                   4776: =cut
                   4777: 
                   4778: ###############################################
                   4779: sub pprmlink {
                   4780:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4781:     if (!($uname && $udom)) {
                   4782: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4783: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4784: 	if (!$symb) { $symb=$cursymb; }
                   4785:     }
1.254     matthew  4786:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4787:     $symb=&escape($symb);
1.242     albertel 4788:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4789:     return '<a href="/adm/parmset?command=set&amp;'.
                   4790: 	'symb='.$symb.'&amp;uname='.$uname.
                   4791: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4792: }
                   4793: ##############################################
1.37      matthew  4794: 
1.112     bowersj2 4795: =pod
                   4796: 
                   4797: =back
                   4798: 
                   4799: =cut
                   4800: 
1.37      matthew  4801: ###############################################
1.51      www      4802: 
                   4803: 
                   4804: sub timehash {
1.687     raeburn  4805:     my ($thistime) = @_;
                   4806:     my $timezone = &Apache::lonlocal::gettimezone();
                   4807:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4808:                      ->set_time_zone($timezone);
                   4809:     my $wday = $dt->day_of_week();
                   4810:     if ($wday == 7) { $wday = 0; }
                   4811:     return ( 'second' => $dt->second(),
                   4812:              'minute' => $dt->minute(),
                   4813:              'hour'   => $dt->hour(),
                   4814:              'day'     => $dt->day_of_month(),
                   4815:              'month'   => $dt->month(),
                   4816:              'year'    => $dt->year(),
                   4817:              'weekday' => $wday,
                   4818:              'dayyear' => $dt->day_of_year(),
                   4819:              'dlsav'   => $dt->is_dst() );
1.51      www      4820: }
                   4821: 
1.370     www      4822: sub utc_string {
                   4823:     my ($date)=@_;
1.371     www      4824:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4825: }
                   4826: 
1.51      www      4827: sub maketime {
                   4828:     my %th=@_;
1.687     raeburn  4829:     my ($epoch_time,$timezone,$dt);
                   4830:     $timezone = &Apache::lonlocal::gettimezone();
                   4831:     eval {
                   4832:         $dt = DateTime->new( year   => $th{'year'},
                   4833:                              month  => $th{'month'},
                   4834:                              day    => $th{'day'},
                   4835:                              hour   => $th{'hour'},
                   4836:                              minute => $th{'minute'},
                   4837:                              second => $th{'second'},
                   4838:                              time_zone => $timezone,
                   4839:                          );
                   4840:     };
                   4841:     if (!$@) {
                   4842:         $epoch_time = $dt->epoch;
                   4843:         if ($epoch_time) {
                   4844:             return $epoch_time;
                   4845:         }
                   4846:     }
1.51      www      4847:     return POSIX::mktime(
                   4848:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4849:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4850: }
                   4851: 
                   4852: #########################################
1.51      www      4853: 
                   4854: sub findallcourses {
1.482     raeburn  4855:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4856:     my %roles;
                   4857:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4858:     my %courses;
1.51      www      4859:     my $now=time;
1.482     raeburn  4860:     if (!defined($uname)) {
                   4861:         $uname = $env{'user.name'};
                   4862:     }
                   4863:     if (!defined($udom)) {
                   4864:         $udom = $env{'user.domain'};
                   4865:     }
                   4866:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4867:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4868:         if (!%roles) {
                   4869:             %roles = (
                   4870:                        cc => 1,
1.907     raeburn  4871:                        co => 1,
1.482     raeburn  4872:                        in => 1,
                   4873:                        ep => 1,
                   4874:                        ta => 1,
                   4875:                        cr => 1,
                   4876:                        st => 1,
                   4877:              );
                   4878:         }
                   4879:         foreach my $entry (keys(%roleshash)) {
                   4880:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4881:             if ($trole =~ /^cr/) { 
                   4882:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4883:             } else {
                   4884:                 next if (!exists($roles{$trole}));
                   4885:             }
                   4886:             if ($tend) {
                   4887:                 next if ($tend < $now);
                   4888:             }
                   4889:             if ($tstart) {
                   4890:                 next if ($tstart > $now);
                   4891:             }
1.1058    raeburn  4892:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4893:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4894:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4895:             if ($secpart eq '') {
                   4896:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4897:                 $sec = 'none';
1.1058    raeburn  4898:                 $value .= $cnum.'/';
1.482     raeburn  4899:             } else {
                   4900:                 $cnum = $cnumpart;
                   4901:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4902:                 $value .= $cnum.'/'.$sec;
                   4903:             }
                   4904:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4905:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4906:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4907:                 }
                   4908:             } else {
                   4909:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4910:             }
1.482     raeburn  4911:         }
                   4912:     } else {
                   4913:         foreach my $key (keys(%env)) {
1.483     albertel 4914: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4915:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4916: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4917: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4918: 	        next if (%roles && !exists($roles{$role}));
                   4919: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4920:                 my $active=1;
                   4921:                 if ($starttime) {
                   4922: 		    if ($now<$starttime) { $active=0; }
                   4923:                 }
                   4924:                 if ($endtime) {
                   4925:                     if ($now>$endtime) { $active=0; }
                   4926:                 }
                   4927:                 if ($active) {
1.1058    raeburn  4928:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4929:                     if ($sec eq '') {
                   4930:                         $sec = 'none';
1.1058    raeburn  4931:                     } else {
                   4932:                         $value .= $sec;
                   4933:                     }
                   4934:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4935:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4936:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4937:                         }
                   4938:                     } else {
                   4939:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4940:                     }
1.474     raeburn  4941:                 }
                   4942:             }
1.51      www      4943:         }
                   4944:     }
1.474     raeburn  4945:     return %courses;
1.51      www      4946: }
1.37      matthew  4947: 
1.54      www      4948: ###############################################
1.474     raeburn  4949: 
                   4950: sub blockcheck {
1.1189    raeburn  4951:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4952: 
1.1189    raeburn  4953:     if (defined($udom) && defined($uname)) {
                   4954:         # If uname and udom are for a course, check for blocks in the course.
                   4955:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4956:             my ($startblock,$endblock,$triggerblock) =
                   4957:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4958:             return ($startblock,$endblock,$triggerblock);
                   4959:         }
                   4960:     } else {
1.490     raeburn  4961:         $udom = $env{'user.domain'};
                   4962:         $uname = $env{'user.name'};
                   4963:     }
                   4964: 
1.502     raeburn  4965:     my $startblock = 0;
                   4966:     my $endblock = 0;
1.1062    raeburn  4967:     my $triggerblock = '';
1.482     raeburn  4968:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4969: 
1.490     raeburn  4970:     # If uname is for a user, and activity is course-specific, i.e.,
                   4971:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4972: 
1.490     raeburn  4973:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1189    raeburn  4974:          $activity eq 'groups' || $activity eq 'printout') &&
                   4975:         ($env{'request.course.id'})) {
1.490     raeburn  4976:         foreach my $key (keys(%live_courses)) {
                   4977:             if ($key ne $env{'request.course.id'}) {
                   4978:                 delete($live_courses{$key});
                   4979:             }
                   4980:         }
                   4981:     }
                   4982: 
                   4983:     my $otheruser = 0;
                   4984:     my %own_courses;
                   4985:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4986:         # Resource belongs to user other than current user.
                   4987:         $otheruser = 1;
                   4988:         # Gather courses for current user
                   4989:         %own_courses = 
                   4990:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4991:     }
                   4992: 
                   4993:     # Gather active course roles - course coordinator, instructor, 
                   4994:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4995: 
                   4996:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4997:         my ($cdom,$cnum);
                   4998:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4999:             $cdom = $env{'course.'.$course.'.domain'};
                   5000:             $cnum = $env{'course.'.$course.'.num'};
                   5001:         } else {
1.490     raeburn  5002:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5003:         }
                   5004:         my $no_ownblock = 0;
                   5005:         my $no_userblock = 0;
1.533     raeburn  5006:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5007:             # Check if current user has 'evb' priv for this
                   5008:             if (defined($own_courses{$course})) {
                   5009:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5010:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5011:                     if ($sec ne 'none') {
                   5012:                         $checkrole .= '/'.$sec;
                   5013:                     }
                   5014:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5015:                         $no_ownblock = 1;
                   5016:                         last;
                   5017:                     }
                   5018:                 }
                   5019:             }
                   5020:             # if they have 'evb' priv and are currently not playing student
                   5021:             next if (($no_ownblock) &&
                   5022:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5023:         }
1.474     raeburn  5024:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5025:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5026:             if ($sec ne 'none') {
1.482     raeburn  5027:                 $checkrole .= '/'.$sec;
1.474     raeburn  5028:             }
1.490     raeburn  5029:             if ($otheruser) {
                   5030:                 # Resource belongs to user other than current user.
                   5031:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5032:                 my (%allroles,%userroles);
                   5033:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5034:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5035:                         my ($trole,$tdom,$tnum,$tsec);
                   5036:                         if ($entry =~ /^cr/) {
                   5037:                             ($trole,$tdom,$tnum,$tsec) = 
                   5038:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5039:                         } else {
                   5040:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5041:                         }
                   5042:                         my ($spec,$area,$trest);
                   5043:                         $area = '/'.$tdom.'/'.$tnum;
                   5044:                         $trest = $tnum;
                   5045:                         if ($tsec ne '') {
                   5046:                             $area .= '/'.$tsec;
                   5047:                             $trest .= '/'.$tsec;
                   5048:                         }
                   5049:                         $spec = $trole.'.'.$area;
                   5050:                         if ($trole =~ /^cr/) {
                   5051:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5052:                                                               $tdom,$spec,$trest,$area);
                   5053:                         } else {
                   5054:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5055:                                                                 $tdom,$spec,$trest,$area);
                   5056:                         }
                   5057:                     }
                   5058:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   5059:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5060:                         if ($1) {
                   5061:                             $no_userblock = 1;
                   5062:                             last;
                   5063:                         }
1.486     raeburn  5064:                     }
                   5065:                 }
1.490     raeburn  5066:             } else {
                   5067:                 # Resource belongs to current user
                   5068:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5069:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5070:                     $no_ownblock = 1;
                   5071:                     last;
                   5072:                 }
1.474     raeburn  5073:             }
                   5074:         }
                   5075:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5076:         next if (($no_ownblock) &&
1.491     albertel 5077:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5078:         next if ($no_userblock);
1.474     raeburn  5079: 
1.866     kalberla 5080:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  5081:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  5082:         
1.1062    raeburn  5083:         my ($start,$end,$trigger) = 
                   5084:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  5085:         if (($start != 0) && 
                   5086:             (($startblock == 0) || ($startblock > $start))) {
                   5087:             $startblock = $start;
1.1062    raeburn  5088:             if ($trigger ne '') {
                   5089:                 $triggerblock = $trigger;
                   5090:             }
1.502     raeburn  5091:         }
                   5092:         if (($end != 0)  &&
                   5093:             (($endblock == 0) || ($endblock < $end))) {
                   5094:             $endblock = $end;
1.1062    raeburn  5095:             if ($trigger ne '') {
                   5096:                 $triggerblock = $trigger;
                   5097:             }
1.502     raeburn  5098:         }
1.490     raeburn  5099:     }
1.1062    raeburn  5100:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5101: }
                   5102: 
                   5103: sub get_blocks {
1.1062    raeburn  5104:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  5105:     my $startblock = 0;
                   5106:     my $endblock = 0;
1.1062    raeburn  5107:     my $triggerblock = '';
1.490     raeburn  5108:     my $course = $cdom.'_'.$cnum;
                   5109:     $setters->{$course} = {};
                   5110:     $setters->{$course}{'staff'} = [];
                   5111:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5112:     $setters->{$course}{'triggers'} = [];
                   5113:     my (@blockers,%triggered);
                   5114:     my $now = time;
                   5115:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5116:     if ($activity eq 'docs') {
                   5117:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   5118:         foreach my $block (@blockers) {
                   5119:             if ($block =~ /^firstaccess____(.+)$/) {
                   5120:                 my $item = $1;
                   5121:                 my $type = 'map';
                   5122:                 my $timersymb = $item;
                   5123:                 if ($item eq 'course') {
                   5124:                     $type = 'course';
                   5125:                 } elsif ($item =~ /___\d+___/) {
                   5126:                     $type = 'resource';
                   5127:                 } else {
                   5128:                     $timersymb = &Apache::lonnet::symbread($item);
                   5129:                 }
                   5130:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5131:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5132:                 $triggered{$block} = {
                   5133:                                        start => $start,
                   5134:                                        end   => $end,
                   5135:                                        type  => $type,
                   5136:                                      };
                   5137:             }
                   5138:         }
                   5139:     } else {
                   5140:         foreach my $block (keys(%commblocks)) {
                   5141:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5142:                 my ($start,$end) = ($1,$2);
                   5143:                 if ($start <= time && $end >= time) {
                   5144:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5145:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5146:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5147:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5148:                                     push(@blockers,$block);
                   5149:                                 }
                   5150:                             }
                   5151:                         }
                   5152:                     }
                   5153:                 }
                   5154:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5155:                 my $item = $1;
                   5156:                 my $timersymb = $item; 
                   5157:                 my $type = 'map';
                   5158:                 if ($item eq 'course') {
                   5159:                     $type = 'course';
                   5160:                 } elsif ($item =~ /___\d+___/) {
                   5161:                     $type = 'resource';
                   5162:                 } else {
                   5163:                     $timersymb = &Apache::lonnet::symbread($item);
                   5164:                 }
                   5165:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5166:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5167:                 if ($start && $end) {
                   5168:                     if (($start <= time) && ($end >= time)) {
                   5169:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   5170:                             push(@blockers,$block);
                   5171:                             $triggered{$block} = {
                   5172:                                                    start => $start,
                   5173:                                                    end   => $end,
                   5174:                                                    type  => $type,
                   5175:                                                  };
                   5176:                         }
                   5177:                     }
1.490     raeburn  5178:                 }
1.1062    raeburn  5179:             }
                   5180:         }
                   5181:     }
                   5182:     foreach my $blocker (@blockers) {
                   5183:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5184:             &parse_block_record($commblocks{$blocker});
                   5185:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5186:         my ($start,$end,$triggertype);
                   5187:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5188:             ($start,$end) = ($1,$2);
                   5189:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5190:             $start = $triggered{$blocker}{'start'};
                   5191:             $end = $triggered{$blocker}{'end'};
                   5192:             $triggertype = $triggered{$blocker}{'type'};
                   5193:         }
                   5194:         if ($start) {
                   5195:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5196:             if ($triggertype) {
                   5197:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5198:             } else {
                   5199:                 push(@{$$setters{$course}{'triggers'}},0);
                   5200:             }
                   5201:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5202:                 $startblock = $start;
                   5203:                 if ($triggertype) {
                   5204:                     $triggerblock = $blocker;
1.474     raeburn  5205:                 }
                   5206:             }
1.1062    raeburn  5207:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5208:                $endblock = $end;
                   5209:                if ($triggertype) {
                   5210:                    $triggerblock = $blocker;
                   5211:                }
                   5212:             }
1.474     raeburn  5213:         }
                   5214:     }
1.1062    raeburn  5215:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5216: }
                   5217: 
                   5218: sub parse_block_record {
                   5219:     my ($record) = @_;
                   5220:     my ($setuname,$setudom,$title,$blocks);
                   5221:     if (ref($record) eq 'HASH') {
                   5222:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5223:         $title = &unescape($record->{'event'});
                   5224:         $blocks = $record->{'blocks'};
                   5225:     } else {
                   5226:         my @data = split(/:/,$record,3);
                   5227:         if (scalar(@data) eq 2) {
                   5228:             $title = $data[1];
                   5229:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5230:         } else {
                   5231:             ($setuname,$setudom,$title) = @data;
                   5232:         }
                   5233:         $blocks = { 'com' => 'on' };
                   5234:     }
                   5235:     return ($setuname,$setudom,$title,$blocks);
                   5236: }
                   5237: 
1.854     kalberla 5238: sub blocking_status {
1.1189    raeburn  5239:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  5240:     my %setters;
1.890     droeschl 5241: 
1.1061    raeburn  5242: # check for active blocking
1.1062    raeburn  5243:     my ($startblock,$endblock,$triggerblock) = 
1.1189    raeburn  5244:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  5245:     my $blocked = 0;
                   5246:     if ($startblock && $endblock) {
                   5247:         $blocked = 1;
                   5248:     }
1.890     droeschl 5249: 
1.1061    raeburn  5250: # caller just wants to know whether a block is active
                   5251:     if (!wantarray) { return $blocked; }
                   5252: 
                   5253: # build a link to a popup window containing the details
                   5254:     my $querystring  = "?activity=$activity";
                   5255: # $uname and $udom decide whose portfolio the user is trying to look at
1.1232    raeburn  5256:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   5257:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5258:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5259:     } elsif ($activity eq 'docs') {
                   5260:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   5261:     }
1.1061    raeburn  5262: 
                   5263:     my $output .= <<'END_MYBLOCK';
                   5264: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5265:     var options = "width=" + w + ",height=" + h + ",";
                   5266:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5267:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5268:     var newWin = window.open(url, wdwName, options);
                   5269:     newWin.focus();
                   5270: }
1.890     droeschl 5271: END_MYBLOCK
1.854     kalberla 5272: 
1.1061    raeburn  5273:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5274:   
1.1061    raeburn  5275:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5276:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5277:     my $class = 'LC_comblock';
1.1062    raeburn  5278:     if ($activity eq 'docs') {
                   5279:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5280:         $class = '';
1.1063    raeburn  5281:     } elsif ($activity eq 'printout') {
                   5282:         $text = &mt('Printing Blocked');
1.1232    raeburn  5283:     } elsif ($activity eq 'passwd') {
                   5284:         $text = &mt('Password Changing Blocked');
1.1062    raeburn  5285:     }
1.1061    raeburn  5286:     $output .= <<"END_BLOCK";
1.1217    raeburn  5287: <div class='$class'>
1.869     kalberla 5288:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5289:   title='$text'>
                   5290:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5291:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5292:   title='$text'>$text</a>
1.867     kalberla 5293: </div>
                   5294: 
                   5295: END_BLOCK
1.474     raeburn  5296: 
1.1061    raeburn  5297:     return ($blocked, $output);
1.854     kalberla 5298: }
1.490     raeburn  5299: 
1.60      matthew  5300: ###############################################
                   5301: 
1.682     raeburn  5302: sub check_ip_acc {
1.1201    raeburn  5303:     my ($acc,$clientip)=@_;
1.682     raeburn  5304:     &Apache::lonxml::debug("acc is $acc");
                   5305:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5306:         return 1;
                   5307:     }
1.1219    raeburn  5308:     my $allowed;
1.1252    raeburn  5309:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
1.682     raeburn  5310: 
                   5311:     my $name;
1.1219    raeburn  5312:     my %access = (
                   5313:                      allowfrom => 1,
                   5314:                      denyfrom  => 0,
                   5315:                  );
                   5316:     my @allows;
                   5317:     my @denies;
                   5318:     foreach my $item (split(',',$acc)) {
                   5319:         $item =~ s/^\s*//;
                   5320:         $item =~ s/\s*$//;
                   5321:         my $pattern;
                   5322:         if ($item =~ /^\!(.+)$/) {
                   5323:             push(@denies,$1);
                   5324:         } else {
                   5325:             push(@allows,$item);
                   5326:         }
                   5327:    }
                   5328:    my $numdenies = scalar(@denies);
                   5329:    my $numallows = scalar(@allows);
                   5330:    my $count = 0;
                   5331:    foreach my $pattern (@denies,@allows) {
                   5332:         $count ++; 
                   5333:         my $acctype = 'allowfrom';
                   5334:         if ($count <= $numdenies) {
                   5335:             $acctype = 'denyfrom';
                   5336:         }
1.682     raeburn  5337:         if ($pattern =~ /\*$/) {
                   5338:             #35.8.*
                   5339:             $pattern=~s/\*//;
1.1219    raeburn  5340:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5341:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5342:             #35.8.3.[34-56]
                   5343:             my $low=$2;
                   5344:             my $high=$3;
                   5345:             $pattern=$1;
                   5346:             if ($ip =~ /^\Q$pattern\E/) {
                   5347:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5348:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5349:             }
                   5350:         } elsif ($pattern =~ /^\*/) {
                   5351:             #*.msu.edu
                   5352:             $pattern=~s/\*//;
                   5353:             if (!defined($name)) {
                   5354:                 use Socket;
                   5355:                 my $netaddr=inet_aton($ip);
                   5356:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5357:             }
1.1219    raeburn  5358:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5359:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5360:             #127.0.0.1
1.1219    raeburn  5361:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5362:         } else {
                   5363:             #some.name.com
                   5364:             if (!defined($name)) {
                   5365:                 use Socket;
                   5366:                 my $netaddr=inet_aton($ip);
                   5367:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5368:             }
1.1219    raeburn  5369:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5370:         }
                   5371:         if ($allowed =~ /^(0|1)$/) { last; }
                   5372:     }
                   5373:     if ($allowed eq '') {
                   5374:         if ($numdenies && !$numallows) {
                   5375:             $allowed = 1;
                   5376:         } else {
                   5377:             $allowed = 0;
1.682     raeburn  5378:         }
                   5379:     }
                   5380:     return $allowed;
                   5381: }
                   5382: 
                   5383: ###############################################
                   5384: 
1.60      matthew  5385: =pod
                   5386: 
1.112     bowersj2 5387: =head1 Domain Template Functions
                   5388: 
                   5389: =over 4
                   5390: 
                   5391: =item * &determinedomain()
1.60      matthew  5392: 
                   5393: Inputs: $domain (usually will be undef)
                   5394: 
1.63      www      5395: Returns: Determines which domain should be used for designs
1.60      matthew  5396: 
                   5397: =cut
1.54      www      5398: 
1.60      matthew  5399: ###############################################
1.63      www      5400: sub determinedomain {
                   5401:     my $domain=shift;
1.531     albertel 5402:     if (! $domain) {
1.60      matthew  5403:         # Determine domain if we have not been given one
1.893     raeburn  5404:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5405:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5406:         if ($env{'request.role.domain'}) { 
                   5407:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5408:         }
                   5409:     }
1.63      www      5410:     return $domain;
                   5411: }
                   5412: ###############################################
1.517     raeburn  5413: 
1.518     albertel 5414: sub devalidate_domconfig_cache {
                   5415:     my ($udom)=@_;
                   5416:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5417: }
                   5418: 
                   5419: # ---------------------- Get domain configuration for a domain
                   5420: sub get_domainconf {
                   5421:     my ($udom) = @_;
                   5422:     my $cachetime=1800;
                   5423:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5424:     if (defined($cached)) { return %{$result}; }
                   5425: 
                   5426:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5427: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5428:     my (%designhash,%legacy);
1.518     albertel 5429:     if (keys(%domconfig) > 0) {
                   5430:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5431:             if (keys(%{$domconfig{'login'}})) {
                   5432:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5433:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5434:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5435:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5436:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5437:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5438:                                         if ($key eq 'loginvia') {
                   5439:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5440:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5441:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5442:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5443: 
                   5444:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5445:                                                 } else {
                   5446:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5447:                                                 }
1.948     raeburn  5448:                                             }
1.1208    raeburn  5449:                                         } elsif ($key eq 'headtag') {
                   5450:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5451:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5452:                                             }
1.946     raeburn  5453:                                         }
1.1208    raeburn  5454:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5455:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5456:                                         }
1.946     raeburn  5457:                                     }
                   5458:                                 }
                   5459:                             }
                   5460:                         } else {
                   5461:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5462:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5463:                                     $domconfig{'login'}{$key}{$img};
                   5464:                             }
1.699     raeburn  5465:                         }
                   5466:                     } else {
                   5467:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5468:                     }
1.632     raeburn  5469:                 }
                   5470:             } else {
                   5471:                 $legacy{'login'} = 1;
1.518     albertel 5472:             }
1.632     raeburn  5473:         } else {
                   5474:             $legacy{'login'} = 1;
1.518     albertel 5475:         }
                   5476:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5477:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5478:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5479:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5480:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5481:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5482:                         }
1.518     albertel 5483:                     }
                   5484:                 }
1.632     raeburn  5485:             } else {
                   5486:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5487:             }
1.632     raeburn  5488:         } else {
                   5489:             $legacy{'rolecolors'} = 1;
1.518     albertel 5490:         }
1.948     raeburn  5491:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5492:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5493:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5494:             }
                   5495:         }
1.632     raeburn  5496:         if (keys(%legacy) > 0) {
                   5497:             my %legacyhash = &get_legacy_domconf($udom);
                   5498:             foreach my $item (keys(%legacyhash)) {
                   5499:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5500:                     if ($legacy{'login'}) { 
                   5501:                         $designhash{$item} = $legacyhash{$item};
                   5502:                     }
                   5503:                 } else {
                   5504:                     if ($legacy{'rolecolors'}) {
                   5505:                         $designhash{$item} = $legacyhash{$item};
                   5506:                     }
1.518     albertel 5507:                 }
                   5508:             }
                   5509:         }
1.632     raeburn  5510:     } else {
                   5511:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5512:     }
                   5513:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5514: 				  $cachetime);
                   5515:     return %designhash;
                   5516: }
                   5517: 
1.632     raeburn  5518: sub get_legacy_domconf {
                   5519:     my ($udom) = @_;
                   5520:     my %legacyhash;
                   5521:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5522:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5523:     if (-e $designfile) {
                   5524:         if ( open (my $fh,"<$designfile") ) {
                   5525:             while (my $line = <$fh>) {
                   5526:                 next if ($line =~ /^\#/);
                   5527:                 chomp($line);
                   5528:                 my ($key,$val)=(split(/\=/,$line));
                   5529:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5530:             }
                   5531:             close($fh);
                   5532:         }
                   5533:     }
1.1026    raeburn  5534:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5535:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5536:     }
                   5537:     return %legacyhash;
                   5538: }
                   5539: 
1.63      www      5540: =pod
                   5541: 
1.112     bowersj2 5542: =item * &domainlogo()
1.63      www      5543: 
                   5544: Inputs: $domain (usually will be undef)
                   5545: 
                   5546: Returns: A link to a domain logo, if the domain logo exists.
                   5547: If the domain logo does not exist, a description of the domain.
                   5548: 
                   5549: =cut
1.112     bowersj2 5550: 
1.63      www      5551: ###############################################
                   5552: sub domainlogo {
1.517     raeburn  5553:     my $domain = &determinedomain(shift);
1.518     albertel 5554:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5555:     # See if there is a logo
                   5556:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5557:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5558:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5559: 	    if ($imgsrc =~ m{^/res/}) {
                   5560: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5561: 		&Apache::lonnet::repcopy($local_name);
                   5562: 	    }
                   5563: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5564:         } 
                   5565:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5566:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5567:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5568:     } else {
1.60      matthew  5569:         return '';
1.59      www      5570:     }
                   5571: }
1.63      www      5572: ##############################################
                   5573: 
                   5574: =pod
                   5575: 
1.112     bowersj2 5576: =item * &designparm()
1.63      www      5577: 
                   5578: Inputs: $which parameter; $domain (usually will be undef)
                   5579: 
                   5580: Returns: value of designparamter $which
                   5581: 
                   5582: =cut
1.112     bowersj2 5583: 
1.397     albertel 5584: 
1.400     albertel 5585: ##############################################
1.397     albertel 5586: sub designparm {
                   5587:     my ($which,$domain)=@_;
                   5588:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5589:         return $env{'environment.color.'.$which};
1.96      www      5590:     }
1.63      www      5591:     $domain=&determinedomain($domain);
1.1016    raeburn  5592:     my %domdesign;
                   5593:     unless ($domain eq 'public') {
                   5594:         %domdesign = &get_domainconf($domain);
                   5595:     }
1.520     raeburn  5596:     my $output;
1.517     raeburn  5597:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5598:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5599:     } else {
1.520     raeburn  5600:         $output = $defaultdesign{$which};
                   5601:     }
                   5602:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5603:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5604:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5605:             if ($output =~ m{^/res/}) {
                   5606:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5607:                 &Apache::lonnet::repcopy($local_name);
                   5608:             }
1.520     raeburn  5609:             $output = &lonhttpdurl($output);
                   5610:         }
1.63      www      5611:     }
1.520     raeburn  5612:     return $output;
1.63      www      5613: }
1.59      www      5614: 
1.822     bisitz   5615: ##############################################
                   5616: =pod
                   5617: 
1.832     bisitz   5618: =item * &authorspace()
                   5619: 
1.1028    raeburn  5620: Inputs: $url (usually will be undef).
1.832     bisitz   5621: 
1.1132    raeburn  5622: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5623:          directory being viewed (or for which action is being taken). 
                   5624:          If $url is provided, and begins /priv/<domain>/<uname>
                   5625:          the path will be that portion of the $context argument.
                   5626:          Otherwise the path will be for the author space of the current
                   5627:          user when the current role is author, or for that of the 
                   5628:          co-author/assistant co-author space when the current role 
                   5629:          is co-author or assistant co-author.
1.832     bisitz   5630: 
                   5631: =cut
                   5632: 
                   5633: sub authorspace {
1.1028    raeburn  5634:     my ($url) = @_;
                   5635:     if ($url ne '') {
                   5636:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5637:            return $1;
                   5638:         }
                   5639:     }
1.832     bisitz   5640:     my $caname = '';
1.1024    www      5641:     my $cadom = '';
1.1028    raeburn  5642:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5643:         ($cadom,$caname) =
1.832     bisitz   5644:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5645:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5646:         $caname = $env{'user.name'};
1.1024    www      5647:         $cadom = $env{'user.domain'};
1.832     bisitz   5648:     }
1.1028    raeburn  5649:     if (($caname ne '') && ($cadom ne '')) {
                   5650:         return "/priv/$cadom/$caname/";
                   5651:     }
                   5652:     return;
1.832     bisitz   5653: }
                   5654: 
                   5655: ##############################################
                   5656: =pod
                   5657: 
1.822     bisitz   5658: =item * &head_subbox()
                   5659: 
                   5660: Inputs: $content (contains HTML code with page functions, etc.)
                   5661: 
                   5662: Returns: HTML div with $content
                   5663:          To be included in page header
                   5664: 
                   5665: =cut
                   5666: 
                   5667: sub head_subbox {
                   5668:     my ($content)=@_;
                   5669:     my $output =
1.993     raeburn  5670:         '<div class="LC_head_subbox">'
1.822     bisitz   5671:        .$content
                   5672:        .'</div>'
                   5673: }
                   5674: 
                   5675: ##############################################
                   5676: =pod
                   5677: 
                   5678: =item * &CSTR_pageheader()
                   5679: 
1.1026    raeburn  5680: Input: (optional) filename from which breadcrumb trail is built.
                   5681:        In most cases no input as needed, as $env{'request.filename'}
                   5682:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5683: 
                   5684: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5685:          To be included on Authoring Space pages
1.822     bisitz   5686: 
                   5687: =cut
                   5688: 
                   5689: sub CSTR_pageheader {
1.1026    raeburn  5690:     my ($trailfile) = @_;
                   5691:     if ($trailfile eq '') {
                   5692:         $trailfile = $env{'request.filename'};
                   5693:     }
                   5694: 
                   5695: # this is for resources; directories have customtitle, and crumbs
                   5696: # and select recent are created in lonpubdir.pm
                   5697: 
                   5698:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5699:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5700:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5701:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5702:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5703: 
                   5704:     my $parentpath = '';
                   5705:     my $lastitem = '';
                   5706:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5707:         $parentpath = $1;
                   5708:         $lastitem = $2;
                   5709:     } else {
                   5710:         $lastitem = $thisdisfn;
                   5711:     }
1.921     bisitz   5712: 
1.1246    raeburn  5713:     my ($crsauthor,$title);
                   5714:     if (($env{'request.course.id'}) &&
                   5715:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  5716:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  5717:         $crsauthor = 1;
                   5718:         $title = &mt('Course Authoring Space');
                   5719:     } else {
                   5720:         $title = &mt('Authoring Space');
                   5721:     }
                   5722: 
1.921     bisitz   5723:     my $output =
1.822     bisitz   5724:          '<div>'
                   5725:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  5726:         .'<b>'.$title.'</b> '
1.822     bisitz   5727:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5728:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5729:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5730: 
                   5731:     if ($lastitem) {
                   5732:         $output .=
                   5733:              '<span class="LC_filename">'
                   5734:             .$lastitem
                   5735:             .'</span>';
                   5736:     }
1.1245    raeburn  5737: 
1.1246    raeburn  5738:     if ($crsauthor) {
                   5739:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
                   5740:     } else {
                   5741:         $output .=
                   5742:              '<br />'
                   5743:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5744:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5745:             .'</form>'
                   5746:             .&Apache::lonmenu::constspaceform();
                   5747:     }
                   5748:     $output .= '</div>';
1.921     bisitz   5749: 
                   5750:     return $output;
1.822     bisitz   5751: }
                   5752: 
1.60      matthew  5753: ###############################################
                   5754: ###############################################
                   5755: 
                   5756: =pod
                   5757: 
1.112     bowersj2 5758: =back
                   5759: 
1.549     albertel 5760: =head1 HTML Helpers
1.112     bowersj2 5761: 
                   5762: =over 4
                   5763: 
                   5764: =item * &bodytag()
1.60      matthew  5765: 
                   5766: Returns a uniform header for LON-CAPA web pages.
                   5767: 
                   5768: Inputs: 
                   5769: 
1.112     bowersj2 5770: =over 4
                   5771: 
                   5772: =item * $title, A title to be displayed on the page.
                   5773: 
                   5774: =item * $function, the current role (can be undef).
                   5775: 
                   5776: =item * $addentries, extra parameters for the <body> tag.
                   5777: 
                   5778: =item * $bodyonly, if defined, only return the <body> tag.
                   5779: 
                   5780: =item * $domain, if defined, force a given domain.
                   5781: 
                   5782: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5783:             text interface only)
1.60      matthew  5784: 
1.814     bisitz   5785: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5786:                      navigational links
1.317     albertel 5787: 
1.338     albertel 5788: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5789: 
1.460     albertel 5790: =item * $args, optional argument valid values are
                   5791:             no_auto_mt_title -> prevents &mt()ing the title arg
                   5792: 
1.1096    raeburn  5793: =item * $advtoolsref, optional argument, ref to an array containing
                   5794:             inlineremote items to be added in "Functions" menu below
                   5795:             breadcrumbs.
                   5796: 
1.112     bowersj2 5797: =back
                   5798: 
1.60      matthew  5799: Returns: A uniform header for LON-CAPA web pages.  
                   5800: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5801: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5802: other decorations will be returned.
                   5803: 
                   5804: =cut
                   5805: 
1.54      www      5806: sub bodytag {
1.831     bisitz   5807:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1096    raeburn  5808:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
1.339     albertel 5809: 
1.954     raeburn  5810:     my $public;
                   5811:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5812:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5813:         $public = 1;
                   5814:     }
1.460     albertel 5815:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  5816:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5817: 
1.183     matthew  5818:     $function = &get_users_function() if (!$function);
1.339     albertel 5819:     my $img =    &designparm($function.'.img',$domain);
                   5820:     my $font =   &designparm($function.'.font',$domain);
                   5821:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5822: 
1.803     bisitz   5823:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5824: 		   'bgcolor' => $pgbg,
1.339     albertel 5825: 		   'text'    => $font,
                   5826:                    'alink'   => &designparm($function.'.alink',$domain),
                   5827: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5828: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5829:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5830: 
1.63      www      5831:  # role and realm
1.1178    raeburn  5832:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5833:     if ($realm) {
                   5834:         $realm = '/'.$realm;
                   5835:     }
1.378     raeburn  5836:     if ($role  eq 'ca') {
1.479     albertel 5837:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5838:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5839:     } 
1.55      www      5840: # realm
1.258     albertel 5841:     if ($env{'request.course.id'}) {
1.378     raeburn  5842:         if ($env{'request.role'} !~ /^cr/) {
                   5843:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5844:         }
1.898     raeburn  5845:         if ($env{'request.course.sec'}) {
                   5846:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5847:         }   
1.359     albertel 5848: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5849:     } else {
                   5850:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5851:     }
1.433     albertel 5852: 
1.359     albertel 5853:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5854: 
1.438     albertel 5855:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5856: 
1.101     www      5857: # construct main body tag
1.359     albertel 5858:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  5859: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5860: 
1.1131    raeburn  5861:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5862: 
1.1130    raeburn  5863:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5864:         return $bodytag;
1.1130    raeburn  5865:     }
1.359     albertel 5866: 
1.954     raeburn  5867:     if ($public) {
1.433     albertel 5868: 	undef($role);
                   5869:     }
1.359     albertel 5870:     
1.762     bisitz   5871:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5872:     #
                   5873:     # Extra info if you are the DC
                   5874:     my $dc_info = '';
                   5875:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5876:                         $env{'course.'.$env{'request.course.id'}.
                   5877:                                  '.domain'}.'/'})) {
                   5878:         my $cid = $env{'request.course.id'};
1.917     raeburn  5879:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5880:         $dc_info =~ s/\s+$//;
1.359     albertel 5881:     }
                   5882: 
1.1237    raeburn  5883:     my $crstype;
                   5884:     if ($env{'request.course.id'}) {
                   5885:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
                   5886:     } elsif ($args->{'crstype'}) {
                   5887:         $crstype = $args->{'crstype'};
                   5888:     }
                   5889:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   5890:         undef($role);
                   5891:     } else {
1.1242    raeburn  5892:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  5893:     }
1.853     droeschl 5894: 
1.903     droeschl 5895:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5896: 
                   5897:         #    if ($env{'request.state'} eq 'construct') {
                   5898:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5899:         #    }
                   5900: 
1.1130    raeburn  5901:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  5902:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5903: 
1.1237    raeburn  5904:         my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
1.359     albertel 5905: 
1.916     droeschl 5906:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5907:              if ($dc_info) {
                   5908:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5909:              }
1.1130    raeburn  5910:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.916     droeschl 5911:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5912:             return $bodytag;
                   5913:         }
1.894     droeschl 5914: 
1.927     raeburn  5915:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1130    raeburn  5916:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5917:         }
1.916     droeschl 5918: 
1.1130    raeburn  5919:         $bodytag .= $right;
1.852     droeschl 5920: 
1.917     raeburn  5921:         if ($dc_info) {
                   5922:             $dc_info = &dc_courseid_toggle($dc_info);
                   5923:         }
                   5924:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5925: 
1.1169    raeburn  5926:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  5927:         if ($args->{'no_secondary_menu'}) {
                   5928:             return $bodytag;
                   5929:         }
1.1169    raeburn  5930:         #don't show menus for public users
1.954     raeburn  5931:         if (!$public){
1.1154    raeburn  5932:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5933:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5934:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5935:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5936:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5937:                                 $args->{'bread_crumbs'});
1.1096    raeburn  5938:             } elsif ($forcereg) {
                   5939:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5940:                                                             $args->{'group'});
                   5941:             } else {
                   5942:                 $bodytag .= 
                   5943:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5944:                                                         $forcereg,$args->{'group'},
                   5945:                                                         $args->{'bread_crumbs'},
                   5946:                                                         $advtoolsref);
1.920     raeburn  5947:             }
1.903     droeschl 5948:         }else{
                   5949:             # this is to seperate menu from content when there's no secondary
                   5950:             # menu. Especially needed for public accessible ressources.
                   5951:             $bodytag .= '<hr style="clear:both" />';
                   5952:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5953:         }
1.903     droeschl 5954: 
1.235     raeburn  5955:         return $bodytag;
1.182     matthew  5956: }
                   5957: 
1.917     raeburn  5958: sub dc_courseid_toggle {
                   5959:     my ($dc_info) = @_;
1.980     raeburn  5960:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5961:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5962:            &mt('(More ...)').'</a></span>'.
                   5963:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5964: }
                   5965: 
1.330     albertel 5966: sub make_attr_string {
                   5967:     my ($register,$attr_ref) = @_;
                   5968: 
                   5969:     if ($attr_ref && !ref($attr_ref)) {
                   5970: 	die("addentries Must be a hash ref ".
                   5971: 	    join(':',caller(1))." ".
                   5972: 	    join(':',caller(0))." ");
                   5973:     }
                   5974: 
                   5975:     if ($register) {
1.339     albertel 5976: 	my ($on_load,$on_unload);
                   5977: 	foreach my $key (keys(%{$attr_ref})) {
                   5978: 	    if      (lc($key) eq 'onload') {
                   5979: 		$on_load.=$attr_ref->{$key}.';';
                   5980: 		delete($attr_ref->{$key});
                   5981: 
                   5982: 	    } elsif (lc($key) eq 'onunload') {
                   5983: 		$on_unload.=$attr_ref->{$key}.';';
                   5984: 		delete($attr_ref->{$key});
                   5985: 	    }
                   5986: 	}
1.953     droeschl 5987: 	$attr_ref->{'onload'}  = $on_load;
                   5988: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 5989:     }
1.339     albertel 5990: 
1.330     albertel 5991:     my $attr_string;
1.1159    raeburn  5992:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5993: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5994:     }
                   5995:     return $attr_string;
                   5996: }
                   5997: 
                   5998: 
1.182     matthew  5999: ###############################################
1.251     albertel 6000: ###############################################
                   6001: 
                   6002: =pod
                   6003: 
                   6004: =item * &endbodytag()
                   6005: 
                   6006: Returns a uniform footer for LON-CAPA web pages.
                   6007: 
1.635     raeburn  6008: Inputs: 1 - optional reference to an args hash
                   6009: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6010: a 'Continue' link is not displayed if the page contains an
                   6011: internal redirect in the <head></head> section,
                   6012: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6013: 
                   6014: =cut
                   6015: 
                   6016: sub endbodytag {
1.635     raeburn  6017:     my ($args) = @_;
1.1080    raeburn  6018:     my $endbodytag;
                   6019:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6020:         $endbodytag='</body>';
                   6021:     }
1.315     albertel 6022:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6023:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6024: 	    $endbodytag=
                   6025: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6026: 	        &mt('Continue').'</a>'.
                   6027: 	        $endbodytag;
                   6028:         }
1.315     albertel 6029:     }
1.251     albertel 6030:     return $endbodytag;
                   6031: }
                   6032: 
1.352     albertel 6033: =pod
                   6034: 
                   6035: =item * &standard_css()
                   6036: 
                   6037: Returns a style sheet
                   6038: 
                   6039: Inputs: (all optional)
                   6040:             domain         -> force to color decorate a page for a specific
                   6041:                                domain
                   6042:             function       -> force usage of a specific rolish color scheme
                   6043:             bgcolor        -> override the default page bgcolor
                   6044: 
                   6045: =cut
                   6046: 
1.343     albertel 6047: sub standard_css {
1.345     albertel 6048:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6049:     $function  = &get_users_function() if (!$function);
                   6050:     my $img    = &designparm($function.'.img',   $domain);
                   6051:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6052:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6053:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6054: #second colour for later usage
1.345     albertel 6055:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6056:     my $pgbg_or_bgcolor =
                   6057: 	         $bgcolor ||
1.352     albertel 6058: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6059:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6060:     my $alink  = &designparm($function.'.alink', $domain);
                   6061:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6062:     my $link   = &designparm($function.'.link',  $domain);
                   6063: 
1.602     albertel 6064:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6065:     my $mono                 = 'monospace';
1.850     bisitz   6066:     my $data_table_head      = $sidebg;
                   6067:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6068:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6069:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6070:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6071:     my $mail_new             = '#FFBB77';
                   6072:     my $mail_new_hover       = '#DD9955';
                   6073:     my $mail_read            = '#BBBB77';
                   6074:     my $mail_read_hover      = '#999944';
                   6075:     my $mail_replied         = '#AAAA88';
                   6076:     my $mail_replied_hover   = '#888855';
                   6077:     my $mail_other           = '#99BBBB';
                   6078:     my $mail_other_hover     = '#669999';
1.391     albertel 6079:     my $table_header         = '#DDDDDD';
1.489     raeburn  6080:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6081:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6082:     my $button_hover         = '#BF2317';
1.392     albertel 6083: 
1.608     albertel 6084:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6085:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6086:                                              : '0 3px 0 4px';
1.448     albertel 6087: 
1.523     albertel 6088: 
1.343     albertel 6089:     return <<END;
1.947     droeschl 6090: 
                   6091: /* needed for iframe to allow 100% height in FF */
                   6092: body, html { 
                   6093:     margin: 0;
                   6094:     padding: 0 0.5%;
                   6095:     height: 99%; /* to avoid scrollbars */
                   6096: }
                   6097: 
1.795     www      6098: body {
1.911     bisitz   6099:   font-family: $sans;
                   6100:   line-height:130%;
                   6101:   font-size:0.83em;
                   6102:   color:$font;
1.795     www      6103: }
                   6104: 
1.959     onken    6105: a:focus,
                   6106: a:focus img {
1.795     www      6107:   color: red;
                   6108: }
1.698     harmsja  6109: 
1.911     bisitz   6110: form, .inline {
                   6111:   display: inline;
1.795     www      6112: }
1.721     harmsja  6113: 
1.795     www      6114: .LC_right {
1.911     bisitz   6115:   text-align:right;
1.795     www      6116: }
                   6117: 
                   6118: .LC_middle {
1.911     bisitz   6119:   vertical-align:middle;
1.795     www      6120: }
1.721     harmsja  6121: 
1.1130    raeburn  6122: .LC_floatleft {
                   6123:   float: left;
                   6124: }
                   6125: 
                   6126: .LC_floatright {
                   6127:   float: right;
                   6128: }
                   6129: 
1.911     bisitz   6130: .LC_400Box {
                   6131:   width:400px;
                   6132: }
1.721     harmsja  6133: 
1.947     droeschl 6134: .LC_iframecontainer {
                   6135:     width: 98%;
                   6136:     margin: 0;
                   6137:     position: fixed;
                   6138:     top: 8.5em;
                   6139:     bottom: 0;
                   6140: }
                   6141: 
                   6142: .LC_iframecontainer iframe{
                   6143:     border: none;
                   6144:     width: 100%;
                   6145:     height: 100%;
                   6146: }
                   6147: 
1.778     bisitz   6148: .LC_filename {
                   6149:   font-family: $mono;
                   6150:   white-space:pre;
1.921     bisitz   6151:   font-size: 120%;
1.778     bisitz   6152: }
                   6153: 
                   6154: .LC_fileicon {
                   6155:   border: none;
                   6156:   height: 1.3em;
                   6157:   vertical-align: text-bottom;
                   6158:   margin-right: 0.3em;
                   6159:   text-decoration:none;
                   6160: }
                   6161: 
1.1008    www      6162: .LC_setting {
                   6163:   text-decoration:underline;
                   6164: }
                   6165: 
1.350     albertel 6166: .LC_error {
                   6167:   color: red;
                   6168: }
1.795     www      6169: 
1.1097    bisitz   6170: .LC_warning {
                   6171:   color: darkorange;
                   6172: }
                   6173: 
1.457     albertel 6174: .LC_diff_removed {
1.733     bisitz   6175:   color: red;
1.394     albertel 6176: }
1.532     albertel 6177: 
                   6178: .LC_info,
1.457     albertel 6179: .LC_success,
                   6180: .LC_diff_added {
1.350     albertel 6181:   color: green;
                   6182: }
1.795     www      6183: 
1.802     bisitz   6184: div.LC_confirm_box {
                   6185:   background-color: #FAFAFA;
                   6186:   border: 1px solid $lg_border_color;
                   6187:   margin-right: 0;
                   6188:   padding: 5px;
                   6189: }
                   6190: 
                   6191: div.LC_confirm_box .LC_error img,
                   6192: div.LC_confirm_box .LC_success img {
                   6193:   vertical-align: middle;
                   6194: }
                   6195: 
1.1242    raeburn  6196: .LC_maxwidth {
                   6197:   max-width: 100%;
                   6198:   height: auto;
                   6199: }
                   6200: 
1.1243    raeburn  6201: .LC_textsize_mobile {
                   6202:   \@media only screen and (max-device-width: 480px) {
                   6203:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6204:   }
                   6205: }
                   6206: 
1.440     albertel 6207: .LC_icon {
1.771     droeschl 6208:   border: none;
1.790     droeschl 6209:   vertical-align: middle;
1.771     droeschl 6210: }
                   6211: 
1.543     albertel 6212: .LC_docs_spacer {
                   6213:   width: 25px;
                   6214:   height: 1px;
1.771     droeschl 6215:   border: none;
1.543     albertel 6216: }
1.346     albertel 6217: 
1.532     albertel 6218: .LC_internal_info {
1.735     bisitz   6219:   color: #999999;
1.532     albertel 6220: }
                   6221: 
1.794     www      6222: .LC_discussion {
1.1050    www      6223:   background: $data_table_dark;
1.911     bisitz   6224:   border: 1px solid black;
                   6225:   margin: 2px;
1.794     www      6226: }
                   6227: 
                   6228: .LC_disc_action_left {
1.1050    www      6229:   background: $sidebg;
1.911     bisitz   6230:   text-align: left;
1.1050    www      6231:   padding: 4px;
                   6232:   margin: 2px;
1.794     www      6233: }
                   6234: 
                   6235: .LC_disc_action_right {
1.1050    www      6236:   background: $sidebg;
1.911     bisitz   6237:   text-align: right;
1.1050    www      6238:   padding: 4px;
                   6239:   margin: 2px;
1.794     www      6240: }
                   6241: 
                   6242: .LC_disc_new_item {
1.911     bisitz   6243:   background: white;
                   6244:   border: 2px solid red;
1.1050    www      6245:   margin: 4px;
                   6246:   padding: 4px;
1.794     www      6247: }
                   6248: 
                   6249: .LC_disc_old_item {
1.911     bisitz   6250:   background: white;
1.1050    www      6251:   margin: 4px;
                   6252:   padding: 4px;
1.794     www      6253: }
                   6254: 
1.458     albertel 6255: table.LC_pastsubmission {
                   6256:   border: 1px solid black;
                   6257:   margin: 2px;
                   6258: }
                   6259: 
1.924     bisitz   6260: table#LC_menubuttons {
1.345     albertel 6261:   width: 100%;
                   6262:   background: $pgbg;
1.392     albertel 6263:   border: 2px;
1.402     albertel 6264:   border-collapse: separate;
1.803     bisitz   6265:   padding: 0;
1.345     albertel 6266: }
1.392     albertel 6267: 
1.801     tempelho 6268: table#LC_title_bar a {
                   6269:   color: $fontmenu;
                   6270: }
1.836     bisitz   6271: 
1.807     droeschl 6272: table#LC_title_bar {
1.819     tempelho 6273:   clear: both;
1.836     bisitz   6274:   display: none;
1.807     droeschl 6275: }
                   6276: 
1.795     www      6277: table#LC_title_bar,
1.933     droeschl 6278: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6279: table#LC_title_bar.LC_with_remote {
1.359     albertel 6280:   width: 100%;
1.392     albertel 6281:   border-color: $pgbg;
                   6282:   border-style: solid;
                   6283:   border-width: $border;
1.379     albertel 6284:   background: $pgbg;
1.801     tempelho 6285:   color: $fontmenu;
1.392     albertel 6286:   border-collapse: collapse;
1.803     bisitz   6287:   padding: 0;
1.819     tempelho 6288:   margin: 0;
1.359     albertel 6289: }
1.795     www      6290: 
1.933     droeschl 6291: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6292:     margin: 0;
                   6293:     padding: 0;
1.933     droeschl 6294:     position: relative;
                   6295:     list-style: none;
1.913     droeschl 6296: }
1.933     droeschl 6297: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6298:     display: inline;
                   6299: }
1.933     droeschl 6300: 
                   6301: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6302:     padding: 0;
1.933     droeschl 6303:     margin: 0;
                   6304:     float: left;
1.913     droeschl 6305: }
1.933     droeschl 6306: .LC_breadcrumb_tools_tools {
                   6307:     padding: 0;
                   6308:     margin: 0;
1.913     droeschl 6309:     float: right;
                   6310: }
                   6311: 
1.1240    raeburn  6312: .LC_placement_prog {
                   6313:     padding-right: 20px;
                   6314:     font-weight: bold;
                   6315:     font-size: 90%;
                   6316: }
                   6317: 
1.359     albertel 6318: table#LC_title_bar td {
                   6319:   background: $tabbg;
                   6320: }
1.795     www      6321: 
1.911     bisitz   6322: table#LC_menubuttons img {
1.803     bisitz   6323:   border: none;
1.346     albertel 6324: }
1.795     www      6325: 
1.842     droeschl 6326: .LC_breadcrumbs_component {
1.911     bisitz   6327:   float: right;
                   6328:   margin: 0 1em;
1.357     albertel 6329: }
1.842     droeschl 6330: .LC_breadcrumbs_component img {
1.911     bisitz   6331:   vertical-align: middle;
1.777     tempelho 6332: }
1.795     www      6333: 
1.1243    raeburn  6334: .LC_breadcrumbs_hoverable {
                   6335:   background: $sidebg;
                   6336: }
                   6337: 
1.383     albertel 6338: td.LC_table_cell_checkbox {
                   6339:   text-align: center;
                   6340: }
1.795     www      6341: 
                   6342: .LC_fontsize_small {
1.911     bisitz   6343:   font-size: 70%;
1.705     tempelho 6344: }
                   6345: 
1.844     bisitz   6346: #LC_breadcrumbs {
1.911     bisitz   6347:   clear:both;
                   6348:   background: $sidebg;
                   6349:   border-bottom: 1px solid $lg_border_color;
                   6350:   line-height: 2.5em;
1.933     droeschl 6351:   overflow: hidden;
1.911     bisitz   6352:   margin: 0;
                   6353:   padding: 0;
1.995     raeburn  6354:   text-align: left;
1.819     tempelho 6355: }
1.862     bisitz   6356: 
1.1098    bisitz   6357: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6358:   clear:both;
                   6359:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6360:   border: 1px solid $sidebg;
1.1098    bisitz   6361:   margin: 0 0 10px 0;
1.966     bisitz   6362:   padding: 3px;
1.995     raeburn  6363:   text-align: left;
1.822     bisitz   6364: }
                   6365: 
1.795     www      6366: .LC_fontsize_medium {
1.911     bisitz   6367:   font-size: 85%;
1.705     tempelho 6368: }
                   6369: 
1.795     www      6370: .LC_fontsize_large {
1.911     bisitz   6371:   font-size: 120%;
1.705     tempelho 6372: }
                   6373: 
1.346     albertel 6374: .LC_menubuttons_inline_text {
                   6375:   color: $font;
1.698     harmsja  6376:   font-size: 90%;
1.701     harmsja  6377:   padding-left:3px;
1.346     albertel 6378: }
                   6379: 
1.934     droeschl 6380: .LC_menubuttons_inline_text img{
                   6381:   vertical-align: middle;
                   6382: }
                   6383: 
1.1051    www      6384: li.LC_menubuttons_inline_text img {
1.951     onken    6385:   cursor:pointer;
1.1002    droeschl 6386:   text-decoration: none;
1.951     onken    6387: }
                   6388: 
1.526     www      6389: .LC_menubuttons_link {
                   6390:   text-decoration: none;
                   6391: }
1.795     www      6392: 
1.522     albertel 6393: .LC_menubuttons_category {
1.521     www      6394:   color: $font;
1.526     www      6395:   background: $pgbg;
1.521     www      6396:   font-size: larger;
                   6397:   font-weight: bold;
                   6398: }
                   6399: 
1.346     albertel 6400: td.LC_menubuttons_text {
1.911     bisitz   6401:   color: $font;
1.346     albertel 6402: }
1.706     harmsja  6403: 
1.346     albertel 6404: .LC_current_location {
                   6405:   background: $tabbg;
                   6406: }
1.795     www      6407: 
1.938     bisitz   6408: table.LC_data_table {
1.347     albertel 6409:   border: 1px solid #000000;
1.402     albertel 6410:   border-collapse: separate;
1.426     albertel 6411:   border-spacing: 1px;
1.610     albertel 6412:   background: $pgbg;
1.347     albertel 6413: }
1.795     www      6414: 
1.422     albertel 6415: .LC_data_table_dense {
                   6416:   font-size: small;
                   6417: }
1.795     www      6418: 
1.507     raeburn  6419: table.LC_nested_outer {
                   6420:   border: 1px solid #000000;
1.589     raeburn  6421:   border-collapse: collapse;
1.803     bisitz   6422:   border-spacing: 0;
1.507     raeburn  6423:   width: 100%;
                   6424: }
1.795     www      6425: 
1.879     raeburn  6426: table.LC_innerpickbox,
1.507     raeburn  6427: table.LC_nested {
1.803     bisitz   6428:   border: none;
1.589     raeburn  6429:   border-collapse: collapse;
1.803     bisitz   6430:   border-spacing: 0;
1.507     raeburn  6431:   width: 100%;
                   6432: }
1.795     www      6433: 
1.911     bisitz   6434: table.LC_data_table tr th,
                   6435: table.LC_calendar tr th,
1.879     raeburn  6436: table.LC_prior_tries tr th,
                   6437: table.LC_innerpickbox tr th {
1.349     albertel 6438:   font-weight: bold;
                   6439:   background-color: $data_table_head;
1.801     tempelho 6440:   color:$fontmenu;
1.701     harmsja  6441:   font-size:90%;
1.347     albertel 6442: }
1.795     www      6443: 
1.879     raeburn  6444: table.LC_innerpickbox tr th,
                   6445: table.LC_innerpickbox tr td {
                   6446:   vertical-align: top;
                   6447: }
                   6448: 
1.711     raeburn  6449: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6450:   background-color: #CCCCCC;
1.711     raeburn  6451:   font-weight: bold;
                   6452:   text-align: left;
                   6453: }
1.795     www      6454: 
1.912     bisitz   6455: table.LC_data_table tr.LC_odd_row > td {
                   6456:   background-color: $data_table_light;
                   6457:   padding: 2px;
                   6458:   vertical-align: top;
                   6459: }
                   6460: 
1.809     bisitz   6461: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6462:   background-color: $data_table_light;
1.912     bisitz   6463:   vertical-align: top;
                   6464: }
                   6465: 
                   6466: table.LC_data_table tr.LC_even_row > td {
                   6467:   background-color: $data_table_dark;
1.425     albertel 6468:   padding: 2px;
1.900     bisitz   6469:   vertical-align: top;
1.347     albertel 6470: }
1.795     www      6471: 
1.809     bisitz   6472: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6473:   background-color: $data_table_dark;
1.900     bisitz   6474:   vertical-align: top;
1.347     albertel 6475: }
1.795     www      6476: 
1.425     albertel 6477: table.LC_data_table tr.LC_data_table_highlight td {
                   6478:   background-color: $data_table_darker;
                   6479: }
1.795     www      6480: 
1.639     raeburn  6481: table.LC_data_table tr td.LC_leftcol_header {
                   6482:   background-color: $data_table_head;
                   6483:   font-weight: bold;
                   6484: }
1.795     www      6485: 
1.451     albertel 6486: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6487: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6488:   font-weight: bold;
                   6489:   font-style: italic;
                   6490:   text-align: center;
                   6491:   padding: 8px;
1.347     albertel 6492: }
1.795     www      6493: 
1.1114    raeburn  6494: table.LC_data_table tr.LC_empty_row td,
                   6495: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6496:   background-color: $sidebg;
                   6497: }
                   6498: 
                   6499: table.LC_nested tr.LC_empty_row td {
                   6500:   background-color: #FFFFFF;
                   6501: }
                   6502: 
1.890     droeschl 6503: table.LC_caption {
                   6504: }
                   6505: 
1.507     raeburn  6506: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6507:   padding: 4ex
                   6508: }
1.795     www      6509: 
1.507     raeburn  6510: table.LC_nested_outer tr th {
                   6511:   font-weight: bold;
1.801     tempelho 6512:   color:$fontmenu;
1.507     raeburn  6513:   background-color: $data_table_head;
1.701     harmsja  6514:   font-size: small;
1.507     raeburn  6515:   border-bottom: 1px solid #000000;
                   6516: }
1.795     www      6517: 
1.507     raeburn  6518: table.LC_nested_outer tr td.LC_subheader {
                   6519:   background-color: $data_table_head;
                   6520:   font-weight: bold;
                   6521:   font-size: small;
                   6522:   border-bottom: 1px solid #000000;
                   6523:   text-align: right;
1.451     albertel 6524: }
1.795     www      6525: 
1.507     raeburn  6526: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6527:   background-color: #CCCCCC;
1.451     albertel 6528:   font-weight: bold;
                   6529:   font-size: small;
1.507     raeburn  6530:   text-align: center;
                   6531: }
1.795     www      6532: 
1.589     raeburn  6533: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6534: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6535:   text-align: left;
1.451     albertel 6536: }
1.795     www      6537: 
1.507     raeburn  6538: table.LC_nested td {
1.735     bisitz   6539:   background-color: #FFFFFF;
1.451     albertel 6540:   font-size: small;
1.507     raeburn  6541: }
1.795     www      6542: 
1.507     raeburn  6543: table.LC_nested_outer tr th.LC_right_item,
                   6544: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6545: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6546: table.LC_nested tr td.LC_right_item {
1.451     albertel 6547:   text-align: right;
                   6548: }
                   6549: 
1.507     raeburn  6550: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6551:   background-color: #EEEEEE;
1.451     albertel 6552: }
                   6553: 
1.473     raeburn  6554: table.LC_createuser {
                   6555: }
                   6556: 
                   6557: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6558:   font-size: small;
1.473     raeburn  6559: }
                   6560: 
                   6561: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6562:   background-color: #CCCCCC;
1.473     raeburn  6563:   font-weight: bold;
                   6564:   text-align: center;
                   6565: }
                   6566: 
1.349     albertel 6567: table.LC_calendar {
                   6568:   border: 1px solid #000000;
                   6569:   border-collapse: collapse;
1.917     raeburn  6570:   width: 98%;
1.349     albertel 6571: }
1.795     www      6572: 
1.349     albertel 6573: table.LC_calendar_pickdate {
                   6574:   font-size: xx-small;
                   6575: }
1.795     www      6576: 
1.349     albertel 6577: table.LC_calendar tr td {
                   6578:   border: 1px solid #000000;
                   6579:   vertical-align: top;
1.917     raeburn  6580:   width: 14%;
1.349     albertel 6581: }
1.795     www      6582: 
1.349     albertel 6583: table.LC_calendar tr td.LC_calendar_day_empty {
                   6584:   background-color: $data_table_dark;
                   6585: }
1.795     www      6586: 
1.779     bisitz   6587: table.LC_calendar tr td.LC_calendar_day_current {
                   6588:   background-color: $data_table_highlight;
1.777     tempelho 6589: }
1.795     www      6590: 
1.938     bisitz   6591: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6592:   background-color: $mail_new;
                   6593: }
1.795     www      6594: 
1.938     bisitz   6595: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6596:   background-color: $mail_new_hover;
                   6597: }
1.795     www      6598: 
1.938     bisitz   6599: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6600:   background-color: $mail_read;
                   6601: }
1.795     www      6602: 
1.938     bisitz   6603: /*
                   6604: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6605:   background-color: $mail_read_hover;
                   6606: }
1.938     bisitz   6607: */
1.795     www      6608: 
1.938     bisitz   6609: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6610:   background-color: $mail_replied;
                   6611: }
1.795     www      6612: 
1.938     bisitz   6613: /*
                   6614: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6615:   background-color: $mail_replied_hover;
                   6616: }
1.938     bisitz   6617: */
1.795     www      6618: 
1.938     bisitz   6619: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6620:   background-color: $mail_other;
                   6621: }
1.795     www      6622: 
1.938     bisitz   6623: /*
                   6624: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6625:   background-color: $mail_other_hover;
                   6626: }
1.938     bisitz   6627: */
1.494     raeburn  6628: 
1.777     tempelho 6629: table.LC_data_table tr > td.LC_browser_file,
                   6630: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6631:   background: #AAEE77;
1.389     albertel 6632: }
1.795     www      6633: 
1.777     tempelho 6634: table.LC_data_table tr > td.LC_browser_file_locked,
                   6635: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6636:   background: #FFAA99;
1.387     albertel 6637: }
1.795     www      6638: 
1.777     tempelho 6639: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6640:   background: #888888;
1.779     bisitz   6641: }
1.795     www      6642: 
1.777     tempelho 6643: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6644: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6645:   background: #F8F866;
1.777     tempelho 6646: }
1.795     www      6647: 
1.696     bisitz   6648: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6649:   background: #E0E8FF;
1.387     albertel 6650: }
1.696     bisitz   6651: 
1.707     bisitz   6652: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6653:   /* background: #77FF77; */
1.707     bisitz   6654: }
1.795     www      6655: 
1.707     bisitz   6656: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6657:   border-right: 8px solid #FFFF77;
1.707     bisitz   6658: }
1.795     www      6659: 
1.707     bisitz   6660: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6661:   border-right: 8px solid #FFAA77;
1.707     bisitz   6662: }
1.795     www      6663: 
1.707     bisitz   6664: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6665:   border-right: 8px solid #FF7777;
1.707     bisitz   6666: }
1.795     www      6667: 
1.707     bisitz   6668: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6669:   border-right: 8px solid #AAFF77;
1.707     bisitz   6670: }
1.795     www      6671: 
1.707     bisitz   6672: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6673:   border-right: 8px solid #11CC55;
1.707     bisitz   6674: }
                   6675: 
1.388     albertel 6676: span.LC_current_location {
1.701     harmsja  6677:   font-size:larger;
1.388     albertel 6678:   background: $pgbg;
                   6679: }
1.387     albertel 6680: 
1.1029    www      6681: span.LC_current_nav_location {
                   6682:   font-weight:bold;
                   6683:   background: $sidebg;
                   6684: }
                   6685: 
1.395     albertel 6686: span.LC_parm_menu_item {
                   6687:   font-size: larger;
                   6688: }
1.795     www      6689: 
1.395     albertel 6690: span.LC_parm_scope_all {
                   6691:   color: red;
                   6692: }
1.795     www      6693: 
1.395     albertel 6694: span.LC_parm_scope_folder {
                   6695:   color: green;
                   6696: }
1.795     www      6697: 
1.395     albertel 6698: span.LC_parm_scope_resource {
                   6699:   color: orange;
                   6700: }
1.795     www      6701: 
1.395     albertel 6702: span.LC_parm_part {
                   6703:   color: blue;
                   6704: }
1.795     www      6705: 
1.911     bisitz   6706: span.LC_parm_folder,
                   6707: span.LC_parm_symb {
1.395     albertel 6708:   font-size: x-small;
                   6709:   font-family: $mono;
                   6710:   color: #AAAAAA;
                   6711: }
                   6712: 
1.977     bisitz   6713: ul.LC_parm_parmlist li {
                   6714:   display: inline-block;
                   6715:   padding: 0.3em 0.8em;
                   6716:   vertical-align: top;
                   6717:   width: 150px;
                   6718:   border-top:1px solid $lg_border_color;
                   6719: }
                   6720: 
1.795     www      6721: td.LC_parm_overview_level_menu,
                   6722: td.LC_parm_overview_map_menu,
                   6723: td.LC_parm_overview_parm_selectors,
                   6724: td.LC_parm_overview_restrictions  {
1.396     albertel 6725:   border: 1px solid black;
                   6726:   border-collapse: collapse;
                   6727: }
1.795     www      6728: 
1.396     albertel 6729: table.LC_parm_overview_restrictions td {
                   6730:   border-width: 1px 4px 1px 4px;
                   6731:   border-style: solid;
                   6732:   border-color: $pgbg;
                   6733:   text-align: center;
                   6734: }
1.795     www      6735: 
1.396     albertel 6736: table.LC_parm_overview_restrictions th {
                   6737:   background: $tabbg;
                   6738:   border-width: 1px 4px 1px 4px;
                   6739:   border-style: solid;
                   6740:   border-color: $pgbg;
                   6741: }
1.795     www      6742: 
1.398     albertel 6743: table#LC_helpmenu {
1.803     bisitz   6744:   border: none;
1.398     albertel 6745:   height: 55px;
1.803     bisitz   6746:   border-spacing: 0;
1.398     albertel 6747: }
                   6748: 
                   6749: table#LC_helpmenu fieldset legend {
                   6750:   font-size: larger;
                   6751: }
1.795     www      6752: 
1.397     albertel 6753: table#LC_helpmenu_links {
                   6754:   width: 100%;
                   6755:   border: 1px solid black;
                   6756:   background: $pgbg;
1.803     bisitz   6757:   padding: 0;
1.397     albertel 6758:   border-spacing: 1px;
                   6759: }
1.795     www      6760: 
1.397     albertel 6761: table#LC_helpmenu_links tr td {
                   6762:   padding: 1px;
                   6763:   background: $tabbg;
1.399     albertel 6764:   text-align: center;
                   6765:   font-weight: bold;
1.397     albertel 6766: }
1.396     albertel 6767: 
1.795     www      6768: table#LC_helpmenu_links a:link,
                   6769: table#LC_helpmenu_links a:visited,
1.397     albertel 6770: table#LC_helpmenu_links a:active {
                   6771:   text-decoration: none;
                   6772:   color: $font;
                   6773: }
1.795     www      6774: 
1.397     albertel 6775: table#LC_helpmenu_links a:hover {
                   6776:   text-decoration: underline;
                   6777:   color: $vlink;
                   6778: }
1.396     albertel 6779: 
1.417     albertel 6780: .LC_chrt_popup_exists {
                   6781:   border: 1px solid #339933;
                   6782:   margin: -1px;
                   6783: }
1.795     www      6784: 
1.417     albertel 6785: .LC_chrt_popup_up {
                   6786:   border: 1px solid yellow;
                   6787:   margin: -1px;
                   6788: }
1.795     www      6789: 
1.417     albertel 6790: .LC_chrt_popup {
                   6791:   border: 1px solid #8888FF;
                   6792:   background: #CCCCFF;
                   6793: }
1.795     www      6794: 
1.421     albertel 6795: table.LC_pick_box {
                   6796:   border-collapse: separate;
                   6797:   background: white;
                   6798:   border: 1px solid black;
                   6799:   border-spacing: 1px;
                   6800: }
1.795     www      6801: 
1.421     albertel 6802: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6803:   background: $sidebg;
1.421     albertel 6804:   font-weight: bold;
1.900     bisitz   6805:   text-align: left;
1.740     bisitz   6806:   vertical-align: top;
1.421     albertel 6807:   width: 184px;
                   6808:   padding: 8px;
                   6809: }
1.795     www      6810: 
1.579     raeburn  6811: table.LC_pick_box td.LC_pick_box_value {
                   6812:   text-align: left;
                   6813:   padding: 8px;
                   6814: }
1.795     www      6815: 
1.579     raeburn  6816: table.LC_pick_box td.LC_pick_box_select {
                   6817:   text-align: left;
                   6818:   padding: 8px;
                   6819: }
1.795     www      6820: 
1.424     albertel 6821: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6822:   padding: 0;
1.421     albertel 6823:   height: 1px;
                   6824:   background: black;
                   6825: }
1.795     www      6826: 
1.421     albertel 6827: table.LC_pick_box td.LC_pick_box_submit {
                   6828:   text-align: right;
                   6829: }
1.795     www      6830: 
1.579     raeburn  6831: table.LC_pick_box td.LC_evenrow_value {
                   6832:   text-align: left;
                   6833:   padding: 8px;
                   6834:   background-color: $data_table_light;
                   6835: }
1.795     www      6836: 
1.579     raeburn  6837: table.LC_pick_box td.LC_oddrow_value {
                   6838:   text-align: left;
                   6839:   padding: 8px;
                   6840:   background-color: $data_table_light;
                   6841: }
1.795     www      6842: 
1.579     raeburn  6843: span.LC_helpform_receipt_cat {
                   6844:   font-weight: bold;
                   6845: }
1.795     www      6846: 
1.424     albertel 6847: table.LC_group_priv_box {
                   6848:   background: white;
                   6849:   border: 1px solid black;
                   6850:   border-spacing: 1px;
                   6851: }
1.795     www      6852: 
1.424     albertel 6853: table.LC_group_priv_box td.LC_pick_box_title {
                   6854:   background: $tabbg;
                   6855:   font-weight: bold;
                   6856:   text-align: right;
                   6857:   width: 184px;
                   6858: }
1.795     www      6859: 
1.424     albertel 6860: table.LC_group_priv_box td.LC_groups_fixed {
                   6861:   background: $data_table_light;
                   6862:   text-align: center;
                   6863: }
1.795     www      6864: 
1.424     albertel 6865: table.LC_group_priv_box td.LC_groups_optional {
                   6866:   background: $data_table_dark;
                   6867:   text-align: center;
                   6868: }
1.795     www      6869: 
1.424     albertel 6870: table.LC_group_priv_box td.LC_groups_functionality {
                   6871:   background: $data_table_darker;
                   6872:   text-align: center;
                   6873:   font-weight: bold;
                   6874: }
1.795     www      6875: 
1.424     albertel 6876: table.LC_group_priv td {
                   6877:   text-align: left;
1.803     bisitz   6878:   padding: 0;
1.424     albertel 6879: }
                   6880: 
                   6881: .LC_navbuttons {
                   6882:   margin: 2ex 0ex 2ex 0ex;
                   6883: }
1.795     www      6884: 
1.423     albertel 6885: .LC_topic_bar {
                   6886:   font-weight: bold;
                   6887:   background: $tabbg;
1.918     wenzelju 6888:   margin: 1em 0em 1em 2em;
1.805     bisitz   6889:   padding: 3px;
1.918     wenzelju 6890:   font-size: 1.2em;
1.423     albertel 6891: }
1.795     www      6892: 
1.423     albertel 6893: .LC_topic_bar span {
1.918     wenzelju 6894:   left: 0.5em;
                   6895:   position: absolute;
1.423     albertel 6896:   vertical-align: middle;
1.918     wenzelju 6897:   font-size: 1.2em;
1.423     albertel 6898: }
1.795     www      6899: 
1.423     albertel 6900: table.LC_course_group_status {
                   6901:   margin: 20px;
                   6902: }
1.795     www      6903: 
1.423     albertel 6904: table.LC_status_selector td {
                   6905:   vertical-align: top;
                   6906:   text-align: center;
1.424     albertel 6907:   padding: 4px;
                   6908: }
1.795     www      6909: 
1.599     albertel 6910: div.LC_feedback_link {
1.616     albertel 6911:   clear: both;
1.829     kalberla 6912:   background: $sidebg;
1.779     bisitz   6913:   width: 100%;
1.829     kalberla 6914:   padding-bottom: 10px;
                   6915:   border: 1px $tabbg solid;
1.833     kalberla 6916:   height: 22px;
                   6917:   line-height: 22px;
                   6918:   padding-top: 5px;
                   6919: }
                   6920: 
                   6921: div.LC_feedback_link img {
                   6922:   height: 22px;
1.867     kalberla 6923:   vertical-align:middle;
1.829     kalberla 6924: }
                   6925: 
1.911     bisitz   6926: div.LC_feedback_link a {
1.829     kalberla 6927:   text-decoration: none;
1.489     raeburn  6928: }
1.795     www      6929: 
1.867     kalberla 6930: div.LC_comblock {
1.911     bisitz   6931:   display:inline;
1.867     kalberla 6932:   color:$font;
                   6933:   font-size:90%;
                   6934: }
                   6935: 
                   6936: div.LC_feedback_link div.LC_comblock {
                   6937:   padding-left:5px;
                   6938: }
                   6939: 
                   6940: div.LC_feedback_link div.LC_comblock a {
                   6941:   color:$font;
                   6942: }
                   6943: 
1.489     raeburn  6944: span.LC_feedback_link {
1.858     bisitz   6945:   /* background: $feedback_link_bg; */
1.599     albertel 6946:   font-size: larger;
                   6947: }
1.795     www      6948: 
1.599     albertel 6949: span.LC_message_link {
1.858     bisitz   6950:   /* background: $feedback_link_bg; */
1.599     albertel 6951:   font-size: larger;
                   6952:   position: absolute;
                   6953:   right: 1em;
1.489     raeburn  6954: }
1.421     albertel 6955: 
1.515     albertel 6956: table.LC_prior_tries {
1.524     albertel 6957:   border: 1px solid #000000;
                   6958:   border-collapse: separate;
                   6959:   border-spacing: 1px;
1.515     albertel 6960: }
1.523     albertel 6961: 
1.515     albertel 6962: table.LC_prior_tries td {
1.524     albertel 6963:   padding: 2px;
1.515     albertel 6964: }
1.523     albertel 6965: 
                   6966: .LC_answer_correct {
1.795     www      6967:   background: lightgreen;
                   6968:   color: darkgreen;
                   6969:   padding: 6px;
1.523     albertel 6970: }
1.795     www      6971: 
1.523     albertel 6972: .LC_answer_charged_try {
1.797     www      6973:   background: #FFAAAA;
1.795     www      6974:   color: darkred;
                   6975:   padding: 6px;
1.523     albertel 6976: }
1.795     www      6977: 
1.779     bisitz   6978: .LC_answer_not_charged_try,
1.523     albertel 6979: .LC_answer_no_grade,
                   6980: .LC_answer_late {
1.795     www      6981:   background: lightyellow;
1.523     albertel 6982:   color: black;
1.795     www      6983:   padding: 6px;
1.523     albertel 6984: }
1.795     www      6985: 
1.523     albertel 6986: .LC_answer_previous {
1.795     www      6987:   background: lightblue;
                   6988:   color: darkblue;
                   6989:   padding: 6px;
1.523     albertel 6990: }
1.795     www      6991: 
1.779     bisitz   6992: .LC_answer_no_message {
1.777     tempelho 6993:   background: #FFFFFF;
                   6994:   color: black;
1.795     www      6995:   padding: 6px;
1.779     bisitz   6996: }
1.795     www      6997: 
1.779     bisitz   6998: .LC_answer_unknown {
                   6999:   background: orange;
                   7000:   color: black;
1.795     www      7001:   padding: 6px;
1.777     tempelho 7002: }
1.795     www      7003: 
1.529     albertel 7004: span.LC_prior_numerical,
                   7005: span.LC_prior_string,
                   7006: span.LC_prior_custom,
                   7007: span.LC_prior_reaction,
                   7008: span.LC_prior_math {
1.925     bisitz   7009:   font-family: $mono;
1.523     albertel 7010:   white-space: pre;
                   7011: }
                   7012: 
1.525     albertel 7013: span.LC_prior_string {
1.925     bisitz   7014:   font-family: $mono;
1.525     albertel 7015:   white-space: pre;
                   7016: }
                   7017: 
1.523     albertel 7018: table.LC_prior_option {
                   7019:   width: 100%;
                   7020:   border-collapse: collapse;
                   7021: }
1.795     www      7022: 
1.911     bisitz   7023: table.LC_prior_rank,
1.795     www      7024: table.LC_prior_match {
1.528     albertel 7025:   border-collapse: collapse;
                   7026: }
1.795     www      7027: 
1.528     albertel 7028: table.LC_prior_option tr td,
                   7029: table.LC_prior_rank tr td,
                   7030: table.LC_prior_match tr td {
1.524     albertel 7031:   border: 1px solid #000000;
1.515     albertel 7032: }
                   7033: 
1.855     bisitz   7034: .LC_nobreak {
1.544     albertel 7035:   white-space: nowrap;
1.519     raeburn  7036: }
                   7037: 
1.576     raeburn  7038: span.LC_cusr_emph {
                   7039:   font-style: italic;
                   7040: }
                   7041: 
1.633     raeburn  7042: span.LC_cusr_subheading {
                   7043:   font-weight: normal;
                   7044:   font-size: 85%;
                   7045: }
                   7046: 
1.861     bisitz   7047: div.LC_docs_entry_move {
1.859     bisitz   7048:   border: 1px solid #BBBBBB;
1.545     albertel 7049:   background: #DDDDDD;
1.861     bisitz   7050:   width: 22px;
1.859     bisitz   7051:   padding: 1px;
                   7052:   margin: 0;
1.545     albertel 7053: }
                   7054: 
1.861     bisitz   7055: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7056: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7057:   font-size: x-small;
                   7058: }
1.795     www      7059: 
1.861     bisitz   7060: .LC_docs_entry_parameter {
                   7061:   white-space: nowrap;
                   7062: }
                   7063: 
1.544     albertel 7064: .LC_docs_copy {
1.545     albertel 7065:   color: #000099;
1.544     albertel 7066: }
1.795     www      7067: 
1.544     albertel 7068: .LC_docs_cut {
1.545     albertel 7069:   color: #550044;
1.544     albertel 7070: }
1.795     www      7071: 
1.544     albertel 7072: .LC_docs_rename {
1.545     albertel 7073:   color: #009900;
1.544     albertel 7074: }
1.795     www      7075: 
1.544     albertel 7076: .LC_docs_remove {
1.545     albertel 7077:   color: #990000;
                   7078: }
                   7079: 
1.547     albertel 7080: .LC_docs_reinit_warn,
                   7081: .LC_docs_ext_edit {
                   7082:   font-size: x-small;
                   7083: }
                   7084: 
1.545     albertel 7085: table.LC_docs_adddocs td,
                   7086: table.LC_docs_adddocs th {
                   7087:   border: 1px solid #BBBBBB;
                   7088:   padding: 4px;
                   7089:   background: #DDDDDD;
1.543     albertel 7090: }
                   7091: 
1.584     albertel 7092: table.LC_sty_begin {
                   7093:   background: #BBFFBB;
                   7094: }
1.795     www      7095: 
1.584     albertel 7096: table.LC_sty_end {
                   7097:   background: #FFBBBB;
                   7098: }
                   7099: 
1.589     raeburn  7100: table.LC_double_column {
1.803     bisitz   7101:   border-width: 0;
1.589     raeburn  7102:   border-collapse: collapse;
                   7103:   width: 100%;
                   7104:   padding: 2px;
                   7105: }
                   7106: 
                   7107: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7108:   top: 2px;
1.589     raeburn  7109:   left: 2px;
                   7110:   width: 47%;
                   7111:   vertical-align: top;
                   7112: }
                   7113: 
                   7114: table.LC_double_column tr td.LC_right_col {
                   7115:   top: 2px;
1.779     bisitz   7116:   right: 2px;
1.589     raeburn  7117:   width: 47%;
                   7118:   vertical-align: top;
                   7119: }
                   7120: 
1.591     raeburn  7121: div.LC_left_float {
                   7122:   float: left;
                   7123:   padding-right: 5%;
1.597     albertel 7124:   padding-bottom: 4px;
1.591     raeburn  7125: }
                   7126: 
                   7127: div.LC_clear_float_header {
1.597     albertel 7128:   padding-bottom: 2px;
1.591     raeburn  7129: }
                   7130: 
                   7131: div.LC_clear_float_footer {
1.597     albertel 7132:   padding-top: 10px;
1.591     raeburn  7133:   clear: both;
                   7134: }
                   7135: 
1.597     albertel 7136: div.LC_grade_show_user {
1.941     bisitz   7137: /*  border-left: 5px solid $sidebg; */
                   7138:   border-top: 5px solid #000000;
                   7139:   margin: 50px 0 0 0;
1.936     bisitz   7140:   padding: 15px 0 5px 10px;
1.597     albertel 7141: }
1.795     www      7142: 
1.936     bisitz   7143: div.LC_grade_show_user_odd_row {
1.941     bisitz   7144: /*  border-left: 5px solid #000000; */
                   7145: }
                   7146: 
                   7147: div.LC_grade_show_user div.LC_Box {
                   7148:   margin-right: 50px;
1.597     albertel 7149: }
                   7150: 
                   7151: div.LC_grade_submissions,
                   7152: div.LC_grade_message_center,
1.936     bisitz   7153: div.LC_grade_info_links {
1.597     albertel 7154:   margin: 5px;
                   7155:   width: 99%;
                   7156:   background: #FFFFFF;
                   7157: }
1.795     www      7158: 
1.597     albertel 7159: div.LC_grade_submissions_header,
1.936     bisitz   7160: div.LC_grade_message_center_header {
1.705     tempelho 7161:   font-weight: bold;
                   7162:   font-size: large;
1.597     albertel 7163: }
1.795     www      7164: 
1.597     albertel 7165: div.LC_grade_submissions_body,
1.936     bisitz   7166: div.LC_grade_message_center_body {
1.597     albertel 7167:   border: 1px solid black;
                   7168:   width: 99%;
                   7169:   background: #FFFFFF;
                   7170: }
1.795     www      7171: 
1.613     albertel 7172: table.LC_scantron_action {
                   7173:   width: 100%;
                   7174: }
1.795     www      7175: 
1.613     albertel 7176: table.LC_scantron_action tr th {
1.698     harmsja  7177:   font-weight:bold;
                   7178:   font-style:normal;
1.613     albertel 7179: }
1.795     www      7180: 
1.779     bisitz   7181: .LC_edit_problem_header,
1.614     albertel 7182: div.LC_edit_problem_footer {
1.705     tempelho 7183:   font-weight: normal;
                   7184:   font-size:  medium;
1.602     albertel 7185:   margin: 2px;
1.1060    bisitz   7186:   background-color: $sidebg;
1.600     albertel 7187: }
1.795     www      7188: 
1.600     albertel 7189: div.LC_edit_problem_header,
1.602     albertel 7190: div.LC_edit_problem_header div,
1.614     albertel 7191: div.LC_edit_problem_footer,
                   7192: div.LC_edit_problem_footer div,
1.602     albertel 7193: div.LC_edit_problem_editxml_header,
                   7194: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7195:   z-index: 100;
1.600     albertel 7196: }
1.795     www      7197: 
1.600     albertel 7198: div.LC_edit_problem_header_title {
1.705     tempelho 7199:   font-weight: bold;
                   7200:   font-size: larger;
1.602     albertel 7201:   background: $tabbg;
                   7202:   padding: 3px;
1.1060    bisitz   7203:   margin: 0 0 5px 0;
1.602     albertel 7204: }
1.795     www      7205: 
1.602     albertel 7206: table.LC_edit_problem_header_title {
                   7207:   width: 100%;
1.600     albertel 7208:   background: $tabbg;
1.602     albertel 7209: }
                   7210: 
1.1205    golterma 7211: div.LC_edit_actionbar {
                   7212:     background-color: $sidebg;
1.1218    droeschl 7213:     margin: 0;
                   7214:     padding: 0;
                   7215:     line-height: 200%;
1.602     albertel 7216: }
1.795     www      7217: 
1.1218    droeschl 7218: div.LC_edit_actionbar div{
                   7219:     padding: 0;
                   7220:     margin: 0;
                   7221:     display: inline-block;
1.600     albertel 7222: }
1.795     www      7223: 
1.1124    bisitz   7224: .LC_edit_opt {
                   7225:   padding-left: 1em;
                   7226:   white-space: nowrap;
                   7227: }
                   7228: 
1.1152    golterma 7229: .LC_edit_problem_latexhelper{
                   7230:     text-align: right;
                   7231: }
                   7232: 
                   7233: #LC_edit_problem_colorful div{
                   7234:     margin-left: 40px;
                   7235: }
                   7236: 
1.1205    golterma 7237: #LC_edit_problem_codemirror div{
                   7238:     margin-left: 0px;
                   7239: }
                   7240: 
1.911     bisitz   7241: img.stift {
1.803     bisitz   7242:   border-width: 0;
                   7243:   vertical-align: middle;
1.677     riegler  7244: }
1.680     riegler  7245: 
1.923     bisitz   7246: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7247:   vertical-align: top;
1.777     tempelho 7248: }
1.795     www      7249: 
1.716     raeburn  7250: div.LC_createcourse {
1.911     bisitz   7251:   margin: 10px 10px 10px 10px;
1.716     raeburn  7252: }
                   7253: 
1.917     raeburn  7254: .LC_dccid {
1.1130    raeburn  7255:   float: right;
1.917     raeburn  7256:   margin: 0.2em 0 0 0;
                   7257:   padding: 0;
                   7258:   font-size: 90%;
                   7259:   display:none;
                   7260: }
                   7261: 
1.897     wenzelju 7262: ol.LC_primary_menu a:hover,
1.721     harmsja  7263: ol#LC_MenuBreadcrumbs a:hover,
                   7264: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7265: ul#LC_secondary_menu a:hover,
1.721     harmsja  7266: .LC_FormSectionClearButton input:hover
1.795     www      7267: ul.LC_TabContent   li:hover a {
1.952     onken    7268:   color:$button_hover;
1.911     bisitz   7269:   text-decoration:none;
1.693     droeschl 7270: }
                   7271: 
1.779     bisitz   7272: h1 {
1.911     bisitz   7273:   padding: 0;
                   7274:   line-height:130%;
1.693     droeschl 7275: }
1.698     harmsja  7276: 
1.911     bisitz   7277: h2,
                   7278: h3,
                   7279: h4,
                   7280: h5,
                   7281: h6 {
                   7282:   margin: 5px 0 5px 0;
                   7283:   padding: 0;
                   7284:   line-height:130%;
1.693     droeschl 7285: }
1.795     www      7286: 
                   7287: .LC_hcell {
1.911     bisitz   7288:   padding:3px 15px 3px 15px;
                   7289:   margin: 0;
                   7290:   background-color:$tabbg;
                   7291:   color:$fontmenu;
                   7292:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7293: }
1.795     www      7294: 
1.840     bisitz   7295: .LC_Box > .LC_hcell {
1.911     bisitz   7296:   margin: 0 -10px 10px -10px;
1.835     bisitz   7297: }
                   7298: 
1.721     harmsja  7299: .LC_noBorder {
1.911     bisitz   7300:   border: 0;
1.698     harmsja  7301: }
1.693     droeschl 7302: 
1.721     harmsja  7303: .LC_FormSectionClearButton input {
1.911     bisitz   7304:   background-color:transparent;
                   7305:   border: none;
                   7306:   cursor:pointer;
                   7307:   text-decoration:underline;
1.693     droeschl 7308: }
1.763     bisitz   7309: 
                   7310: .LC_help_open_topic {
1.911     bisitz   7311:   color: #FFFFFF;
                   7312:   background-color: #EEEEFF;
                   7313:   margin: 1px;
                   7314:   padding: 4px;
                   7315:   border: 1px solid #000033;
                   7316:   white-space: nowrap;
                   7317:   /* vertical-align: middle; */
1.759     neumanie 7318: }
1.693     droeschl 7319: 
1.911     bisitz   7320: dl,
                   7321: ul,
                   7322: div,
                   7323: fieldset {
                   7324:   margin: 10px 10px 10px 0;
                   7325:   /* overflow: hidden; */
1.693     droeschl 7326: }
1.795     www      7327: 
1.1211    raeburn  7328: article.geogebraweb div {
                   7329:     margin: 0;
                   7330: }
                   7331: 
1.838     bisitz   7332: fieldset > legend {
1.911     bisitz   7333:   font-weight: bold;
                   7334:   padding: 0 5px 0 5px;
1.838     bisitz   7335: }
                   7336: 
1.813     bisitz   7337: #LC_nav_bar {
1.911     bisitz   7338:   float: left;
1.995     raeburn  7339:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7340:   margin: 0 0 2px 0;
1.807     droeschl 7341: }
                   7342: 
1.916     droeschl 7343: #LC_realm {
                   7344:   margin: 0.2em 0 0 0;
                   7345:   padding: 0;
                   7346:   font-weight: bold;
                   7347:   text-align: center;
1.995     raeburn  7348:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7349: }
                   7350: 
1.911     bisitz   7351: #LC_nav_bar em {
                   7352:   font-weight: bold;
                   7353:   font-style: normal;
1.807     droeschl 7354: }
                   7355: 
1.897     wenzelju 7356: ol.LC_primary_menu {
1.934     droeschl 7357:   margin: 0;
1.1076    raeburn  7358:   padding: 0;
1.807     droeschl 7359: }
                   7360: 
1.852     droeschl 7361: ol#LC_PathBreadcrumbs {
1.911     bisitz   7362:   margin: 0;
1.693     droeschl 7363: }
                   7364: 
1.897     wenzelju 7365: ol.LC_primary_menu li {
1.1076    raeburn  7366:   color: RGB(80, 80, 80);
                   7367:   vertical-align: middle;
                   7368:   text-align: left;
                   7369:   list-style: none;
1.1205    golterma 7370:   position: relative;
1.1076    raeburn  7371:   float: left;
1.1205    golterma 7372:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7373:   line-height: 1.5em;
1.1076    raeburn  7374: }
                   7375: 
1.1205    golterma 7376: ol.LC_primary_menu li a,
                   7377: ol.LC_primary_menu li p {
1.1076    raeburn  7378:   display: block;
                   7379:   margin: 0;
                   7380:   padding: 0 5px 0 10px;
                   7381:   text-decoration: none;
                   7382: }
                   7383: 
1.1205    golterma 7384: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7385:   display: inline-block;
                   7386:   width: 95%;
                   7387:   text-align: left;
                   7388: }
                   7389: 
                   7390: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7391:   display: inline-block;	
                   7392:   width: 5%;
                   7393:   float: right;
                   7394:   text-align: right;
                   7395:   font-size: 70%;
                   7396: }
                   7397: 
                   7398: ol.LC_primary_menu ul {
1.1076    raeburn  7399:   display: none;
1.1205    golterma 7400:   width: 15em;
1.1076    raeburn  7401:   background-color: $data_table_light;
1.1205    golterma 7402:   position: absolute;
                   7403:   top: 100%;
1.1076    raeburn  7404: }
                   7405: 
1.1205    golterma 7406: ol.LC_primary_menu ul ul {
                   7407:   left: 100%;
                   7408:   top: 0;
                   7409: }
                   7410: 
                   7411: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7412:   display: block;
                   7413:   position: absolute;
                   7414:   margin: 0;
                   7415:   padding: 0;
1.1078    raeburn  7416:   z-index: 2;
1.1076    raeburn  7417: }
                   7418: 
                   7419: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7420: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7421:   font-size: 90%;
1.911     bisitz   7422:   vertical-align: top;
1.1076    raeburn  7423:   float: none;
1.1079    raeburn  7424:   border-left: 1px solid black;
                   7425:   border-right: 1px solid black;
1.1205    golterma 7426: /* A dark bottom border to visualize different menu options; 
                   7427: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7428:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7429: }
                   7430: 
1.1205    golterma 7431: ol.LC_primary_menu li li p:hover {
                   7432:   color:$button_hover;
                   7433:   text-decoration:none;
                   7434:   background-color:$data_table_dark;
1.1076    raeburn  7435: }
                   7436: 
                   7437: ol.LC_primary_menu li li a:hover {
                   7438:    color:$button_hover;
                   7439:    background-color:$data_table_dark;
1.693     droeschl 7440: }
                   7441: 
1.1205    golterma 7442: /* Font-size equal to the size of the predecessors*/
                   7443: ol.LC_primary_menu li:hover li li {
                   7444:   font-size: 100%;
                   7445: }
                   7446: 
1.897     wenzelju 7447: ol.LC_primary_menu li img {
1.911     bisitz   7448:   vertical-align: bottom;
1.934     droeschl 7449:   height: 1.1em;
1.1077    raeburn  7450:   margin: 0.2em 0 0 0;
1.693     droeschl 7451: }
                   7452: 
1.897     wenzelju 7453: ol.LC_primary_menu a {
1.911     bisitz   7454:   color: RGB(80, 80, 80);
                   7455:   text-decoration: none;
1.693     droeschl 7456: }
1.795     www      7457: 
1.949     droeschl 7458: ol.LC_primary_menu a.LC_new_message {
                   7459:   font-weight:bold;
                   7460:   color: darkred;
                   7461: }
                   7462: 
1.975     raeburn  7463: ol.LC_docs_parameters {
                   7464:   margin-left: 0;
                   7465:   padding: 0;
                   7466:   list-style: none;
                   7467: }
                   7468: 
                   7469: ol.LC_docs_parameters li {
                   7470:   margin: 0;
                   7471:   padding-right: 20px;
                   7472:   display: inline;
                   7473: }
                   7474: 
1.976     raeburn  7475: ol.LC_docs_parameters li:before {
                   7476:   content: "\\002022 \\0020";
                   7477: }
                   7478: 
                   7479: li.LC_docs_parameters_title {
                   7480:   font-weight: bold;
                   7481: }
                   7482: 
                   7483: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7484:   content: "";
                   7485: }
                   7486: 
1.897     wenzelju 7487: ul#LC_secondary_menu {
1.1107    raeburn  7488:   clear: right;
1.911     bisitz   7489:   color: $fontmenu;
                   7490:   background: $tabbg;
                   7491:   list-style: none;
                   7492:   padding: 0;
                   7493:   margin: 0;
                   7494:   width: 100%;
1.995     raeburn  7495:   text-align: left;
1.1107    raeburn  7496:   float: left;
1.808     droeschl 7497: }
                   7498: 
1.897     wenzelju 7499: ul#LC_secondary_menu li {
1.911     bisitz   7500:   font-weight: bold;
                   7501:   line-height: 1.8em;
1.1107    raeburn  7502:   border-right: 1px solid black;
                   7503:   float: left;
                   7504: }
                   7505: 
                   7506: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7507:   background-color: $data_table_light;
                   7508: }
                   7509: 
                   7510: ul#LC_secondary_menu li a {
1.911     bisitz   7511:   padding: 0 0.8em;
1.1107    raeburn  7512: }
                   7513: 
                   7514: ul#LC_secondary_menu li ul {
                   7515:   display: none;
                   7516: }
                   7517: 
                   7518: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7519:   display: block;
                   7520:   position: absolute;
                   7521:   margin: 0;
                   7522:   padding: 0;
                   7523:   list-style:none;
                   7524:   float: none;
                   7525:   background-color: $data_table_light;
                   7526:   z-index: 2;
                   7527:   margin-left: -1px;
                   7528: }
                   7529: 
                   7530: ul#LC_secondary_menu li ul li {
                   7531:   font-size: 90%;
                   7532:   vertical-align: top;
                   7533:   border-left: 1px solid black;
1.911     bisitz   7534:   border-right: 1px solid black;
1.1119    raeburn  7535:   background-color: $data_table_light;
1.1107    raeburn  7536:   list-style:none;
                   7537:   float: none;
                   7538: }
                   7539: 
                   7540: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7541:   background-color: $data_table_dark;
1.807     droeschl 7542: }
                   7543: 
1.847     tempelho 7544: ul.LC_TabContent {
1.911     bisitz   7545:   display:block;
                   7546:   background: $sidebg;
                   7547:   border-bottom: solid 1px $lg_border_color;
                   7548:   list-style:none;
1.1020    raeburn  7549:   margin: -1px -10px 0 -10px;
1.911     bisitz   7550:   padding: 0;
1.693     droeschl 7551: }
                   7552: 
1.795     www      7553: ul.LC_TabContent li,
                   7554: ul.LC_TabContentBigger li {
1.911     bisitz   7555:   float:left;
1.741     harmsja  7556: }
1.795     www      7557: 
1.897     wenzelju 7558: ul#LC_secondary_menu li a {
1.911     bisitz   7559:   color: $fontmenu;
                   7560:   text-decoration: none;
1.693     droeschl 7561: }
1.795     www      7562: 
1.721     harmsja  7563: ul.LC_TabContent {
1.952     onken    7564:   min-height:20px;
1.721     harmsja  7565: }
1.795     www      7566: 
                   7567: ul.LC_TabContent li {
1.911     bisitz   7568:   vertical-align:middle;
1.959     onken    7569:   padding: 0 16px 0 10px;
1.911     bisitz   7570:   background-color:$tabbg;
                   7571:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7572:   border-left: solid 1px $font;
1.721     harmsja  7573: }
1.795     www      7574: 
1.847     tempelho 7575: ul.LC_TabContent .right {
1.911     bisitz   7576:   float:right;
1.847     tempelho 7577: }
                   7578: 
1.911     bisitz   7579: ul.LC_TabContent li a,
                   7580: ul.LC_TabContent li {
                   7581:   color:rgb(47,47,47);
                   7582:   text-decoration:none;
                   7583:   font-size:95%;
                   7584:   font-weight:bold;
1.952     onken    7585:   min-height:20px;
                   7586: }
                   7587: 
1.959     onken    7588: ul.LC_TabContent li a:hover,
                   7589: ul.LC_TabContent li a:focus {
1.952     onken    7590:   color: $button_hover;
1.959     onken    7591:   background:none;
                   7592:   outline:none;
1.952     onken    7593: }
                   7594: 
                   7595: ul.LC_TabContent li:hover {
                   7596:   color: $button_hover;
                   7597:   cursor:pointer;
1.721     harmsja  7598: }
1.795     www      7599: 
1.911     bisitz   7600: ul.LC_TabContent li.active {
1.952     onken    7601:   color: $font;
1.911     bisitz   7602:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7603:   border-bottom:solid 1px #FFFFFF;
                   7604:   cursor: default;
1.744     ehlerst  7605: }
1.795     www      7606: 
1.959     onken    7607: ul.LC_TabContent li.active a {
                   7608:   color:$font;
                   7609:   background:#FFFFFF;
                   7610:   outline: none;
                   7611: }
1.1047    raeburn  7612: 
                   7613: ul.LC_TabContent li.goback {
                   7614:   float: left;
                   7615:   border-left: none;
                   7616: }
                   7617: 
1.870     tempelho 7618: #maincoursedoc {
1.911     bisitz   7619:   clear:both;
1.870     tempelho 7620: }
                   7621: 
                   7622: ul.LC_TabContentBigger {
1.911     bisitz   7623:   display:block;
                   7624:   list-style:none;
                   7625:   padding: 0;
1.870     tempelho 7626: }
                   7627: 
1.795     www      7628: ul.LC_TabContentBigger li {
1.911     bisitz   7629:   vertical-align:bottom;
                   7630:   height: 30px;
                   7631:   font-size:110%;
                   7632:   font-weight:bold;
                   7633:   color: #737373;
1.841     tempelho 7634: }
                   7635: 
1.957     onken    7636: ul.LC_TabContentBigger li.active {
                   7637:   position: relative;
                   7638:   top: 1px;
                   7639: }
                   7640: 
1.870     tempelho 7641: ul.LC_TabContentBigger li a {
1.911     bisitz   7642:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7643:   height: 30px;
                   7644:   line-height: 30px;
                   7645:   text-align: center;
                   7646:   display: block;
                   7647:   text-decoration: none;
1.958     onken    7648:   outline: none;  
1.741     harmsja  7649: }
1.795     www      7650: 
1.870     tempelho 7651: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7652:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7653:   color:$font;
1.744     ehlerst  7654: }
1.795     www      7655: 
1.870     tempelho 7656: ul.LC_TabContentBigger li b {
1.911     bisitz   7657:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7658:   display: block;
                   7659:   float: left;
                   7660:   padding: 0 30px;
1.957     onken    7661:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7662: }
                   7663: 
1.956     onken    7664: ul.LC_TabContentBigger li:hover b {
                   7665:   color:$button_hover;
                   7666: }
                   7667: 
1.870     tempelho 7668: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7669:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7670:   color:$font;
1.957     onken    7671:   border: 0;
1.741     harmsja  7672: }
1.693     droeschl 7673: 
1.870     tempelho 7674: 
1.862     bisitz   7675: ul.LC_CourseBreadcrumbs {
                   7676:   background: $sidebg;
1.1020    raeburn  7677:   height: 2em;
1.862     bisitz   7678:   padding-left: 10px;
1.1020    raeburn  7679:   margin: 0;
1.862     bisitz   7680:   list-style-position: inside;
                   7681: }
                   7682: 
1.911     bisitz   7683: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7684: ol#LC_PathBreadcrumbs {
1.911     bisitz   7685:   padding-left: 10px;
                   7686:   margin: 0;
1.933     droeschl 7687:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7688: }
                   7689: 
1.911     bisitz   7690: ol#LC_MenuBreadcrumbs li,
                   7691: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7692: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7693:   display: inline;
1.933     droeschl 7694:   white-space: normal;  
1.693     droeschl 7695: }
                   7696: 
1.823     bisitz   7697: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7698: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7699:   text-decoration: none;
                   7700:   font-size:90%;
1.693     droeschl 7701: }
1.795     www      7702: 
1.969     droeschl 7703: ol#LC_MenuBreadcrumbs h1 {
                   7704:   display: inline;
                   7705:   font-size: 90%;
                   7706:   line-height: 2.5em;
                   7707:   margin: 0;
                   7708:   padding: 0;
                   7709: }
                   7710: 
1.795     www      7711: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7712:   text-decoration:none;
                   7713:   font-size:100%;
                   7714:   font-weight:bold;
1.693     droeschl 7715: }
1.795     www      7716: 
1.840     bisitz   7717: .LC_Box {
1.911     bisitz   7718:   border: solid 1px $lg_border_color;
                   7719:   padding: 0 10px 10px 10px;
1.746     neumanie 7720: }
1.795     www      7721: 
1.1020    raeburn  7722: .LC_DocsBox {
                   7723:   border: solid 1px $lg_border_color;
                   7724:   padding: 0 0 10px 10px;
                   7725: }
                   7726: 
1.795     www      7727: .LC_AboutMe_Image {
1.911     bisitz   7728:   float:left;
                   7729:   margin-right:10px;
1.747     neumanie 7730: }
1.795     www      7731: 
                   7732: .LC_Clear_AboutMe_Image {
1.911     bisitz   7733:   clear:left;
1.747     neumanie 7734: }
1.795     www      7735: 
1.721     harmsja  7736: dl.LC_ListStyleClean dt {
1.911     bisitz   7737:   padding-right: 5px;
                   7738:   display: table-header-group;
1.693     droeschl 7739: }
                   7740: 
1.721     harmsja  7741: dl.LC_ListStyleClean dd {
1.911     bisitz   7742:   display: table-row;
1.693     droeschl 7743: }
                   7744: 
1.721     harmsja  7745: .LC_ListStyleClean,
                   7746: .LC_ListStyleSimple,
                   7747: .LC_ListStyleNormal,
1.795     www      7748: .LC_ListStyleSpecial {
1.911     bisitz   7749:   /* display:block; */
                   7750:   list-style-position: inside;
                   7751:   list-style-type: none;
                   7752:   overflow: hidden;
                   7753:   padding: 0;
1.693     droeschl 7754: }
                   7755: 
1.721     harmsja  7756: .LC_ListStyleSimple li,
                   7757: .LC_ListStyleSimple dd,
                   7758: .LC_ListStyleNormal li,
                   7759: .LC_ListStyleNormal dd,
                   7760: .LC_ListStyleSpecial li,
1.795     www      7761: .LC_ListStyleSpecial dd {
1.911     bisitz   7762:   margin: 0;
                   7763:   padding: 5px 5px 5px 10px;
                   7764:   clear: both;
1.693     droeschl 7765: }
                   7766: 
1.721     harmsja  7767: .LC_ListStyleClean li,
                   7768: .LC_ListStyleClean dd {
1.911     bisitz   7769:   padding-top: 0;
                   7770:   padding-bottom: 0;
1.693     droeschl 7771: }
                   7772: 
1.721     harmsja  7773: .LC_ListStyleSimple dd,
1.795     www      7774: .LC_ListStyleSimple li {
1.911     bisitz   7775:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7776: }
                   7777: 
1.721     harmsja  7778: .LC_ListStyleSpecial li,
                   7779: .LC_ListStyleSpecial dd {
1.911     bisitz   7780:   list-style-type: none;
                   7781:   background-color: RGB(220, 220, 220);
                   7782:   margin-bottom: 4px;
1.693     droeschl 7783: }
                   7784: 
1.721     harmsja  7785: table.LC_SimpleTable {
1.911     bisitz   7786:   margin:5px;
                   7787:   border:solid 1px $lg_border_color;
1.795     www      7788: }
1.693     droeschl 7789: 
1.721     harmsja  7790: table.LC_SimpleTable tr {
1.911     bisitz   7791:   padding: 0;
                   7792:   border:solid 1px $lg_border_color;
1.693     droeschl 7793: }
1.795     www      7794: 
                   7795: table.LC_SimpleTable thead {
1.911     bisitz   7796:   background:rgb(220,220,220);
1.693     droeschl 7797: }
                   7798: 
1.721     harmsja  7799: div.LC_columnSection {
1.911     bisitz   7800:   display: block;
                   7801:   clear: both;
                   7802:   overflow: hidden;
                   7803:   margin: 0;
1.693     droeschl 7804: }
                   7805: 
1.721     harmsja  7806: div.LC_columnSection>* {
1.911     bisitz   7807:   float: left;
                   7808:   margin: 10px 20px 10px 0;
                   7809:   overflow:hidden;
1.693     droeschl 7810: }
1.721     harmsja  7811: 
1.795     www      7812: table em {
1.911     bisitz   7813:   font-weight: bold;
                   7814:   font-style: normal;
1.748     schulted 7815: }
1.795     www      7816: 
1.779     bisitz   7817: table.LC_tableBrowseRes,
1.795     www      7818: table.LC_tableOfContent {
1.911     bisitz   7819:   border:none;
                   7820:   border-spacing: 1px;
                   7821:   padding: 3px;
                   7822:   background-color: #FFFFFF;
                   7823:   font-size: 90%;
1.753     droeschl 7824: }
1.789     droeschl 7825: 
1.911     bisitz   7826: table.LC_tableOfContent {
                   7827:   border-collapse: collapse;
1.789     droeschl 7828: }
                   7829: 
1.771     droeschl 7830: table.LC_tableBrowseRes a,
1.768     schulted 7831: table.LC_tableOfContent a {
1.911     bisitz   7832:   background-color: transparent;
                   7833:   text-decoration: none;
1.753     droeschl 7834: }
                   7835: 
1.795     www      7836: table.LC_tableOfContent img {
1.911     bisitz   7837:   border: none;
                   7838:   height: 1.3em;
                   7839:   vertical-align: text-bottom;
                   7840:   margin-right: 0.3em;
1.753     droeschl 7841: }
1.757     schulted 7842: 
1.795     www      7843: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7844:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7845: }
                   7846: 
1.795     www      7847: a#LC_content_toolbar_everything {
1.911     bisitz   7848:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7849: }
                   7850: 
1.795     www      7851: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7852:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7853: }
                   7854: 
1.795     www      7855: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7856:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7857: }
                   7858: 
1.795     www      7859: a#LC_content_toolbar_changefolder {
1.911     bisitz   7860:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7861: }
                   7862: 
1.795     www      7863: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7864:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7865: }
                   7866: 
1.1043    raeburn  7867: a#LC_content_toolbar_edittoplevel {
                   7868:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7869: }
                   7870: 
1.795     www      7871: ul#LC_toolbar li a:hover {
1.911     bisitz   7872:   background-position: bottom center;
1.757     schulted 7873: }
                   7874: 
1.795     www      7875: ul#LC_toolbar {
1.911     bisitz   7876:   padding: 0;
                   7877:   margin: 2px;
                   7878:   list-style:none;
                   7879:   position:relative;
                   7880:   background-color:white;
1.1082    raeburn  7881:   overflow: auto;
1.757     schulted 7882: }
                   7883: 
1.795     www      7884: ul#LC_toolbar li {
1.911     bisitz   7885:   border:1px solid white;
                   7886:   padding: 0;
                   7887:   margin: 0;
                   7888:   float: left;
                   7889:   display:inline;
                   7890:   vertical-align:middle;
1.1082    raeburn  7891:   white-space: nowrap;
1.911     bisitz   7892: }
1.757     schulted 7893: 
1.783     amueller 7894: 
1.795     www      7895: a.LC_toolbarItem {
1.911     bisitz   7896:   display:block;
                   7897:   padding: 0;
                   7898:   margin: 0;
                   7899:   height: 32px;
                   7900:   width: 32px;
                   7901:   color:white;
                   7902:   border: none;
                   7903:   background-repeat:no-repeat;
                   7904:   background-color:transparent;
1.757     schulted 7905: }
                   7906: 
1.915     droeschl 7907: ul.LC_funclist {
                   7908:     margin: 0;
                   7909:     padding: 0.5em 1em 0.5em 0;
                   7910: }
                   7911: 
1.933     droeschl 7912: ul.LC_funclist > li:first-child {
                   7913:     font-weight:bold; 
                   7914:     margin-left:0.8em;
                   7915: }
                   7916: 
1.915     droeschl 7917: ul.LC_funclist + ul.LC_funclist {
                   7918:     /* 
                   7919:        left border as a seperator if we have more than
                   7920:        one list 
                   7921:     */
                   7922:     border-left: 1px solid $sidebg;
                   7923:     /* 
                   7924:        this hides the left border behind the border of the 
                   7925:        outer box if element is wrapped to the next 'line' 
                   7926:     */
                   7927:     margin-left: -1px;
                   7928: }
                   7929: 
1.843     bisitz   7930: ul.LC_funclist li {
1.915     droeschl 7931:   display: inline;
1.782     bisitz   7932:   white-space: nowrap;
1.915     droeschl 7933:   margin: 0 0 0 25px;
                   7934:   line-height: 150%;
1.782     bisitz   7935: }
                   7936: 
1.974     wenzelju 7937: .LC_hidden {
                   7938:   display: none;
                   7939: }
                   7940: 
1.1030    www      7941: .LCmodal-overlay {
                   7942: 		position:fixed;
                   7943: 		top:0;
                   7944: 		right:0;
                   7945: 		bottom:0;
                   7946: 		left:0;
                   7947: 		height:100%;
                   7948: 		width:100%;
                   7949: 		margin:0;
                   7950: 		padding:0;
                   7951: 		background:#999;
                   7952: 		opacity:.75;
                   7953: 		filter: alpha(opacity=75);
                   7954: 		-moz-opacity: 0.75;
                   7955: 		z-index:101;
                   7956: }
                   7957: 
                   7958: * html .LCmodal-overlay {   
                   7959: 		position: absolute;
                   7960: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7961: }
                   7962: 
                   7963: .LCmodal-window {
                   7964: 		position:fixed;
                   7965: 		top:50%;
                   7966: 		left:50%;
                   7967: 		margin:0;
                   7968: 		padding:0;
                   7969: 		z-index:102;
                   7970: 	}
                   7971: 
                   7972: * html .LCmodal-window {
                   7973: 		position:absolute;
                   7974: }
                   7975: 
                   7976: .LCclose-window {
                   7977: 		position:absolute;
                   7978: 		width:32px;
                   7979: 		height:32px;
                   7980: 		right:8px;
                   7981: 		top:8px;
                   7982: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7983: 		text-indent:-99999px;
                   7984: 		overflow:hidden;
                   7985: 		cursor:pointer;
                   7986: }
                   7987: 
1.1100    raeburn  7988: /*
1.1231    damieng  7989:   styles used for response display
                   7990: */
                   7991: div.LC_radiofoil, div.LC_rankfoil {
                   7992:   margin: .5em 0em .5em 0em;
                   7993: }
                   7994: table.LC_itemgroup {
                   7995:   margin-top: 1em;
                   7996: }
                   7997: 
                   7998: /*
1.1100    raeburn  7999:   styles used by TTH when "Default set of options to pass to tth/m
                   8000:   when converting TeX" in course settings has been set
                   8001: 
                   8002:   option passed: -t
                   8003: 
                   8004: */
                   8005: 
                   8006: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8007: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8008: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8009: td div.norm {line-height:normal;}
                   8010: 
                   8011: /*
                   8012:   option passed -y3
                   8013: */
                   8014: 
                   8015: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8016: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8017: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8018: 
1.1230    damieng  8019: /*
                   8020:   sections with roles, for content only
                   8021: */
                   8022: section[class^="role-"] {
                   8023:   padding-left: 10px;
                   8024:   padding-right: 5px;
                   8025:   margin-top: 8px;
                   8026:   margin-bottom: 8px;
                   8027:   border: 1px solid #2A4;
                   8028:   border-radius: 5px;
                   8029:   box-shadow: 0px 1px 1px #BBB;
                   8030: }
                   8031: section[class^="role-"]>h1 {
                   8032:   position: relative;
                   8033:   margin: 0px;
                   8034:   padding-top: 10px;
                   8035:   padding-left: 40px;
                   8036: }
                   8037: section[class^="role-"]>h1:before {
                   8038:   position: absolute;
                   8039:   left: -5px;
                   8040:   top: 5px;
                   8041: }
                   8042: section.role-activity>h1:before {
                   8043:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8044: }
                   8045: section.role-advice>h1:before {
                   8046:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8047: }
                   8048: section.role-bibliography>h1:before {
                   8049:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8050: }
                   8051: section.role-citation>h1:before {
                   8052:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8053: }
                   8054: section.role-conclusion>h1:before {
                   8055:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8056: }
                   8057: section.role-definition>h1:before {
                   8058:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8059: }
                   8060: section.role-demonstration>h1:before {
                   8061:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8062: }
                   8063: section.role-example>h1:before {
                   8064:   content:url('/adm/daxe/images/section_icons/example.png');
                   8065: }
                   8066: section.role-explanation>h1:before {
                   8067:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8068: }
                   8069: section.role-introduction>h1:before {
                   8070:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8071: }
                   8072: section.role-method>h1:before {
                   8073:   content:url('/adm/daxe/images/section_icons/method.png');
                   8074: }
                   8075: section.role-more_information>h1:before {
                   8076:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8077: }
                   8078: section.role-objectives>h1:before {
                   8079:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8080: }
                   8081: section.role-prerequisites>h1:before {
                   8082:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8083: }
                   8084: section.role-remark>h1:before {
                   8085:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8086: }
                   8087: section.role-reminder>h1:before {
                   8088:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8089: }
                   8090: section.role-summary>h1:before {
                   8091:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8092: }
                   8093: section.role-syntax>h1:before {
                   8094:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8095: }
                   8096: section.role-warning>h1:before {
                   8097:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8098: }
                   8099: 
1.343     albertel 8100: END
                   8101: }
                   8102: 
1.306     albertel 8103: =pod
                   8104: 
                   8105: =item * &headtag()
                   8106: 
                   8107: Returns a uniform footer for LON-CAPA web pages.
                   8108: 
1.307     albertel 8109: Inputs: $title - optional title for the head
                   8110:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8111:         $args - optional arguments
1.319     albertel 8112:             force_register - if is true call registerurl so the remote is 
                   8113:                              informed
1.415     albertel 8114:             redirect       -> array ref of
                   8115:                                    1- seconds before redirect occurs
                   8116:                                    2- url to redirect to
                   8117:                                    3- whether the side effect should occur
1.315     albertel 8118:                            (side effect of setting 
                   8119:                                $env{'internal.head.redirect'} to the url 
                   8120:                                redirected too)
1.352     albertel 8121:             domain         -> force to color decorate a page for a specific
                   8122:                                domain
                   8123:             function       -> force usage of a specific rolish color scheme
                   8124:             bgcolor        -> override the default page bgcolor
1.460     albertel 8125:             no_auto_mt_title
                   8126:                            -> prevent &mt()ing the title arg
1.464     albertel 8127: 
1.306     albertel 8128: =cut
                   8129: 
                   8130: sub headtag {
1.313     albertel 8131:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8132:     
1.363     albertel 8133:     my $function = $args->{'function'} || &get_users_function();
                   8134:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8135:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8136:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8137:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8138: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8139: 		   #time(),
1.418     albertel 8140: 		   $env{'environment.color.timestamp'},
1.363     albertel 8141: 		   $function,$domain,$bgcolor);
                   8142: 
1.369     www      8143:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8144: 
1.308     albertel 8145:     my $result =
                   8146: 	'<head>'.
1.1160    raeburn  8147: 	&font_settings($args);
1.319     albertel 8148: 
1.1188    raeburn  8149:     my $inhibitprint;
                   8150:     if ($args->{'print_suppress'}) {
                   8151:         $inhibitprint = &print_suppression();
                   8152:     }
1.1064    raeburn  8153: 
1.461     albertel 8154:     if (!$args->{'frameset'}) {
                   8155: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8156:     }
1.962     droeschl 8157:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8158:         $result .= Apache::lonxml::display_title();
1.319     albertel 8159:     }
1.436     albertel 8160:     if (!$args->{'no_nav_bar'} 
                   8161: 	&& !$args->{'only_body'}
                   8162: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8163: 	$result .= &help_menu_js($httphost);
1.1032    www      8164:         $result.=&modal_window();
1.1038    www      8165:         $result.=&togglebox_script();
1.1034    www      8166:         $result.=&wishlist_window();
1.1041    www      8167:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8168:     } else {
                   8169:         if ($args->{'add_modal'}) {
                   8170:            $result.=&modal_window();
                   8171:         }
                   8172:         if ($args->{'add_wishlist'}) {
                   8173:            $result.=&wishlist_window();
                   8174:         }
1.1038    www      8175:         if ($args->{'add_togglebox'}) {
                   8176:            $result.=&togglebox_script();
                   8177:         }
1.1041    www      8178:         if ($args->{'add_progressbar'}) {
                   8179:            $result.=&LCprogressbarUpdate_script();
                   8180:         }
1.436     albertel 8181:     }
1.314     albertel 8182:     if (ref($args->{'redirect'})) {
1.414     albertel 8183: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8184: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8185: 	if (!$inhibit_continue) {
                   8186: 	    $env{'internal.head.redirect'} = $url;
                   8187: 	}
1.313     albertel 8188: 	$result.=<<ADDMETA
                   8189: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8190: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8191: ADDMETA
1.1210    raeburn  8192:     } else {
                   8193:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8194:             my $requrl = $env{'request.uri'};
                   8195:             if ($requrl eq '') {
                   8196:                 $requrl = $ENV{'REQUEST_URI'};
                   8197:                 $requrl =~ s/\?.+$//;
                   8198:             }
                   8199:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8200:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8201:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8202:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8203:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8204:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   8205:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8206:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   8207:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   8208:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   8209:                             if (($newserver) && ($newserver ne $lonhost)) {
                   8210:                                 my $numsec = 5;
                   8211:                                 my $timeout = $numsec * 1000;
                   8212:                                 my ($newurl,$locknum,%locks,$msg);
                   8213:                                 if ($env{'request.role.adv'}) {
                   8214:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8215:                                 }
                   8216:                                 my $disable_submit = 0;
                   8217:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   8218:                                     $disable_submit = 1;
                   8219:                                 }
                   8220:                                 if ($locknum) {
                   8221:                                     my @lockinfo = sort(values(%locks));
                   8222:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   8223:                                            join(", ",sort(values(%locks)))."\\n".
                   8224:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   8225:                                 } else {
                   8226:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8227:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   8228:                                     }
                   8229:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8230:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8231:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8232:                                         $newurl .= '&role='.$env{'request.role'};
                   8233:                                     }
                   8234:                                     if ($env{'request.symb'}) {
                   8235:                                         $newurl .= '&symb='.$env{'request.symb'};
                   8236:                                     } else {
                   8237:                                         $newurl .= '&origurl='.$requrl;
                   8238:                                     }
                   8239:                                 }
1.1222    damieng  8240:                                 &js_escape(\$msg);
1.1210    raeburn  8241:                                 $result.=<<OFFLOAD
                   8242: <meta http-equiv="pragma" content="no-cache" />
                   8243: <script type="text/javascript">
1.1215    raeburn  8244: // <![CDATA[
1.1210    raeburn  8245: function LC_Offload_Now() {
                   8246:     var dest = "$newurl";
                   8247:     if (dest != '') {
                   8248:         window.location.href="$newurl";
                   8249:     }
                   8250: }
1.1214    raeburn  8251: \$(document).ready(function () {
                   8252:     window.alert('$msg');
                   8253:     if ($disable_submit) {
1.1210    raeburn  8254:         \$(".LC_hwk_submit").prop("disabled", true);
                   8255:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  8256:     }
                   8257:     setTimeout('LC_Offload_Now()', $timeout);
                   8258: });
1.1215    raeburn  8259: // ]]>
1.1210    raeburn  8260: </script>
                   8261: OFFLOAD
                   8262:                             }
                   8263:                         }
                   8264:                     }
                   8265:                 }
                   8266:             }
                   8267:         }
1.313     albertel 8268:     }
1.306     albertel 8269:     if (!defined($title)) {
                   8270: 	$title = 'The LearningOnline Network with CAPA';
                   8271:     }
1.460     albertel 8272:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8273:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  8274: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8275:     if (!$args->{'frameset'}) {
                   8276:         $result .= ' /';
                   8277:     }
                   8278:     $result .= '>' 
1.1064    raeburn  8279:         .$inhibitprint
1.414     albertel 8280: 	.$head_extra;
1.1242    raeburn  8281:     my $clientmobile;
                   8282:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8283:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8284:     } else {
                   8285:         $clientmobile = $env{'browser.mobile'};
                   8286:     }
                   8287:     if ($clientmobile) {
1.1137    raeburn  8288:         $result .= '
                   8289: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8290: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8291:     }
1.962     droeschl 8292:     return $result.'</head>';
1.306     albertel 8293: }
                   8294: 
                   8295: =pod
                   8296: 
1.340     albertel 8297: =item * &font_settings()
                   8298: 
                   8299: Returns neccessary <meta> to set the proper encoding
                   8300: 
1.1160    raeburn  8301: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8302: 
                   8303: =cut
                   8304: 
                   8305: sub font_settings {
1.1160    raeburn  8306:     my ($args) = @_;
1.340     albertel 8307:     my $headerstring='';
1.1160    raeburn  8308:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8309:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  8310:         $headerstring.=
                   8311:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8312:         if (!$args->{'frameset'}) {
                   8313: 	    $headerstring.= ' /';
                   8314:         }
                   8315: 	$headerstring .= '>'."\n";
1.340     albertel 8316:     }
                   8317:     return $headerstring;
                   8318: }
                   8319: 
1.341     albertel 8320: =pod
                   8321: 
1.1064    raeburn  8322: =item * &print_suppression()
                   8323: 
                   8324: In course context returns css which causes the body to be blank when media="print",
                   8325: if printout generation is unavailable for the current resource.
                   8326: 
                   8327: This could be because:
                   8328: 
                   8329: (a) printstartdate is in the future
                   8330: 
                   8331: (b) printenddate is in the past
                   8332: 
                   8333: (c) there is an active exam block with "printout"
                   8334: functionality blocked
                   8335: 
                   8336: Users with pav, pfo or evb privileges are exempt.
                   8337: 
                   8338: Inputs: none
                   8339: 
                   8340: =cut
                   8341: 
                   8342: 
                   8343: sub print_suppression {
                   8344:     my $noprint;
                   8345:     if ($env{'request.course.id'}) {
                   8346:         my $scope = $env{'request.course.id'};
                   8347:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8348:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8349:             return;
                   8350:         }
                   8351:         if ($env{'request.course.sec'} ne '') {
                   8352:             $scope .= "/$env{'request.course.sec'}";
                   8353:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8354:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8355:                 return;
1.1064    raeburn  8356:             }
                   8357:         }
                   8358:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8359:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8360:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8361:         if ($blocked) {
                   8362:             my $checkrole = "cm./$cdom/$cnum";
                   8363:             if ($env{'request.course.sec'} ne '') {
                   8364:                 $checkrole .= "/$env{'request.course.sec'}";
                   8365:             }
                   8366:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8367:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8368:                 $noprint = 1;
                   8369:             }
                   8370:         }
                   8371:         unless ($noprint) {
                   8372:             my $symb = &Apache::lonnet::symbread();
                   8373:             if ($symb ne '') {
                   8374:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8375:                 if (ref($navmap)) {
                   8376:                     my $res = $navmap->getBySymb($symb);
                   8377:                     if (ref($res)) {
                   8378:                         if (!$res->resprintable()) {
                   8379:                             $noprint = 1;
                   8380:                         }
                   8381:                     }
                   8382:                 }
                   8383:             }
                   8384:         }
                   8385:         if ($noprint) {
                   8386:             return <<"ENDSTYLE";
                   8387: <style type="text/css" media="print">
                   8388:     body { display:none }
                   8389: </style>
                   8390: ENDSTYLE
                   8391:         }
                   8392:     }
                   8393:     return;
                   8394: }
                   8395: 
                   8396: =pod
                   8397: 
1.341     albertel 8398: =item * &xml_begin()
                   8399: 
                   8400: Returns the needed doctype and <html>
                   8401: 
                   8402: Inputs: none
                   8403: 
                   8404: =cut
                   8405: 
                   8406: sub xml_begin {
1.1168    raeburn  8407:     my ($is_frameset) = @_;
1.341     albertel 8408:     my $output='';
                   8409: 
                   8410:     if ($env{'browser.mathml'}) {
                   8411: 	$output='<?xml version="1.0"?>'
                   8412:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8413: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8414:             
                   8415: #	    .'<!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">] >'
                   8416: 	    .'<!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">'
                   8417:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8418: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8419:     } elsif ($is_frameset) {
                   8420:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8421:                 '<html>'."\n";
1.341     albertel 8422:     } else {
1.1168    raeburn  8423: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8424:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8425:     }
                   8426:     return $output;
                   8427: }
1.340     albertel 8428: 
                   8429: =pod
                   8430: 
1.306     albertel 8431: =item * &start_page()
                   8432: 
                   8433: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8434: 
1.648     raeburn  8435: Inputs:
                   8436: 
                   8437: =over 4
                   8438: 
                   8439: $title - optional title for the page
                   8440: 
                   8441: $head_extra - optional extra HTML to incude inside the <head>
                   8442: 
                   8443: $args - additional optional args supported are:
                   8444: 
                   8445: =over 8
                   8446: 
                   8447:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8448:                                     arg on
1.814     bisitz   8449:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8450:              add_entries    -> additional attributes to add to the  <body>
                   8451:              domain         -> force to color decorate a page for a 
1.317     albertel 8452:                                     specific domain
1.648     raeburn  8453:              function       -> force usage of a specific rolish color
1.317     albertel 8454:                                     scheme
1.648     raeburn  8455:              redirect       -> see &headtag()
                   8456:              bgcolor        -> override the default page bg color
                   8457:              js_ready       -> return a string ready for being used in 
1.317     albertel 8458:                                     a javascript writeln
1.648     raeburn  8459:              html_encode    -> return a string ready for being used in 
1.320     albertel 8460:                                     a html attribute
1.648     raeburn  8461:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8462:                                     $forcereg arg
1.648     raeburn  8463:              frameset       -> if true will start with a <frameset>
1.330     albertel 8464:                                     rather than <body>
1.648     raeburn  8465:              skip_phases    -> hash ref of 
1.338     albertel 8466:                                     head -> skip the <html><head> generation
                   8467:                                     body -> skip all <body> generation
1.648     raeburn  8468:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8469:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8470:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1096    raeburn  8471:              group          -> includes the current group, if page is for a 
                   8472:                                specific group  
1.361     albertel 8473: 
1.648     raeburn  8474: =back
1.460     albertel 8475: 
1.648     raeburn  8476: =back
1.562     albertel 8477: 
1.306     albertel 8478: =cut
                   8479: 
                   8480: sub start_page {
1.309     albertel 8481:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8482:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8483: 
1.315     albertel 8484:     $env{'internal.start_page'}++;
1.1096    raeburn  8485:     my ($result,@advtools);
1.964     droeschl 8486: 
1.338     albertel 8487:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8488:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8489:     }
                   8490:     
                   8491:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8492: 	if ($args->{'frameset'}) {
                   8493: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8494: 						$args->{'add_entries'});
                   8495: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8496:         } else {
                   8497:             $result .=
                   8498:                 &bodytag($title, 
                   8499:                          $args->{'function'},       $args->{'add_entries'},
                   8500:                          $args->{'only_body'},      $args->{'domain'},
                   8501:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8502:                          $args->{'bgcolor'},        $args,
                   8503:                          \@advtools);
1.831     bisitz   8504:         }
1.330     albertel 8505:     }
1.338     albertel 8506: 
1.315     albertel 8507:     if ($args->{'js_ready'}) {
1.713     kaisler  8508: 		$result = &js_ready($result);
1.315     albertel 8509:     }
1.320     albertel 8510:     if ($args->{'html_encode'}) {
1.713     kaisler  8511: 		$result = &html_encode($result);
                   8512:     }
                   8513: 
1.813     bisitz   8514:     # Preparation for new and consistent functionlist at top of screen
                   8515:     # if ($args->{'functionlist'}) {
                   8516:     #            $result .= &build_functionlist();
                   8517:     #}
                   8518: 
1.964     droeschl 8519:     # Don't add anything more if only_body wanted or in const space
                   8520:     return $result if    $args->{'only_body'} 
                   8521:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8522: 
                   8523:     #Breadcrumbs
1.758     kaisler  8524:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8525: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8526: 		#if any br links exists, add them to the breadcrumbs
                   8527: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8528: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8529: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8530: 			}
                   8531: 		}
1.1096    raeburn  8532:                 # if @advtools array contains items add then to the breadcrumbs
                   8533:                 if (@advtools > 0) {
                   8534:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8535:                 }
1.758     kaisler  8536: 
                   8537: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8538: 		if(exists($args->{'bread_crumbs_component'})){
                   8539: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
1.1237    raeburn  8540: 		} elsif ($args->{'crstype'} eq 'Placement') {
                   8541: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','','','','','','','','',
                   8542:                                                                        $args->{'crstype'});
                   8543:                 } else {
1.758     kaisler  8544: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   8545: 		}
1.320     albertel 8546:     }
1.315     albertel 8547:     return $result;
1.306     albertel 8548: }
                   8549: 
                   8550: sub end_page {
1.315     albertel 8551:     my ($args) = @_;
                   8552:     $env{'internal.end_page'}++;
1.330     albertel 8553:     my $result;
1.335     albertel 8554:     if ($args->{'discussion'}) {
                   8555: 	my ($target,$parser);
                   8556: 	if (ref($args->{'discussion'})) {
                   8557: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8558: 				$args->{'discussion'}{'parser'});
                   8559: 	}
                   8560: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8561:     }
1.330     albertel 8562:     if ($args->{'frameset'}) {
                   8563: 	$result .= '</frameset>';
                   8564:     } else {
1.635     raeburn  8565: 	$result .= &endbodytag($args);
1.330     albertel 8566:     }
1.1080    raeburn  8567:     unless ($args->{'notbody'}) {
                   8568:         $result .= "\n</html>";
                   8569:     }
1.330     albertel 8570: 
1.315     albertel 8571:     if ($args->{'js_ready'}) {
1.317     albertel 8572: 	$result = &js_ready($result);
1.315     albertel 8573:     }
1.335     albertel 8574: 
1.320     albertel 8575:     if ($args->{'html_encode'}) {
                   8576: 	$result = &html_encode($result);
                   8577:     }
1.335     albertel 8578: 
1.315     albertel 8579:     return $result;
                   8580: }
                   8581: 
1.1034    www      8582: sub wishlist_window {
                   8583:     return(<<'ENDWISHLIST');
1.1046    raeburn  8584: <script type="text/javascript">
1.1034    www      8585: // <![CDATA[
                   8586: // <!-- BEGIN LON-CAPA Internal
                   8587: function set_wishlistlink(title, path) {
                   8588:     if (!title) {
                   8589:         title = document.title;
                   8590:         title = title.replace(/^LON-CAPA /,'');
                   8591:     }
1.1175    raeburn  8592:     title = encodeURIComponent(title);
1.1203    raeburn  8593:     title = title.replace("'","\\\'");
1.1034    www      8594:     if (!path) {
                   8595:         path = location.pathname;
                   8596:     }
1.1175    raeburn  8597:     path = encodeURIComponent(path);
1.1203    raeburn  8598:     path = path.replace("'","\\\'");
1.1034    www      8599:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8600:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8601: }
                   8602: // END LON-CAPA Internal -->
                   8603: // ]]>
                   8604: </script>
                   8605: ENDWISHLIST
                   8606: }
                   8607: 
1.1030    www      8608: sub modal_window {
                   8609:     return(<<'ENDMODAL');
1.1046    raeburn  8610: <script type="text/javascript">
1.1030    www      8611: // <![CDATA[
                   8612: // <!-- BEGIN LON-CAPA Internal
                   8613: var modalWindow = {
                   8614: 	parent:"body",
                   8615: 	windowId:null,
                   8616: 	content:null,
                   8617: 	width:null,
                   8618: 	height:null,
                   8619: 	close:function()
                   8620: 	{
                   8621: 	        $(".LCmodal-window").remove();
                   8622: 	        $(".LCmodal-overlay").remove();
                   8623: 	},
                   8624: 	open:function()
                   8625: 	{
                   8626: 		var modal = "";
                   8627: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8628: 		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;\">";
                   8629: 		modal += this.content;
                   8630: 		modal += "</div>";	
                   8631: 
                   8632: 		$(this.parent).append(modal);
                   8633: 
                   8634: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8635: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8636: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8637: 	}
                   8638: };
1.1140    raeburn  8639: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8640: 	{
1.1203    raeburn  8641:                 source = source.replace("'","&#39;");
1.1030    www      8642: 		modalWindow.windowId = "myModal";
                   8643: 		modalWindow.width = width;
                   8644: 		modalWindow.height = height;
1.1196    raeburn  8645: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8646: 		modalWindow.open();
1.1208    raeburn  8647: 	};
1.1030    www      8648: // END LON-CAPA Internal -->
                   8649: // ]]>
                   8650: </script>
                   8651: ENDMODAL
                   8652: }
                   8653: 
                   8654: sub modal_link {
1.1140    raeburn  8655:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8656:     unless ($width) { $width=480; }
                   8657:     unless ($height) { $height=400; }
1.1031    www      8658:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  8659:     unless ($transparency) { $transparency='true'; }
                   8660: 
1.1074    raeburn  8661:     my $target_attr;
                   8662:     if (defined($target)) {
                   8663:         $target_attr = 'target="'.$target.'"';
                   8664:     }
                   8665:     return <<"ENDLINK";
1.1140    raeburn  8666: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8667:            $linktext</a>
                   8668: ENDLINK
1.1030    www      8669: }
                   8670: 
1.1032    www      8671: sub modal_adhoc_script {
                   8672:     my ($funcname,$width,$height,$content)=@_;
                   8673:     return (<<ENDADHOC);
1.1046    raeburn  8674: <script type="text/javascript">
1.1032    www      8675: // <![CDATA[
                   8676:         var $funcname = function()
                   8677:         {
                   8678:                 modalWindow.windowId = "myModal";
                   8679:                 modalWindow.width = $width;
                   8680:                 modalWindow.height = $height;
                   8681:                 modalWindow.content = '$content';
                   8682:                 modalWindow.open();
                   8683:         };  
                   8684: // ]]>
                   8685: </script>
                   8686: ENDADHOC
                   8687: }
                   8688: 
1.1041    www      8689: sub modal_adhoc_inner {
                   8690:     my ($funcname,$width,$height,$content)=@_;
                   8691:     my $innerwidth=$width-20;
                   8692:     $content=&js_ready(
1.1140    raeburn  8693:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   8694:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8695:                  $content.
1.1041    www      8696:                  &end_scrollbox().
1.1140    raeburn  8697:                  &end_page()
1.1041    www      8698:              );
                   8699:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8700: }
                   8701: 
                   8702: sub modal_adhoc_window {
                   8703:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8704:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8705:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8706: }
                   8707: 
                   8708: sub modal_adhoc_launch {
                   8709:     my ($funcname,$width,$height,$content)=@_;
                   8710:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8711: <script type="text/javascript">
                   8712: // <![CDATA[
                   8713: $funcname();
                   8714: // ]]>
                   8715: </script>
                   8716: ENDLAUNCH
                   8717: }
                   8718: 
                   8719: sub modal_adhoc_close {
                   8720:     return (<<ENDCLOSE);
                   8721: <script type="text/javascript">
                   8722: // <![CDATA[
                   8723: modalWindow.close();
                   8724: // ]]>
                   8725: </script>
                   8726: ENDCLOSE
                   8727: }
                   8728: 
1.1038    www      8729: sub togglebox_script {
                   8730:    return(<<ENDTOGGLE);
                   8731: <script type="text/javascript"> 
                   8732: // <![CDATA[
                   8733: function LCtoggleDisplay(id,hidetext,showtext) {
                   8734:    link = document.getElementById(id + "link").childNodes[0];
                   8735:    with (document.getElementById(id).style) {
                   8736:       if (display == "none" ) {
                   8737:           display = "inline";
                   8738:           link.nodeValue = hidetext;
                   8739:         } else {
                   8740:           display = "none";
                   8741:           link.nodeValue = showtext;
                   8742:        }
                   8743:    }
                   8744: }
                   8745: // ]]>
                   8746: </script>
                   8747: ENDTOGGLE
                   8748: }
                   8749: 
1.1039    www      8750: sub start_togglebox {
                   8751:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8752:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8753:     unless ($showtext) { $showtext=&mt('show'); }
                   8754:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8755:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8756:     return &start_data_table().
                   8757:            &start_data_table_header_row().
                   8758:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8759:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8760:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8761:            &end_data_table_header_row().
                   8762:            '<tr id="'.$id.'" style="display:none""><td>';
                   8763: }
                   8764: 
                   8765: sub end_togglebox {
                   8766:     return '</td></tr>'.&end_data_table();
                   8767: }
                   8768: 
1.1041    www      8769: sub LCprogressbar_script {
1.1045    www      8770:    my ($id)=@_;
1.1041    www      8771:    return(<<ENDPROGRESS);
                   8772: <script type="text/javascript">
                   8773: // <![CDATA[
1.1045    www      8774: \$('#progressbar$id').progressbar({
1.1041    www      8775:   value: 0,
                   8776:   change: function(event, ui) {
                   8777:     var newVal = \$(this).progressbar('option', 'value');
                   8778:     \$('.pblabel', this).text(LCprogressTxt);
                   8779:   }
                   8780: });
                   8781: // ]]>
                   8782: </script>
                   8783: ENDPROGRESS
                   8784: }
                   8785: 
                   8786: sub LCprogressbarUpdate_script {
                   8787:    return(<<ENDPROGRESSUPDATE);
                   8788: <style type="text/css">
                   8789: .ui-progressbar { position:relative; }
                   8790: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8791: </style>
                   8792: <script type="text/javascript">
                   8793: // <![CDATA[
1.1045    www      8794: var LCprogressTxt='---';
                   8795: 
                   8796: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8797:    LCprogressTxt=progresstext;
1.1045    www      8798:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8799: }
                   8800: // ]]>
                   8801: </script>
                   8802: ENDPROGRESSUPDATE
                   8803: }
                   8804: 
1.1042    www      8805: my $LClastpercent;
1.1045    www      8806: my $LCidcnt;
                   8807: my $LCcurrentid;
1.1042    www      8808: 
1.1041    www      8809: sub LCprogressbar {
1.1042    www      8810:     my ($r)=(@_);
                   8811:     $LClastpercent=0;
1.1045    www      8812:     $LCidcnt++;
                   8813:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8814:     my $starting=&mt('Starting');
                   8815:     my $content=(<<ENDPROGBAR);
1.1045    www      8816:   <div id="progressbar$LCcurrentid">
1.1041    www      8817:     <span class="pblabel">$starting</span>
                   8818:   </div>
                   8819: ENDPROGBAR
1.1045    www      8820:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8821: }
                   8822: 
                   8823: sub LCprogressbarUpdate {
1.1042    www      8824:     my ($r,$val,$text)=@_;
                   8825:     unless ($val) { 
                   8826:        if ($LClastpercent) {
                   8827:            $val=$LClastpercent;
                   8828:        } else {
                   8829:            $val=0;
                   8830:        }
                   8831:     }
1.1041    www      8832:     if ($val<0) { $val=0; }
                   8833:     if ($val>100) { $val=0; }
1.1042    www      8834:     $LClastpercent=$val;
1.1041    www      8835:     unless ($text) { $text=$val.'%'; }
                   8836:     $text=&js_ready($text);
1.1044    www      8837:     &r_print($r,<<ENDUPDATE);
1.1041    www      8838: <script type="text/javascript">
                   8839: // <![CDATA[
1.1045    www      8840: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8841: // ]]>
                   8842: </script>
                   8843: ENDUPDATE
1.1035    www      8844: }
                   8845: 
1.1042    www      8846: sub LCprogressbarClose {
                   8847:     my ($r)=@_;
                   8848:     $LClastpercent=0;
1.1044    www      8849:     &r_print($r,<<ENDCLOSE);
1.1042    www      8850: <script type="text/javascript">
                   8851: // <![CDATA[
1.1045    www      8852: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8853: // ]]>
                   8854: </script>
                   8855: ENDCLOSE
1.1044    www      8856: }
                   8857: 
                   8858: sub r_print {
                   8859:     my ($r,$to_print)=@_;
                   8860:     if ($r) {
                   8861:       $r->print($to_print);
                   8862:       $r->rflush();
                   8863:     } else {
                   8864:       print($to_print);
                   8865:     }
1.1042    www      8866: }
                   8867: 
1.320     albertel 8868: sub html_encode {
                   8869:     my ($result) = @_;
                   8870: 
1.322     albertel 8871:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8872:     
                   8873:     return $result;
                   8874: }
1.1044    www      8875: 
1.317     albertel 8876: sub js_ready {
                   8877:     my ($result) = @_;
                   8878: 
1.323     albertel 8879:     $result =~ s/[\n\r]/ /xmsg;
                   8880:     $result =~ s/\\/\\\\/xmsg;
                   8881:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8882:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8883:     
                   8884:     return $result;
                   8885: }
                   8886: 
1.315     albertel 8887: sub validate_page {
                   8888:     if (  exists($env{'internal.start_page'})
1.316     albertel 8889: 	  &&     $env{'internal.start_page'} > 1) {
                   8890: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8891: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8892: 				 $ENV{'request.filename'});
1.315     albertel 8893:     }
                   8894:     if (  exists($env{'internal.end_page'})
1.316     albertel 8895: 	  &&     $env{'internal.end_page'} > 1) {
                   8896: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8897: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8898: 				 $env{'request.filename'});
1.315     albertel 8899:     }
                   8900:     if (     exists($env{'internal.start_page'})
                   8901: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8902: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8903: 				 $env{'request.filename'});
1.315     albertel 8904:     }
                   8905:     if (   ! exists($env{'internal.start_page'})
                   8906: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8907: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8908: 				 $env{'request.filename'});
1.315     albertel 8909:     }
1.306     albertel 8910: }
1.315     albertel 8911: 
1.996     www      8912: 
                   8913: sub start_scrollbox {
1.1140    raeburn  8914:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8915:     unless ($outerwidth) { $outerwidth='520px'; }
                   8916:     unless ($width) { $width='500px'; }
                   8917:     unless ($height) { $height='200px'; }
1.1075    raeburn  8918:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8919:     if ($id ne '') {
1.1140    raeburn  8920:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  8921:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8922:     }
1.1075    raeburn  8923:     if ($bgcolor ne '') {
                   8924:         $tdcol = "background-color: $bgcolor;";
                   8925:     }
1.1137    raeburn  8926:     my $nicescroll_js;
                   8927:     if ($env{'browser.mobile'}) {
1.1140    raeburn  8928:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8929:     }
                   8930:     return <<"END";
                   8931: $nicescroll_js
                   8932: 
                   8933: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   8934: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   8935: END
                   8936: }
                   8937: 
                   8938: sub end_scrollbox {
                   8939:     return '</div></td></tr></table>';
                   8940: }
                   8941: 
                   8942: sub nicescroll_javascript {
                   8943:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8944:     my %options;
                   8945:     if (ref($cursor) eq 'HASH') {
                   8946:         %options = %{$cursor};
                   8947:     }
                   8948:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8949:         $options{'railalign'} = 'left';
                   8950:     }
                   8951:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8952:         my $function  = &get_users_function();
                   8953:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  8954:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  8955:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  8956:         }
1.1140    raeburn  8957:     }
                   8958:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8959:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  8960:             $options{'cursoropacity'}='1.0';
                   8961:         }
1.1140    raeburn  8962:     } else {
                   8963:         $options{'cursoropacity'}='1.0';
                   8964:     }
                   8965:     if ($options{'cursorfixedheight'} eq 'none') {
                   8966:         delete($options{'cursorfixedheight'});
                   8967:     } else {
                   8968:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8969:     }
                   8970:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8971:         delete($options{'railoffset'});
                   8972:     }
                   8973:     my @niceoptions;
                   8974:     while (my($key,$value) = each(%options)) {
                   8975:         if ($value =~ /^\{.+\}$/) {
                   8976:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  8977:         } else {
1.1140    raeburn  8978:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  8979:         }
1.1140    raeburn  8980:     }
                   8981:     my $nicescroll_js = '
1.1137    raeburn  8982: $(document).ready(
1.1140    raeburn  8983:       function() {
                   8984:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8985:       }
1.1137    raeburn  8986: );
                   8987: ';
1.1140    raeburn  8988:     if ($framecheck) {
                   8989:         $nicescroll_js .= '
                   8990: function expand_div(caller) {
                   8991:     if (top === self) {
                   8992:         document.getElementById("'.$id.'").style.width = "auto";
                   8993:         document.getElementById("'.$id.'").style.height = "auto";
                   8994:     } else {
                   8995:         try {
                   8996:             if (parent.frames) {
                   8997:                 if (parent.frames.length > 1) {
                   8998:                     var framesrc = parent.frames[1].location.href;
                   8999:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9000:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9001:                         document.getElementById("'.$id.'").style.width = "auto";
                   9002:                         document.getElementById("'.$id.'").style.height = "auto";
                   9003:                     }
                   9004:                 }
                   9005:             }
                   9006:         } catch (e) {
                   9007:             return;
                   9008:         }
1.1137    raeburn  9009:     }
1.1140    raeburn  9010:     return;
1.996     www      9011: }
1.1140    raeburn  9012: ';
                   9013:     }
                   9014:     if ($needjsready) {
                   9015:         $nicescroll_js = '
                   9016: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9017:     } else {
                   9018:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9019:     }
                   9020:     return $nicescroll_js;
1.996     www      9021: }
                   9022: 
1.318     albertel 9023: sub simple_error_page {
1.1150    bisitz   9024:     my ($r,$title,$msg,$args) = @_;
1.1151    raeburn  9025:     if (ref($args) eq 'HASH') {
                   9026:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   9027:     } else {
                   9028:         $msg = &mt($msg);
                   9029:     }
1.1150    bisitz   9030: 
1.318     albertel 9031:     my $page =
                   9032: 	&Apache::loncommon::start_page($title).
1.1150    bisitz   9033: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9034: 	&Apache::loncommon::end_page();
                   9035:     if (ref($r)) {
                   9036: 	$r->print($page);
1.327     albertel 9037: 	return;
1.318     albertel 9038:     }
                   9039:     return $page;
                   9040: }
1.347     albertel 9041: 
                   9042: {
1.610     albertel 9043:     my @row_count;
1.961     onken    9044: 
                   9045:     sub start_data_table_count {
                   9046:         unshift(@row_count, 0);
                   9047:         return;
                   9048:     }
                   9049: 
                   9050:     sub end_data_table_count {
                   9051:         shift(@row_count);
                   9052:         return;
                   9053:     }
                   9054: 
1.347     albertel 9055:     sub start_data_table {
1.1018    raeburn  9056: 	my ($add_class,$id) = @_;
1.422     albertel 9057: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9058:         my $table_id;
                   9059:         if (defined($id)) {
                   9060:             $table_id = ' id="'.$id.'"';
                   9061:         }
1.961     onken    9062: 	&start_data_table_count();
1.1018    raeburn  9063: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9064:     }
                   9065: 
                   9066:     sub end_data_table {
1.961     onken    9067: 	&end_data_table_count();
1.389     albertel 9068: 	return '</table>'."\n";;
1.347     albertel 9069:     }
                   9070: 
                   9071:     sub start_data_table_row {
1.974     wenzelju 9072: 	my ($add_class, $id) = @_;
1.610     albertel 9073: 	$row_count[0]++;
                   9074: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9075: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9076:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9077:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9078:     }
1.471     banghart 9079:     
                   9080:     sub continue_data_table_row {
1.974     wenzelju 9081: 	my ($add_class, $id) = @_;
1.610     albertel 9082: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9083: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9084:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9085:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9086:     }
1.347     albertel 9087: 
                   9088:     sub end_data_table_row {
1.389     albertel 9089: 	return '</tr>'."\n";;
1.347     albertel 9090:     }
1.367     www      9091: 
1.421     albertel 9092:     sub start_data_table_empty_row {
1.707     bisitz   9093: #	$row_count[0]++;
1.421     albertel 9094: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9095:     }
                   9096: 
                   9097:     sub end_data_table_empty_row {
                   9098: 	return '</tr>'."\n";;
                   9099:     }
                   9100: 
1.367     www      9101:     sub start_data_table_header_row {
1.389     albertel 9102: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9103:     }
                   9104: 
                   9105:     sub end_data_table_header_row {
1.389     albertel 9106: 	return '</tr>'."\n";;
1.367     www      9107:     }
1.890     droeschl 9108: 
                   9109:     sub data_table_caption {
                   9110:         my $caption = shift;
                   9111:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9112:     }
1.347     albertel 9113: }
                   9114: 
1.548     albertel 9115: =pod
                   9116: 
                   9117: =item * &inhibit_menu_check($arg)
                   9118: 
                   9119: Checks for a inhibitmenu state and generates output to preserve it
                   9120: 
                   9121: Inputs:         $arg - can be any of
                   9122:                      - undef - in which case the return value is a string 
                   9123:                                to add  into arguments list of a uri
                   9124:                      - 'input' - in which case the return value is a HTML
                   9125:                                  <form> <input> field of type hidden to
                   9126:                                  preserve the value
                   9127:                      - a url - in which case the return value is the url with
                   9128:                                the neccesary cgi args added to preserve the
                   9129:                                inhibitmenu state
                   9130:                      - a ref to a url - no return value, but the string is
                   9131:                                         updated to include the neccessary cgi
                   9132:                                         args to preserve the inhibitmenu state
                   9133: 
                   9134: =cut
                   9135: 
                   9136: sub inhibit_menu_check {
                   9137:     my ($arg) = @_;
                   9138:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9139:     if ($arg eq 'input') {
                   9140: 	if ($env{'form.inhibitmenu'}) {
                   9141: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9142: 	} else {
                   9143: 	    return
                   9144: 	}
                   9145:     }
                   9146:     if ($env{'form.inhibitmenu'}) {
                   9147: 	if (ref($arg)) {
                   9148: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9149: 	} elsif ($arg eq '') {
                   9150: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9151: 	} else {
                   9152: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9153: 	}
                   9154:     }
                   9155:     if (!ref($arg)) {
                   9156: 	return $arg;
                   9157:     }
                   9158: }
                   9159: 
1.251     albertel 9160: ###############################################
1.182     matthew  9161: 
                   9162: =pod
                   9163: 
1.549     albertel 9164: =back
                   9165: 
                   9166: =head1 User Information Routines
                   9167: 
                   9168: =over 4
                   9169: 
1.405     albertel 9170: =item * &get_users_function()
1.182     matthew  9171: 
                   9172: Used by &bodytag to determine the current users primary role.
                   9173: Returns either 'student','coordinator','admin', or 'author'.
                   9174: 
                   9175: =cut
                   9176: 
                   9177: ###############################################
                   9178: sub get_users_function {
1.815     tempelho 9179:     my $function = 'norole';
1.818     tempelho 9180:     if ($env{'request.role'}=~/^(st)/) {
                   9181:         $function='student';
                   9182:     }
1.907     raeburn  9183:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9184:         $function='coordinator';
                   9185:     }
1.258     albertel 9186:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9187:         $function='admin';
                   9188:     }
1.826     bisitz   9189:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9190:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9191:         $function='author';
                   9192:     }
                   9193:     return $function;
1.54      www      9194: }
1.99      www      9195: 
                   9196: ###############################################
                   9197: 
1.233     raeburn  9198: =pod
                   9199: 
1.821     raeburn  9200: =item * &show_course()
                   9201: 
                   9202: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9203: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9204: 
                   9205: Inputs:
                   9206: None
                   9207: 
                   9208: Outputs:
                   9209: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9210: 
                   9211: =cut
                   9212: 
                   9213: ###############################################
                   9214: sub show_course {
                   9215:     my $course = !$env{'user.adv'};
                   9216:     if (!$env{'user.adv'}) {
                   9217:         foreach my $env (keys(%env)) {
                   9218:             next if ($env !~ m/^user\.priv\./);
                   9219:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9220:                 $course = 0;
                   9221:                 last;
                   9222:             }
                   9223:         }
                   9224:     }
                   9225:     return $course;
                   9226: }
                   9227: 
                   9228: ###############################################
                   9229: 
                   9230: =pod
                   9231: 
1.542     raeburn  9232: =item * &check_user_status()
1.274     raeburn  9233: 
                   9234: Determines current status of supplied role for a
                   9235: specific user. Roles can be active, previous or future.
                   9236: 
                   9237: Inputs: 
                   9238: user's domain, user's username, course's domain,
1.375     raeburn  9239: course's number, optional section ID.
1.274     raeburn  9240: 
                   9241: Outputs:
                   9242: role status: active, previous or future. 
                   9243: 
                   9244: =cut
                   9245: 
                   9246: sub check_user_status {
1.412     raeburn  9247:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9248:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  9249:     my @uroles = keys(%userinfo);
1.274     raeburn  9250:     my $srchstr;
                   9251:     my $active_chk = 'none';
1.412     raeburn  9252:     my $now = time;
1.274     raeburn  9253:     if (@uroles > 0) {
1.908     raeburn  9254:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9255:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9256:         } else {
1.412     raeburn  9257:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9258:         }
                   9259:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9260:             my $role_end = 0;
                   9261:             my $role_start = 0;
                   9262:             $active_chk = 'active';
1.412     raeburn  9263:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9264:                 $role_end = $1;
                   9265:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9266:                     $role_start = $1;
1.274     raeburn  9267:                 }
                   9268:             }
                   9269:             if ($role_start > 0) {
1.412     raeburn  9270:                 if ($now < $role_start) {
1.274     raeburn  9271:                     $active_chk = 'future';
                   9272:                 }
                   9273:             }
                   9274:             if ($role_end > 0) {
1.412     raeburn  9275:                 if ($now > $role_end) {
1.274     raeburn  9276:                     $active_chk = 'previous';
                   9277:                 }
                   9278:             }
                   9279:         }
                   9280:     }
                   9281:     return $active_chk;
                   9282: }
                   9283: 
                   9284: ###############################################
                   9285: 
                   9286: =pod
                   9287: 
1.405     albertel 9288: =item * &get_sections()
1.233     raeburn  9289: 
                   9290: Determines all the sections for a course including
                   9291: sections with students and sections containing other roles.
1.419     raeburn  9292: Incoming parameters: 
                   9293: 
                   9294: 1. domain
                   9295: 2. course number 
                   9296: 3. reference to array containing roles for which sections should 
                   9297: be gathered (optional).
                   9298: 4. reference to array containing status types for which sections 
                   9299: should be gathered (optional).
                   9300: 
                   9301: If the third argument is undefined, sections are gathered for any role. 
                   9302: If the fourth argument is undefined, sections are gathered for any status.
                   9303: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9304:  
1.374     raeburn  9305: Returns section hash (keys are section IDs, values are
                   9306: number of users in each section), subject to the
1.419     raeburn  9307: optional roles filter, optional status filter 
1.233     raeburn  9308: 
                   9309: =cut
                   9310: 
                   9311: ###############################################
                   9312: sub get_sections {
1.419     raeburn  9313:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9314:     if (!defined($cdom) || !defined($cnum)) {
                   9315:         my $cid =  $env{'request.course.id'};
                   9316: 
                   9317: 	return if (!defined($cid));
                   9318: 
                   9319:         $cdom = $env{'course.'.$cid.'.domain'};
                   9320:         $cnum = $env{'course.'.$cid.'.num'};
                   9321:     }
                   9322: 
                   9323:     my %sectioncount;
1.419     raeburn  9324:     my $now = time;
1.240     albertel 9325: 
1.1118    raeburn  9326:     my $check_students = 1;
                   9327:     my $only_students = 0;
                   9328:     if (ref($possible_roles) eq 'ARRAY') {
                   9329:         if (grep(/^st$/,@{$possible_roles})) {
                   9330:             if (@{$possible_roles} == 1) {
                   9331:                 $only_students = 1;
                   9332:             }
                   9333:         } else {
                   9334:             $check_students = 0;
                   9335:         }
                   9336:     }
                   9337: 
                   9338:     if ($check_students) { 
1.276     albertel 9339: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9340: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9341: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9342:         my $start_index = &Apache::loncoursedata::CL_START();
                   9343:         my $end_index = &Apache::loncoursedata::CL_END();
                   9344:         my $status;
1.366     albertel 9345: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9346: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9347: 				                     $data->[$status_index],
                   9348:                                                      $data->[$start_index],
                   9349:                                                      $data->[$end_index]);
                   9350:             if ($stu_status eq 'Active') {
                   9351:                 $status = 'active';
                   9352:             } elsif ($end < $now) {
                   9353:                 $status = 'previous';
                   9354:             } elsif ($start > $now) {
                   9355:                 $status = 'future';
                   9356:             } 
                   9357: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9358:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9359:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9360: 		    $sectioncount{$section}++;
                   9361:                 }
1.240     albertel 9362: 	    }
                   9363: 	}
                   9364:     }
1.1118    raeburn  9365:     if ($only_students) {
                   9366:         return %sectioncount;
                   9367:     }
1.240     albertel 9368:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9369:     foreach my $user (sort(keys(%courseroles))) {
                   9370: 	if ($user !~ /^(\w{2})/) { next; }
                   9371: 	my ($role) = ($user =~ /^(\w{2})/);
                   9372: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9373: 	my ($section,$status);
1.240     albertel 9374: 	if ($role eq 'cr' &&
                   9375: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9376: 	    $section=$1;
                   9377: 	}
                   9378: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9379: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9380:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9381:         if ($end == -1 && $start == -1) {
                   9382:             next; #deleted role
                   9383:         }
                   9384:         if (!defined($possible_status)) { 
                   9385:             $sectioncount{$section}++;
                   9386:         } else {
                   9387:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9388:                 $status = 'active';
                   9389:             } elsif ($end < $now) {
                   9390:                 $status = 'future';
                   9391:             } elsif ($start > $now) {
                   9392:                 $status = 'previous';
                   9393:             }
                   9394:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9395:                 $sectioncount{$section}++;
                   9396:             }
                   9397:         }
1.233     raeburn  9398:     }
1.366     albertel 9399:     return %sectioncount;
1.233     raeburn  9400: }
                   9401: 
1.274     raeburn  9402: ###############################################
1.294     raeburn  9403: 
                   9404: =pod
1.405     albertel 9405: 
                   9406: =item * &get_course_users()
                   9407: 
1.275     raeburn  9408: Retrieves usernames:domains for users in the specified course
                   9409: with specific role(s), and access status. 
                   9410: 
                   9411: Incoming parameters:
1.277     albertel 9412: 1. course domain
                   9413: 2. course number
                   9414: 3. access status: users must have - either active, 
1.275     raeburn  9415: previous, future, or all.
1.277     albertel 9416: 4. reference to array of permissible roles
1.288     raeburn  9417: 5. reference to array of section restrictions (optional)
                   9418: 6. reference to results object (hash of hashes).
                   9419: 7. reference to optional userdata hash
1.609     raeburn  9420: 8. reference to optional statushash
1.630     raeburn  9421: 9. flag if privileged users (except those set to unhide in
                   9422:    course settings) should be excluded    
1.609     raeburn  9423: Keys of top level results hash are roles.
1.275     raeburn  9424: Keys of inner hashes are username:domain, with 
                   9425: values set to access type.
1.288     raeburn  9426: Optional userdata hash returns an array with arguments in the 
                   9427: same order as loncoursedata::get_classlist() for student data.
                   9428: 
1.609     raeburn  9429: Optional statushash returns
                   9430: 
1.288     raeburn  9431: Entries for end, start, section and status are blank because
                   9432: of the possibility of multiple values for non-student roles.
                   9433: 
1.275     raeburn  9434: =cut
1.405     albertel 9435: 
1.275     raeburn  9436: ###############################################
1.405     albertel 9437: 
1.275     raeburn  9438: sub get_course_users {
1.630     raeburn  9439:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9440:     my %idx = ();
1.419     raeburn  9441:     my %seclists;
1.288     raeburn  9442: 
                   9443:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9444:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9445:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9446:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9447:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9448:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9449:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9450:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9451: 
1.290     albertel 9452:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9453:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9454:         my $now = time;
1.277     albertel 9455:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9456:             my $match = 0;
1.412     raeburn  9457:             my $secmatch = 0;
1.419     raeburn  9458:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9459:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9460:             if ($section eq '') {
                   9461:                 $section = 'none';
                   9462:             }
1.291     albertel 9463:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9464:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9465:                     $secmatch = 1;
                   9466:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9467:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9468:                         $secmatch = 1;
                   9469:                     }
                   9470:                 } else {  
1.419     raeburn  9471: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9472: 		        $secmatch = 1;
                   9473:                     }
1.290     albertel 9474: 		}
1.412     raeburn  9475:                 if (!$secmatch) {
                   9476:                     next;
                   9477:                 }
1.419     raeburn  9478:             }
1.275     raeburn  9479:             if (defined($$types{'active'})) {
1.288     raeburn  9480:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9481:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9482:                     $match = 1;
1.275     raeburn  9483:                 }
                   9484:             }
                   9485:             if (defined($$types{'previous'})) {
1.609     raeburn  9486:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9487:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9488:                     $match = 1;
1.275     raeburn  9489:                 }
                   9490:             }
                   9491:             if (defined($$types{'future'})) {
1.609     raeburn  9492:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9493:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9494:                     $match = 1;
1.275     raeburn  9495:                 }
                   9496:             }
1.609     raeburn  9497:             if ($match) {
                   9498:                 push(@{$seclists{$student}},$section);
                   9499:                 if (ref($userdata) eq 'HASH') {
                   9500:                     $$userdata{$student} = $$classlist{$student};
                   9501:                 }
                   9502:                 if (ref($statushash) eq 'HASH') {
                   9503:                     $statushash->{$student}{'st'}{$section} = $status;
                   9504:                 }
1.288     raeburn  9505:             }
1.275     raeburn  9506:         }
                   9507:     }
1.412     raeburn  9508:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9509:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9510:         my $now = time;
1.609     raeburn  9511:         my %displaystatus = ( previous => 'Expired',
                   9512:                               active   => 'Active',
                   9513:                               future   => 'Future',
                   9514:                             );
1.1121    raeburn  9515:         my (%nothide,@possdoms);
1.630     raeburn  9516:         if ($hidepriv) {
                   9517:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9518:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9519:                 if ($user !~ /:/) {
                   9520:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9521:                 } else {
                   9522:                     $nothide{$user} = 1;
                   9523:                 }
                   9524:             }
1.1121    raeburn  9525:             my @possdoms = ($cdom);
                   9526:             if ($coursehash{'checkforpriv'}) {
                   9527:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9528:             }
1.630     raeburn  9529:         }
1.439     raeburn  9530:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9531:             my $match = 0;
1.412     raeburn  9532:             my $secmatch = 0;
1.439     raeburn  9533:             my $status;
1.412     raeburn  9534:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9535:             $user =~ s/:$//;
1.439     raeburn  9536:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9537:             if ($end == -1 || $start == -1) {
                   9538:                 next;
                   9539:             }
                   9540:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9541:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9542:                 my ($uname,$udom) = split(/:/,$user);
                   9543:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9544:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9545:                         $secmatch = 1;
                   9546:                     } elsif ($usec eq '') {
1.420     albertel 9547:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9548:                             $secmatch = 1;
                   9549:                         }
                   9550:                     } else {
                   9551:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9552:                             $secmatch = 1;
                   9553:                         }
                   9554:                     }
                   9555:                     if (!$secmatch) {
                   9556:                         next;
                   9557:                     }
1.288     raeburn  9558:                 }
1.419     raeburn  9559:                 if ($usec eq '') {
                   9560:                     $usec = 'none';
                   9561:                 }
1.275     raeburn  9562:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9563:                     if ($hidepriv) {
1.1121    raeburn  9564:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9565:                             (!$nothide{$uname.':'.$udom})) {
                   9566:                             next;
                   9567:                         }
                   9568:                     }
1.503     raeburn  9569:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9570:                         $status = 'previous';
                   9571:                     } elsif ($start > $now) {
                   9572:                         $status = 'future';
                   9573:                     } else {
                   9574:                         $status = 'active';
                   9575:                     }
1.277     albertel 9576:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9577:                         if ($status eq $type) {
1.420     albertel 9578:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9579:                                 push(@{$$users{$role}{$user}},$type);
                   9580:                             }
1.288     raeburn  9581:                             $match = 1;
                   9582:                         }
                   9583:                     }
1.419     raeburn  9584:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9585:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9586: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9587:                         }
1.420     albertel 9588:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9589:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9590:                         }
1.609     raeburn  9591:                         if (ref($statushash) eq 'HASH') {
                   9592:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9593:                         }
1.275     raeburn  9594:                     }
                   9595:                 }
                   9596:             }
                   9597:         }
1.290     albertel 9598:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9599:             if ((defined($cdom)) && (defined($cnum))) {
                   9600:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9601:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9602:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9603:                     next if ($owner eq '');
                   9604:                     my ($ownername,$ownerdom);
                   9605:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9606:                         $ownername = $1;
                   9607:                         $ownerdom = $2;
                   9608:                     } else {
                   9609:                         $ownername = $owner;
                   9610:                         $ownerdom = $cdom;
                   9611:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9612:                     }
                   9613:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9614:                     if (defined($userdata) && 
1.609     raeburn  9615: 			!exists($$userdata{$owner})) {
                   9616: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9617:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9618:                             push(@{$seclists{$owner}},'none');
                   9619:                         }
                   9620:                         if (ref($statushash) eq 'HASH') {
                   9621:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9622:                         }
1.290     albertel 9623: 		    }
1.279     raeburn  9624:                 }
                   9625:             }
                   9626:         }
1.419     raeburn  9627:         foreach my $user (keys(%seclists)) {
                   9628:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9629:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9630:         }
1.275     raeburn  9631:     }
                   9632:     return;
                   9633: }
                   9634: 
1.288     raeburn  9635: sub get_user_info {
                   9636:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9637:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9638: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9639:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9640:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9641:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9642:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9643:     return;
                   9644: }
1.275     raeburn  9645: 
1.472     raeburn  9646: ###############################################
                   9647: 
                   9648: =pod
                   9649: 
                   9650: =item * &get_user_quota()
                   9651: 
1.1134    raeburn  9652: Retrieves quota assigned for storage of user files.
                   9653: Default is to report quota for portfolio files.
1.472     raeburn  9654: 
                   9655: Incoming parameters:
                   9656: 1. user's username
                   9657: 2. user's domain
1.1134    raeburn  9658: 3. quota name - portfolio, author, or course
1.1136    raeburn  9659:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  9660: 4. crstype - official, unofficial, textbook, placement or community, 
                   9661:    if quota name is course
1.472     raeburn  9662: 
                   9663: Returns:
1.1163    raeburn  9664: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9665: 2. (Optional) Type of setting: custom or default
                   9666:    (individually assigned or default for user's 
                   9667:    institutional status).
                   9668: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9669:    or student - types as defined in localenroll::inst_usertypes 
                   9670:    for user's domain, which determines default quota for user.
                   9671: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9672: 
                   9673: If a value has been stored in the user's environment, 
1.536     raeburn  9674: it will return that, otherwise it returns the maximal default
1.1134    raeburn  9675: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9676: 
                   9677: =cut
                   9678: 
                   9679: ###############################################
                   9680: 
                   9681: 
                   9682: sub get_user_quota {
1.1136    raeburn  9683:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9684:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9685:     if (!defined($udom)) {
                   9686:         $udom = $env{'user.domain'};
                   9687:     }
                   9688:     if (!defined($uname)) {
                   9689:         $uname = $env{'user.name'};
                   9690:     }
                   9691:     if (($udom eq '' || $uname eq '') ||
                   9692:         ($udom eq 'public') && ($uname eq 'public')) {
                   9693:         $quota = 0;
1.536     raeburn  9694:         $quotatype = 'default';
                   9695:         $defquota = 0; 
1.472     raeburn  9696:     } else {
1.536     raeburn  9697:         my $inststatus;
1.1134    raeburn  9698:         if ($quotaname eq 'course') {
                   9699:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9700:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9701:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9702:             } else {
                   9703:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9704:                 $quota = $cenv{'internal.uploadquota'};
                   9705:             }
1.536     raeburn  9706:         } else {
1.1134    raeburn  9707:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9708:                 if ($quotaname eq 'author') {
                   9709:                     $quota = $env{'environment.authorquota'};
                   9710:                 } else {
                   9711:                     $quota = $env{'environment.portfolioquota'};
                   9712:                 }
                   9713:                 $inststatus = $env{'environment.inststatus'};
                   9714:             } else {
                   9715:                 my %userenv = 
                   9716:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9717:                                          'authorquota','inststatus'],$udom,$uname);
                   9718:                 my ($tmp) = keys(%userenv);
                   9719:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9720:                     if ($quotaname eq 'author') {
                   9721:                         $quota = $userenv{'authorquota'};
                   9722:                     } else {
                   9723:                         $quota = $userenv{'portfolioquota'};
                   9724:                     }
                   9725:                     $inststatus = $userenv{'inststatus'};
                   9726:                 } else {
                   9727:                     undef(%userenv);
                   9728:                 }
                   9729:             }
                   9730:         }
                   9731:         if ($quota eq '' || wantarray) {
                   9732:             if ($quotaname eq 'course') {
                   9733:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  9734:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  9735:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   9736:                     ($crstype eq 'placement')) { 
1.1136    raeburn  9737:                     $defquota = $domdefs{$crstype.'quota'};
                   9738:                 }
                   9739:                 if ($defquota eq '') {
                   9740:                     $defquota = 500;
                   9741:                 }
1.1134    raeburn  9742:             } else {
                   9743:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9744:             }
                   9745:             if ($quota eq '') {
                   9746:                 $quota = $defquota;
                   9747:                 $quotatype = 'default';
                   9748:             } else {
                   9749:                 $quotatype = 'custom';
                   9750:             }
1.472     raeburn  9751:         }
                   9752:     }
1.536     raeburn  9753:     if (wantarray) {
                   9754:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9755:     } else {
                   9756:         return $quota;
                   9757:     }
1.472     raeburn  9758: }
                   9759: 
                   9760: ###############################################
                   9761: 
                   9762: =pod
                   9763: 
                   9764: =item * &default_quota()
                   9765: 
1.536     raeburn  9766: Retrieves default quota assigned for storage of user portfolio files,
                   9767: given an (optional) user's institutional status.
1.472     raeburn  9768: 
                   9769: Incoming parameters:
1.1142    raeburn  9770: 
1.472     raeburn  9771: 1. domain
1.536     raeburn  9772: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9773:    status types (e.g., faculty, staff, student etc.)
                   9774:    which apply to the user for whom the default is being retrieved.
                   9775:    If the institutional status string in undefined, the domain
1.1134    raeburn  9776:    default quota will be returned.
                   9777: 3.  quota name - portfolio, author, or course
                   9778:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9779: 
                   9780: Returns:
1.1142    raeburn  9781: 
1.1163    raeburn  9782: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9783: 2. (Optional) institutional type which determined the value of the
                   9784:    default quota.
1.472     raeburn  9785: 
                   9786: If a value has been stored in the domain's configuration db,
                   9787: it will return that, otherwise it returns 20 (for backwards 
                   9788: compatibility with domains which have not set up a configuration
1.1163    raeburn  9789: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9790: 
1.536     raeburn  9791: If the user's status includes multiple types (e.g., staff and student),
                   9792: the largest default quota which applies to the user determines the
                   9793: default quota returned.
                   9794: 
1.472     raeburn  9795: =cut
                   9796: 
                   9797: ###############################################
                   9798: 
                   9799: 
                   9800: sub default_quota {
1.1134    raeburn  9801:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9802:     my ($defquota,$settingstatus);
                   9803:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9804:                                             ['quotas'],$udom);
1.1134    raeburn  9805:     my $key = 'defaultquota';
                   9806:     if ($quotaname eq 'author') {
                   9807:         $key = 'authorquota';
                   9808:     }
1.622     raeburn  9809:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9810:         if ($inststatus ne '') {
1.765     raeburn  9811:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9812:             foreach my $item (@statuses) {
1.1134    raeburn  9813:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9814:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9815:                         if ($defquota eq '') {
1.1134    raeburn  9816:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9817:                             $settingstatus = $item;
1.1134    raeburn  9818:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9819:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9820:                             $settingstatus = $item;
                   9821:                         }
                   9822:                     }
1.1134    raeburn  9823:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9824:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9825:                         if ($defquota eq '') {
                   9826:                             $defquota = $quotahash{'quotas'}{$item};
                   9827:                             $settingstatus = $item;
                   9828:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9829:                             $defquota = $quotahash{'quotas'}{$item};
                   9830:                             $settingstatus = $item;
                   9831:                         }
1.536     raeburn  9832:                     }
                   9833:                 }
                   9834:             }
                   9835:         }
                   9836:         if ($defquota eq '') {
1.1134    raeburn  9837:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9838:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9839:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9840:                 $defquota = $quotahash{'quotas'}{'default'};
                   9841:             }
1.536     raeburn  9842:             $settingstatus = 'default';
1.1139    raeburn  9843:             if ($defquota eq '') {
                   9844:                 if ($quotaname eq 'author') {
                   9845:                     $defquota = 500;
                   9846:                 }
                   9847:             }
1.536     raeburn  9848:         }
                   9849:     } else {
                   9850:         $settingstatus = 'default';
1.1134    raeburn  9851:         if ($quotaname eq 'author') {
                   9852:             $defquota = 500;
                   9853:         } else {
                   9854:             $defquota = 20;
                   9855:         }
1.536     raeburn  9856:     }
                   9857:     if (wantarray) {
                   9858:         return ($defquota,$settingstatus);
1.472     raeburn  9859:     } else {
1.536     raeburn  9860:         return $defquota;
1.472     raeburn  9861:     }
                   9862: }
                   9863: 
1.1135    raeburn  9864: ###############################################
                   9865: 
                   9866: =pod
                   9867: 
1.1136    raeburn  9868: =item * &excess_filesize_warning()
1.1135    raeburn  9869: 
                   9870: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  9871: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  9872: space to be exceeded.
1.1136    raeburn  9873: 
                   9874: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  9875: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  9876: 
1.1165    raeburn  9877: Inputs: 7 
1.1136    raeburn  9878: 1. username or coursenum
1.1135    raeburn  9879: 2. domain
1.1136    raeburn  9880: 3. context ('author' or 'course')
1.1135    raeburn  9881: 4. filename of file for which action is being requested
                   9882: 5. filesize (kB) of file
                   9883: 6. action being taken: copy or upload.
1.1237    raeburn  9884: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  9885: 
                   9886: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  9887:          otherwise return null.
                   9888: 
                   9889: =back
1.1135    raeburn  9890: 
                   9891: =cut
                   9892: 
1.1136    raeburn  9893: sub excess_filesize_warning {
1.1165    raeburn  9894:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  9895:     my $current_disk_usage = 0;
1.1165    raeburn  9896:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  9897:     if ($context eq 'author') {
                   9898:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9899:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9900:     } else {
                   9901:         foreach my $subdir ('docs','supplemental') {
                   9902:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9903:         }
                   9904:     }
1.1135    raeburn  9905:     $disk_quota = int($disk_quota * 1000);
                   9906:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   9907:         return '<p class="LC_warning">'.
1.1135    raeburn  9908:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   9909:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9910:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  9911:                             $disk_quota,$current_disk_usage).
                   9912:                '</p>';
                   9913:     }
                   9914:     return;
                   9915: }
                   9916: 
                   9917: ###############################################
                   9918: 
                   9919: 
1.1136    raeburn  9920: 
                   9921: 
1.384     raeburn  9922: sub get_secgrprole_info {
                   9923:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9924:     my %sections_count = &get_sections($cdom,$cnum);
                   9925:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9926:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9927:     my @groups = sort(keys(%curr_groups));
                   9928:     my $allroles = [];
                   9929:     my $rolehash;
                   9930:     my $accesshash = {
                   9931:                      active => 'Currently has access',
                   9932:                      future => 'Will have future access',
                   9933:                      previous => 'Previously had access',
                   9934:                   };
                   9935:     if ($needroles) {
                   9936:         $rolehash = {'all' => 'all'};
1.385     albertel 9937:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9938: 	if (&Apache::lonnet::error(%user_roles)) {
                   9939: 	    undef(%user_roles);
                   9940: 	}
                   9941:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9942:             my ($role)=split(/\:/,$item,2);
                   9943:             if ($role eq 'cr') { next; }
                   9944:             if ($role =~ /^cr/) {
                   9945:                 $$rolehash{$role} = (split('/',$role))[3];
                   9946:             } else {
                   9947:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9948:             }
                   9949:         }
                   9950:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9951:             push(@{$allroles},$key);
                   9952:         }
                   9953:         push (@{$allroles},'st');
                   9954:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9955:     }
                   9956:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9957: }
                   9958: 
1.555     raeburn  9959: sub user_picker {
1.994     raeburn  9960:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  9961:     my $currdom = $dom;
1.1253  ! raeburn  9962:     my @alldoms = &Apache::lonnet::all_domains();
        !          9963:     if (@alldoms == 1) {
        !          9964:         my %domsrch = &Apache::lonnet::get_dom('configuration',
        !          9965:                                                ['directorysrch'],$alldoms[0]);
        !          9966:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
        !          9967:         my $showdom = $domdesc;
        !          9968:         if ($showdom eq '') {
        !          9969:             $showdom = $dom;
        !          9970:         }
        !          9971:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
        !          9972:             if ((!$domsrch{'directorysrch'}{'available'}) &&
        !          9973:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
        !          9974:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
        !          9975:             }
        !          9976:         }
        !          9977:     }
1.555     raeburn  9978:     my %curr_selected = (
                   9979:                         srchin => 'dom',
1.580     raeburn  9980:                         srchby => 'lastname',
1.555     raeburn  9981:                       );
                   9982:     my $srchterm;
1.625     raeburn  9983:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9984:         if ($srch->{'srchby'} ne '') {
                   9985:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9986:         }
                   9987:         if ($srch->{'srchin'} ne '') {
                   9988:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9989:         }
                   9990:         if ($srch->{'srchtype'} ne '') {
                   9991:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9992:         }
                   9993:         if ($srch->{'srchdomain'} ne '') {
                   9994:             $currdom = $srch->{'srchdomain'};
                   9995:         }
                   9996:         $srchterm = $srch->{'srchterm'};
                   9997:     }
1.1222    damieng  9998:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9999:                     'usr'       => 'Search criteria',
1.563     raeburn  10000:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10001:                     'uname'     => 'username',
                   10002:                     'lastname'  => 'last name',
1.555     raeburn  10003:                     'lastfirst' => 'last name, first name',
1.558     albertel 10004:                     'crs'       => 'in this course',
1.576     raeburn  10005:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10006:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10007:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10008:                     'exact'     => 'is',
                   10009:                     'contains'  => 'contains',
1.569     raeburn  10010:                     'begins'    => 'begins with',
1.1222    damieng  10011:                                        );
                   10012:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10013:                     'youm'      => "You must include some text to search for.",
                   10014:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10015:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10016:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10017:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10018:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10019:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10020:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10021:                                        );
1.1222    damieng  10022:     &html_escape(\%html_lt);
                   10023:     &js_escape(\%js_lt);
1.563     raeburn  10024:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   10025:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10026: 
                   10027:     my @srchins = ('crs','dom','alc','instd');
                   10028: 
                   10029:     foreach my $option (@srchins) {
                   10030:         # FIXME 'alc' option unavailable until 
                   10031:         #       loncreateuser::print_user_query_page()
                   10032:         #       has been completed.
                   10033:         next if ($option eq 'alc');
1.880     raeburn  10034:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10035:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  10036:         if ($curr_selected{'srchin'} eq $option) {
                   10037:             $srchinsel .= ' 
1.1222    damieng  10038:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10039:         } else {
                   10040:             $srchinsel .= '
1.1222    damieng  10041:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10042:         }
1.555     raeburn  10043:     }
1.563     raeburn  10044:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10045: 
                   10046:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10047:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10048:         if ($curr_selected{'srchby'} eq $option) {
                   10049:             $srchbysel .= '
1.1222    damieng  10050:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10051:         } else {
                   10052:             $srchbysel .= '
1.1222    damieng  10053:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10054:          }
                   10055:     }
                   10056:     $srchbysel .= "\n  </select>\n";
                   10057: 
                   10058:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10059:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10060:         if ($curr_selected{'srchtype'} eq $option) {
                   10061:             $srchtypesel .= '
1.1222    damieng  10062:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10063:         } else {
                   10064:             $srchtypesel .= '
1.1222    damieng  10065:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10066:         }
                   10067:     }
                   10068:     $srchtypesel .= "\n  </select>\n";
                   10069: 
1.558     albertel 10070:     my ($newuserscript,$new_user_create);
1.994     raeburn  10071:     my $context_dom = $env{'request.role.domain'};
                   10072:     if ($context eq 'requestcrs') {
                   10073:         if ($env{'form.coursedom'} ne '') { 
                   10074:             $context_dom = $env{'form.coursedom'};
                   10075:         }
                   10076:     }
1.556     raeburn  10077:     if ($forcenewuser) {
1.576     raeburn  10078:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10079:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10080:                 if ($cancreate) {
                   10081:                     $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>';
                   10082:                 } else {
1.799     bisitz   10083:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10084:                     my %usertypetext = (
                   10085:                         official   => 'institutional',
                   10086:                         unofficial => 'non-institutional',
                   10087:                     );
1.799     bisitz   10088:                     $new_user_create = '<p class="LC_warning">'
                   10089:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10090:                                       .' '
                   10091:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10092:                                           ,'<a href="'.$helplink.'">','</a>')
                   10093:                                       .'</p><br />';
1.627     raeburn  10094:                 }
1.576     raeburn  10095:             }
                   10096:         }
                   10097: 
1.556     raeburn  10098:         $newuserscript = <<"ENDSCRIPT";
                   10099: 
1.570     raeburn  10100: function setSearch(createnew,callingForm) {
1.556     raeburn  10101:     if (createnew == 1) {
1.570     raeburn  10102:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10103:             if (callingForm.srchby.options[i].value == 'uname') {
                   10104:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10105:             }
                   10106:         }
1.570     raeburn  10107:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10108:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10109: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10110:             }
                   10111:         }
1.570     raeburn  10112:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10113:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10114:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10115:             }
                   10116:         }
1.570     raeburn  10117:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10118:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10119:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10120:             }
                   10121:         }
                   10122:     }
                   10123: }
                   10124: ENDSCRIPT
1.558     albertel 10125: 
1.556     raeburn  10126:     }
                   10127: 
1.555     raeburn  10128:     my $output = <<"END_BLOCK";
1.556     raeburn  10129: <script type="text/javascript">
1.824     bisitz   10130: // <![CDATA[
1.570     raeburn  10131: function validateEntry(callingForm) {
1.558     albertel 10132: 
1.556     raeburn  10133:     var checkok = 1;
1.558     albertel 10134:     var srchin;
1.570     raeburn  10135:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10136: 	if ( callingForm.srchin[i].checked ) {
                   10137: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10138: 	}
                   10139:     }
                   10140: 
1.570     raeburn  10141:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10142:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10143:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10144:     var srchterm =  callingForm.srchterm.value;
                   10145:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10146:     var msg = "";
                   10147: 
                   10148:     if (srchterm == "") {
                   10149:         checkok = 0;
1.1222    damieng  10150:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10151:     }
                   10152: 
1.569     raeburn  10153:     if (srchtype== 'begins') {
                   10154:         if (srchterm.length < 2) {
                   10155:             checkok = 0;
1.1222    damieng  10156:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10157:         }
                   10158:     }
                   10159: 
1.556     raeburn  10160:     if (srchtype== 'contains') {
                   10161:         if (srchterm.length < 3) {
                   10162:             checkok = 0;
1.1222    damieng  10163:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10164:         }
                   10165:     }
                   10166:     if (srchin == 'instd') {
                   10167:         if (srchdomain == '') {
                   10168:             checkok = 0;
1.1222    damieng  10169:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10170:         }
                   10171:     }
                   10172:     if (srchin == 'dom') {
                   10173:         if (srchdomain == '') {
                   10174:             checkok = 0;
1.1222    damieng  10175:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10176:         }
                   10177:     }
                   10178:     if (srchby == 'lastfirst') {
                   10179:         if (srchterm.indexOf(",") == -1) {
                   10180:             checkok = 0;
1.1222    damieng  10181:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10182:         }
                   10183:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10184:             checkok = 0;
1.1222    damieng  10185:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10186:         }
                   10187:     }
                   10188:     if (checkok == 0) {
1.1222    damieng  10189:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10190:         return;
                   10191:     }
                   10192:     if (checkok == 1) {
1.570     raeburn  10193:         callingForm.submit();
1.556     raeburn  10194:     }
                   10195: }
                   10196: 
                   10197: $newuserscript
                   10198: 
1.824     bisitz   10199: // ]]>
1.556     raeburn  10200: </script>
1.558     albertel 10201: 
                   10202: $new_user_create
                   10203: 
1.555     raeburn  10204: END_BLOCK
1.558     albertel 10205: 
1.876     raeburn  10206:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  10207:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10208:                $domform.
                   10209:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  10210:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10211:                $srchbysel.
                   10212:                $srchtypesel. 
                   10213:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10214:                $srchinsel.
                   10215:                &Apache::lonhtmlcommon::row_closure(1). 
                   10216:                &Apache::lonhtmlcommon::end_pick_box().
                   10217:                '<br />';
1.1253  ! raeburn  10218:     return ($output,1);
1.555     raeburn  10219: }
                   10220: 
1.612     raeburn  10221: sub user_rule_check {
1.615     raeburn  10222:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  10223:     my ($response,%inst_response);
1.612     raeburn  10224:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  10225:         if (keys(%{$usershash}) > 1) {
                   10226:             my (%by_username,%by_id,%userdoms);
                   10227:             my $checkid; 
                   10228:             if (ref($checks) eq 'HASH') {
                   10229:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10230:                     $checkid = 1;
                   10231:                 }
                   10232:             }
                   10233:             foreach my $user (keys(%{$usershash})) {
                   10234:                 my ($uname,$udom) = split(/:/,$user);
                   10235:                 if ($checkid) {
                   10236:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10237:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  10238:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  10239:                             $userdoms{$udom} = 1;
1.1227    raeburn  10240:                             if (ref($inst_results) eq 'HASH') {
                   10241:                                 $inst_results->{$uname.':'.$udom} = {};
                   10242:                             }
1.1226    raeburn  10243:                         }
                   10244:                     }
                   10245:                 } else {
                   10246:                     $by_username{$udom}{$uname} = 1;
                   10247:                     $userdoms{$udom} = 1;
1.1227    raeburn  10248:                     if (ref($inst_results) eq 'HASH') {
                   10249:                         $inst_results->{$uname.':'.$udom} = {};
                   10250:                     }
1.1226    raeburn  10251:                 }
                   10252:             }
                   10253:             foreach my $udom (keys(%userdoms)) {
                   10254:                 if (!$got_rules->{$udom}) {
                   10255:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10256:                                                              ['usercreation'],$udom);
                   10257:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10258:                         foreach my $item ('username','id') {
                   10259:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  10260:                                 $$curr_rules{$udom}{$item} =
                   10261:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  10262:                             }
                   10263:                         }
                   10264:                     }
                   10265:                     $got_rules->{$udom} = 1;
                   10266:                 }
1.612     raeburn  10267:             }
1.1226    raeburn  10268:             if ($checkid) {
                   10269:                 foreach my $udom (keys(%by_id)) {
                   10270:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10271:                     if ($outcome eq 'ok') {
1.1227    raeburn  10272:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10273:                             my $uname = $by_id{$udom}{$id};
                   10274:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10275:                         }
1.1226    raeburn  10276:                         if (ref($results) eq 'HASH') {
                   10277:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  10278:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10279:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10280:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10281:                                 }
1.1226    raeburn  10282:                             }
                   10283:                         }
                   10284:                     }
1.612     raeburn  10285:                 }
1.615     raeburn  10286:             } else {
1.1226    raeburn  10287:                 foreach my $udom (keys(%by_username)) {
                   10288:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10289:                     if ($outcome eq 'ok') {
1.1227    raeburn  10290:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10291:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10292:                         }
1.1226    raeburn  10293:                         if (ref($results) eq 'HASH') {
                   10294:                             foreach my $uname (keys(%{$results})) {
                   10295:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10296:                             }
                   10297:                         }
                   10298:                     }
                   10299:                 }
1.612     raeburn  10300:             }
1.1226    raeburn  10301:         } elsif (keys(%{$usershash}) == 1) {
                   10302:             my $user = (keys(%{$usershash}))[0];
                   10303:             my ($uname,$udom) = split(/:/,$user);
                   10304:             if (($udom ne '') && ($uname ne '')) {
                   10305:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10306:                     if (ref($checks) eq 'HASH') {
                   10307:                         if (defined($checks->{'username'})) {
                   10308:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   10309:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10310:                         } elsif (defined($checks->{'id'})) {
                   10311:                             if ($usershash->{$user}->{'id'} ne '') {
                   10312:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10313:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10314:                                                                   $usershash->{$user}->{'id'});
                   10315:                             } else {
                   10316:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10317:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10318:                             }
1.585     raeburn  10319:                         }
1.1226    raeburn  10320:                     } else {
                   10321:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10322:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10323:                        return;
                   10324:                     }
                   10325:                     if (!$got_rules->{$udom}) {
                   10326:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10327:                                                                  ['usercreation'],$udom);
                   10328:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10329:                             foreach my $item ('username','id') {
                   10330:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10331:                                    $$curr_rules{$udom}{$item} = 
                   10332:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10333:                                 }
                   10334:                             }
                   10335:                         }
                   10336:                         $got_rules->{$udom} = 1;
1.585     raeburn  10337:                     }
                   10338:                 }
1.1226    raeburn  10339:             } else {
                   10340:                 return;
                   10341:             }
                   10342:         } else {
                   10343:             return;
                   10344:         }
                   10345:         foreach my $user (keys(%{$usershash})) {
                   10346:             my ($uname,$udom) = split(/:/,$user);
                   10347:             next if (($udom eq '') || ($uname eq ''));
                   10348:             my $id;
1.1227    raeburn  10349:             if (ref($inst_results) eq 'HASH') {
                   10350:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10351:                     $id = $inst_results->{$user}->{'id'};
                   10352:                 }
                   10353:             }
                   10354:             if ($id eq '') { 
                   10355:                 if (ref($usershash->{$user})) {
                   10356:                     $id = $usershash->{$user}->{'id'};
                   10357:                 }
1.585     raeburn  10358:             }
1.612     raeburn  10359:             foreach my $item (keys(%{$checks})) {
                   10360:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10361:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10362:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  10363:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10364:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10365:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10366:                                 if ($rule_check{$rule}) {
                   10367:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  10368:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10369:                                         if (ref($inst_results) eq 'HASH') {
                   10370:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10371:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10372:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  10373:                                                 } elsif ($item eq 'id') {
                   10374:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10375:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10376:                                                     }
1.615     raeburn  10377:                                                 }
1.612     raeburn  10378:                                             }
                   10379:                                         }
1.615     raeburn  10380:                                     }
                   10381:                                     last;
1.585     raeburn  10382:                                 }
                   10383:                             }
                   10384:                         }
                   10385:                     }
                   10386:                 }
                   10387:             }
                   10388:         }
                   10389:     }
1.612     raeburn  10390:     return;
                   10391: }
                   10392: 
                   10393: sub user_rule_formats {
                   10394:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10395:     my %text = ( 
                   10396:                  'username' => 'Usernames',
                   10397:                  'id'       => 'IDs',
                   10398:                );
                   10399:     my $output;
                   10400:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10401:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10402:         if (@{$ruleorder} > 0) {
1.1102    raeburn  10403:             $output = '<br />'.
                   10404:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10405:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10406:                       ' <ul>';
1.612     raeburn  10407:             foreach my $rule (@{$ruleorder}) {
                   10408:                 if (ref($curr_rules) eq 'ARRAY') {
                   10409:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10410:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10411:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10412:                                         $rules->{$rule}{'desc'}.'</li>';
                   10413:                         }
                   10414:                     }
                   10415:                 }
                   10416:             }
                   10417:             $output .= '</ul>';
                   10418:         }
                   10419:     }
                   10420:     return $output;
                   10421: }
                   10422: 
                   10423: sub instrule_disallow_msg {
1.615     raeburn  10424:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10425:     my $response;
                   10426:     my %text = (
                   10427:                   item   => 'username',
                   10428:                   items  => 'usernames',
                   10429:                   match  => 'matches',
                   10430:                   do     => 'does',
                   10431:                   action => 'a username',
                   10432:                   one    => 'one',
                   10433:                );
                   10434:     if ($count > 1) {
                   10435:         $text{'item'} = 'usernames';
                   10436:         $text{'match'} ='match';
                   10437:         $text{'do'} = 'do';
                   10438:         $text{'action'} = 'usernames',
                   10439:         $text{'one'} = 'ones';
                   10440:     }
                   10441:     if ($checkitem eq 'id') {
                   10442:         $text{'items'} = 'IDs';
                   10443:         $text{'item'} = 'ID';
                   10444:         $text{'action'} = 'an ID';
1.615     raeburn  10445:         if ($count > 1) {
                   10446:             $text{'item'} = 'IDs';
                   10447:             $text{'action'} = 'IDs';
                   10448:         }
1.612     raeburn  10449:     }
1.674     bisitz   10450:     $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  10451:     if ($mode eq 'upload') {
                   10452:         if ($checkitem eq 'username') {
                   10453:             $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'}.");
                   10454:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10455:             $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  10456:         }
1.669     raeburn  10457:     } elsif ($mode eq 'selfcreate') {
                   10458:         if ($checkitem eq 'id') {
                   10459:             $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.");
                   10460:         }
1.615     raeburn  10461:     } else {
                   10462:         if ($checkitem eq 'username') {
                   10463:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10464:         } elsif ($checkitem eq 'id') {
                   10465:             $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.");
                   10466:         }
1.612     raeburn  10467:     }
                   10468:     return $response;
1.585     raeburn  10469: }
                   10470: 
1.624     raeburn  10471: sub personal_data_fieldtitles {
                   10472:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10473:                         id => 'Student/Employee ID',
                   10474:                         permanentemail => 'E-mail address',
                   10475:                         lastname => 'Last Name',
                   10476:                         firstname => 'First Name',
                   10477:                         middlename => 'Middle Name',
                   10478:                         generation => 'Generation',
                   10479:                         gen => 'Generation',
1.765     raeburn  10480:                         inststatus => 'Affiliation',
1.624     raeburn  10481:                    );
                   10482:     return %fieldtitles;
                   10483: }
                   10484: 
1.642     raeburn  10485: sub sorted_inst_types {
                   10486:     my ($dom) = @_;
1.1185    raeburn  10487:     my ($usertypes,$order);
                   10488:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10489:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10490:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10491:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10492:     } else {
                   10493:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10494:     }
1.642     raeburn  10495:     my $othertitle = &mt('All users');
                   10496:     if ($env{'request.course.id'}) {
1.668     raeburn  10497:         $othertitle  = &mt('Any users');
1.642     raeburn  10498:     }
                   10499:     my @types;
                   10500:     if (ref($order) eq 'ARRAY') {
                   10501:         @types = @{$order};
                   10502:     }
                   10503:     if (@types == 0) {
                   10504:         if (ref($usertypes) eq 'HASH') {
                   10505:             @types = sort(keys(%{$usertypes}));
                   10506:         }
                   10507:     }
                   10508:     if (keys(%{$usertypes}) > 0) {
                   10509:         $othertitle = &mt('Other users');
                   10510:     }
                   10511:     return ($othertitle,$usertypes,\@types);
                   10512: }
                   10513: 
1.645     raeburn  10514: sub get_institutional_codes {
                   10515:     my ($settings,$allcourses,$LC_code) = @_;
                   10516: # Get complete list of course sections to update
                   10517:     my @currsections = ();
                   10518:     my @currxlists = ();
                   10519:     my $coursecode = $$settings{'internal.coursecode'};
                   10520: 
                   10521:     if ($$settings{'internal.sectionnums'} ne '') {
                   10522:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10523:     }
                   10524: 
                   10525:     if ($$settings{'internal.crosslistings'} ne '') {
                   10526:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10527:     }
                   10528: 
                   10529:     if (@currxlists > 0) {
                   10530:         foreach (@currxlists) {
                   10531:             if (m/^([^:]+):(\w*)$/) {
                   10532:                 unless (grep/^$1$/,@{$allcourses}) {
                   10533:                     push @{$allcourses},$1;
                   10534:                     $$LC_code{$1} = $2;
                   10535:                 }
                   10536:             }
                   10537:         }
                   10538:     }
                   10539:  
                   10540:     if (@currsections > 0) {
                   10541:         foreach (@currsections) {
                   10542:             if (m/^(\w+):(\w*)$/) {
                   10543:                 my $sec = $coursecode.$1;
                   10544:                 my $lc_sec = $2;
                   10545:                 unless (grep/^$sec$/,@{$allcourses}) {
                   10546:                     push @{$allcourses},$sec;
                   10547:                     $$LC_code{$sec} = $lc_sec;
                   10548:                 }
                   10549:             }
                   10550:         }
                   10551:     }
                   10552:     return;
                   10553: }
                   10554: 
1.971     raeburn  10555: sub get_standard_codeitems {
                   10556:     return ('Year','Semester','Department','Number','Section');
                   10557: }
                   10558: 
1.112     bowersj2 10559: =pod
                   10560: 
1.780     raeburn  10561: =head1 Slot Helpers
                   10562: 
                   10563: =over 4
                   10564: 
                   10565: =item * sorted_slots()
                   10566: 
1.1040    raeburn  10567: Sorts an array of slot names in order of an optional sort key,
                   10568: default sort is by slot start time (earliest first). 
1.780     raeburn  10569: 
                   10570: Inputs:
                   10571: 
                   10572: =over 4
                   10573: 
                   10574: slotsarr  - Reference to array of unsorted slot names.
                   10575: 
                   10576: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10577: 
1.1040    raeburn  10578: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10579: 
1.549     albertel 10580: =back
                   10581: 
1.780     raeburn  10582: Returns:
                   10583: 
                   10584: =over 4
                   10585: 
1.1040    raeburn  10586: sorted   - An array of slot names sorted by a specified sort key 
                   10587:            (default sort key is start time of the slot).
1.780     raeburn  10588: 
                   10589: =back
                   10590: 
                   10591: =cut
                   10592: 
                   10593: 
                   10594: sub sorted_slots {
1.1040    raeburn  10595:     my ($slotsarr,$slots,$sortkey) = @_;
                   10596:     if ($sortkey eq '') {
                   10597:         $sortkey = 'starttime';
                   10598:     }
1.780     raeburn  10599:     my @sorted;
                   10600:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10601:         @sorted =
                   10602:             sort {
                   10603:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10604:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10605:                      }
                   10606:                      if (ref($slots->{$a})) { return -1;}
                   10607:                      if (ref($slots->{$b})) { return 1;}
                   10608:                      return 0;
                   10609:                  } @{$slotsarr};
                   10610:     }
                   10611:     return @sorted;
                   10612: }
                   10613: 
1.1040    raeburn  10614: =pod
                   10615: 
                   10616: =item * get_future_slots()
                   10617: 
                   10618: Inputs:
                   10619: 
                   10620: =over 4
                   10621: 
                   10622: cnum - course number
                   10623: 
                   10624: cdom - course domain
                   10625: 
                   10626: now - current UNIX time
                   10627: 
                   10628: symb - optional symb
                   10629: 
                   10630: =back
                   10631: 
                   10632: Returns:
                   10633: 
                   10634: =over 4
                   10635: 
                   10636: sorted_reservable - ref to array of student_schedulable slots currently 
                   10637:                     reservable, ordered by end date of reservation period.
                   10638: 
                   10639: reservable_now - ref to hash of student_schedulable slots currently
                   10640:                  reservable.
                   10641: 
                   10642:     Keys in inner hash are:
                   10643:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10644:     (b) endreserve: end date of reservation period.
                   10645:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10646:         selected.
1.1040    raeburn  10647: 
                   10648: sorted_future - ref to array of student_schedulable slots reservable in
                   10649:                 the future, ordered by start date of reservation period.
                   10650: 
                   10651: future_reservable - ref to hash of student_schedulable slots reservable
                   10652:                     in the future.
                   10653: 
                   10654:     Keys in inner hash are:
                   10655:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10656:     (b) startreserve: start date of reservation period.
                   10657:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10658:         selected.
1.1040    raeburn  10659: 
                   10660: =back
                   10661: 
                   10662: =cut
                   10663: 
                   10664: sub get_future_slots {
                   10665:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  10666:     my $map;
                   10667:     if ($symb) {
                   10668:         ($map) = &Apache::lonnet::decode_symb($symb);
                   10669:     }
1.1040    raeburn  10670:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10671:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10672:     foreach my $slot (keys(%slots)) {
                   10673:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10674:         if ($symb) {
1.1229    raeburn  10675:             if ($slots{$slot}->{'symb'} ne '') {
                   10676:                 my $canuse;
                   10677:                 my %oksymbs;
                   10678:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   10679:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   10680:                 if ($oksymbs{$symb}) {
                   10681:                     $canuse = 1;
                   10682:                 } else {
                   10683:                     foreach my $item (@slotsymbs) {
                   10684:                         if ($item =~ /\.(page|sequence)$/) {
                   10685:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   10686:                             if (($map ne '') && ($map eq $sloturl)) {
                   10687:                                 $canuse = 1;
                   10688:                                 last;
                   10689:                             }
                   10690:                         }
                   10691:                     }
                   10692:                 }
                   10693:                 next unless ($canuse);
                   10694:             }
1.1040    raeburn  10695:         }
                   10696:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10697:             ($slots{$slot}->{'endtime'} > $now)) {
                   10698:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10699:                 my $userallowed = 0;
                   10700:                 if ($slots{$slot}->{'allowedsections'}) {
                   10701:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10702:                     if (!defined($env{'request.role.sec'})
                   10703:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10704:                         $userallowed=1;
                   10705:                     } else {
                   10706:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10707:                             $userallowed=1;
                   10708:                         }
                   10709:                     }
                   10710:                     unless ($userallowed) {
                   10711:                         if (defined($env{'request.course.groups'})) {
                   10712:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10713:                             foreach my $group (@groups) {
                   10714:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10715:                                     $userallowed=1;
                   10716:                                     last;
                   10717:                                 }
                   10718:                             }
                   10719:                         }
                   10720:                     }
                   10721:                 }
                   10722:                 if ($slots{$slot}->{'allowedusers'}) {
                   10723:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10724:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10725:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10726:                         $userallowed = 1;
                   10727:                     }
                   10728:                 }
                   10729:                 next unless($userallowed);
                   10730:             }
                   10731:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10732:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10733:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  10734:             my $uniqueperiod;
                   10735:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10736:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10737:             }
1.1040    raeburn  10738:             if (($startreserve < $now) &&
                   10739:                 (!$endreserve || $endreserve > $now)) {
                   10740:                 my $lastres = $endreserve;
                   10741:                 if (!$lastres) {
                   10742:                     $lastres = $slots{$slot}->{'starttime'};
                   10743:                 }
                   10744:                 $reservable_now{$slot} = {
                   10745:                                            symb       => $symb,
1.1250    raeburn  10746:                                            endreserve => $lastres,
                   10747:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  10748:                                          };
                   10749:             } elsif (($startreserve > $now) &&
                   10750:                      (!$endreserve || $endreserve > $startreserve)) {
                   10751:                 $future_reservable{$slot} = {
                   10752:                                               symb         => $symb,
1.1250    raeburn  10753:                                               startreserve => $startreserve,
                   10754:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10755:                                             };
                   10756:             }
                   10757:         }
                   10758:     }
                   10759:     my @unsorted_reservable = keys(%reservable_now);
                   10760:     if (@unsorted_reservable > 0) {
                   10761:         @sorted_reservable = 
                   10762:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10763:     }
                   10764:     my @unsorted_future = keys(%future_reservable);
                   10765:     if (@unsorted_future > 0) {
                   10766:         @sorted_future =
                   10767:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10768:     }
                   10769:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10770: }
1.780     raeburn  10771: 
                   10772: =pod
                   10773: 
1.1057    foxr     10774: =back
                   10775: 
1.549     albertel 10776: =head1 HTTP Helpers
                   10777: 
                   10778: =over 4
                   10779: 
1.648     raeburn  10780: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10781: 
1.258     albertel 10782: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10783: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10784: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10785: 
                   10786: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10787: $possible_names is an ref to an array of form element names.  As an example:
                   10788: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10789: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10790: 
                   10791: =cut
1.1       albertel 10792: 
1.6       albertel 10793: sub get_unprocessed_cgi {
1.25      albertel 10794:   my ($query,$possible_names)= @_;
1.26      matthew  10795:   # $Apache::lonxml::debug=1;
1.356     albertel 10796:   foreach my $pair (split(/&/,$query)) {
                   10797:     my ($name, $value) = split(/=/,$pair);
1.369     www      10798:     $name = &unescape($name);
1.25      albertel 10799:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10800:       $value =~ tr/+/ /;
                   10801:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10802:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10803:     }
1.16      harris41 10804:   }
1.6       albertel 10805: }
                   10806: 
1.112     bowersj2 10807: =pod
                   10808: 
1.648     raeburn  10809: =item * &cacheheader() 
1.112     bowersj2 10810: 
                   10811: returns cache-controlling header code
                   10812: 
                   10813: =cut
                   10814: 
1.7       albertel 10815: sub cacheheader {
1.258     albertel 10816:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10817:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10818:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10819:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10820:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10821:     return $output;
1.7       albertel 10822: }
                   10823: 
1.112     bowersj2 10824: =pod
                   10825: 
1.648     raeburn  10826: =item * &no_cache($r) 
1.112     bowersj2 10827: 
                   10828: specifies header code to not have cache
                   10829: 
                   10830: =cut
                   10831: 
1.9       albertel 10832: sub no_cache {
1.216     albertel 10833:     my ($r) = @_;
                   10834:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10835: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10836:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10837:     $r->no_cache(1);
                   10838:     $r->header_out("Expires" => $date);
                   10839:     $r->header_out("Pragma" => "no-cache");
1.123     www      10840: }
                   10841: 
                   10842: sub content_type {
1.181     albertel 10843:     my ($r,$type,$charset) = @_;
1.299     foxr     10844:     if ($r) {
                   10845: 	#  Note that printout.pl calls this with undef for $r.
                   10846: 	&no_cache($r);
                   10847:     }
1.258     albertel 10848:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10849:     unless ($charset) {
                   10850: 	$charset=&Apache::lonlocal::current_encoding;
                   10851:     }
                   10852:     if ($charset) { $type.='; charset='.$charset; }
                   10853:     if ($r) {
                   10854: 	$r->content_type($type);
                   10855:     } else {
                   10856: 	print("Content-type: $type\n\n");
                   10857:     }
1.9       albertel 10858: }
1.25      albertel 10859: 
1.112     bowersj2 10860: =pod
                   10861: 
1.648     raeburn  10862: =item * &add_to_env($name,$value) 
1.112     bowersj2 10863: 
1.258     albertel 10864: adds $name to the %env hash with value
1.112     bowersj2 10865: $value, if $name already exists, the entry is converted to an array
                   10866: reference and $value is added to the array.
                   10867: 
                   10868: =cut
                   10869: 
1.25      albertel 10870: sub add_to_env {
                   10871:   my ($name,$value)=@_;
1.258     albertel 10872:   if (defined($env{$name})) {
                   10873:     if (ref($env{$name})) {
1.25      albertel 10874:       #already have multiple values
1.258     albertel 10875:       push(@{ $env{$name} },$value);
1.25      albertel 10876:     } else {
                   10877:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10878:       my $first=$env{$name};
                   10879:       undef($env{$name});
                   10880:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10881:     }
                   10882:   } else {
1.258     albertel 10883:     $env{$name}=$value;
1.25      albertel 10884:   }
1.31      albertel 10885: }
1.149     albertel 10886: 
                   10887: =pod
                   10888: 
1.648     raeburn  10889: =item * &get_env_multiple($name) 
1.149     albertel 10890: 
1.258     albertel 10891: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10892: values may be defined and end up as an array ref.
                   10893: 
                   10894: returns an array of values
                   10895: 
                   10896: =cut
                   10897: 
                   10898: sub get_env_multiple {
                   10899:     my ($name) = @_;
                   10900:     my @values;
1.258     albertel 10901:     if (defined($env{$name})) {
1.149     albertel 10902:         # exists is it an array
1.258     albertel 10903:         if (ref($env{$name})) {
                   10904:             @values=@{ $env{$name} };
1.149     albertel 10905:         } else {
1.258     albertel 10906:             $values[0]=$env{$name};
1.149     albertel 10907:         }
                   10908:     }
                   10909:     return(@values);
                   10910: }
                   10911: 
1.1249    damieng  10912: # Looks at given dependencies, and returns something depending on the context.
                   10913: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   10914: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   10915: # For all other contexts, returns ($output, $counter, $numpathchg).
                   10916: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   10917: # $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.
                   10918: # $numpathchg: integer with the number of cleaned up dependency paths.
                   10919: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   10920: # \%mapping: hash reference clean path -> original path for all dependencies.
                   10921: # @param {string} actionurl - The path to the handler, indicative of the context.
                   10922: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   10923: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   10924: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   10925: # @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)
                   10926: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  10927: sub ask_for_embedded_content {
1.1249    damieng  10928:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  10929:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10930:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  10931:         %currsubfile,%unused,$rem);
1.1071    raeburn  10932:     my $counter = 0;
                   10933:     my $numnew = 0;
1.987     raeburn  10934:     my $numremref = 0;
                   10935:     my $numinvalid = 0;
                   10936:     my $numpathchg = 0;
                   10937:     my $numexisting = 0;
1.1071    raeburn  10938:     my $numunused = 0;
                   10939:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  10940:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10941:     my $heading = &mt('Upload embedded files');
                   10942:     my $buttontext = &mt('Upload');
                   10943: 
1.1249    damieng  10944:     # fills these variables based on the context:
                   10945:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   10946:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  10947:     if ($env{'request.course.id'}) {
1.1123    raeburn  10948:         if ($actionurl eq '/adm/dependencies') {
                   10949:             $navmap = Apache::lonnavmaps::navmap->new();
                   10950:         }
                   10951:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10952:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  10953:     }
1.1123    raeburn  10954:     if (($actionurl eq '/adm/portfolio') || 
                   10955:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10956:         my $current_path='/';
                   10957:         if ($env{'form.currentpath'}) {
                   10958:             $current_path = $env{'form.currentpath'};
                   10959:         }
                   10960:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  10961:             $udom = $cdom;
                   10962:             $uname = $cnum;
1.984     raeburn  10963:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10964:         } else {
                   10965:             $udom = $env{'user.domain'};
                   10966:             $uname = $env{'user.name'};
                   10967:             $url = '/userfiles/portfolio';
                   10968:         }
1.987     raeburn  10969:         $toplevel = $url.'/';
1.984     raeburn  10970:         $url .= $current_path;
                   10971:         $getpropath = 1;
1.987     raeburn  10972:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10973:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10974:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10975:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10976:         $toplevel = $url;
1.984     raeburn  10977:         if ($rest ne '') {
1.987     raeburn  10978:             $url .= $rest;
                   10979:         }
                   10980:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10981:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10982:             $url = $args->{'docs_url'};
                   10983:             $toplevel = $url;
1.1084    raeburn  10984:             if ($args->{'context'} eq 'paste') {
                   10985:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10986:                 ($path) = 
                   10987:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10988:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10989:                 $fileloc =~ s{^/}{};
                   10990:             }
1.1071    raeburn  10991:         }
1.1084    raeburn  10992:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  10993:         if ($env{'request.course.id'} ne '') {
                   10994:             if (ref($args) eq 'HASH') {
                   10995:                 $url = $args->{'docs_url'};
                   10996:                 $title = $args->{'docs_title'};
1.1126    raeburn  10997:                 $toplevel = $url; 
                   10998:                 unless ($toplevel =~ m{^/}) {
                   10999:                     $toplevel = "/$url";
                   11000:                 }
1.1085    raeburn  11001:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  11002:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11003:                     $path = $1;
                   11004:                 } else {
                   11005:                     ($path) =
                   11006:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11007:                 }
1.1195    raeburn  11008:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11009:                     $fileloc = $toplevel;
                   11010:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11011:                     my ($udom,$uname,$fname) =
                   11012:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11013:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11014:                 } else {
                   11015:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11016:                 }
1.1071    raeburn  11017:                 $fileloc =~ s{^/}{};
                   11018:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11019:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11020:             }
1.987     raeburn  11021:         }
1.1123    raeburn  11022:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11023:         $udom = $cdom;
                   11024:         $uname = $cnum;
                   11025:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11026:         $toplevel = $url;
                   11027:         $path = $url;
                   11028:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11029:         $fileloc =~ s{^/}{};
1.987     raeburn  11030:     }
1.1249    damieng  11031:     
                   11032:     # parses the dependency paths to get some info
                   11033:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   11034:     # $newfiles: hash URL -> 1 for new files or external URLs
                   11035:     # (will be completed later)
                   11036:     # $mapping:
                   11037:     #   for external URLs: external URL -> external URL
                   11038:     #   for relative paths: clean path -> original path
                   11039:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   11040:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  11041:     foreach my $file (keys(%{$allfiles})) {
                   11042:         my $embed_file;
                   11043:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11044:             $embed_file = $1;
                   11045:         } else {
                   11046:             $embed_file = $file;
                   11047:         }
1.1158    raeburn  11048:         my ($absolutepath,$cleaned_file);
                   11049:         if ($embed_file =~ m{^\w+://}) {
                   11050:             $cleaned_file = $embed_file;
1.1147    raeburn  11051:             $newfiles{$cleaned_file} = 1;
                   11052:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11053:         } else {
1.1158    raeburn  11054:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11055:             if ($embed_file =~ m{^/}) {
                   11056:                 $absolutepath = $embed_file;
                   11057:             }
1.1147    raeburn  11058:             if ($cleaned_file =~ m{/}) {
                   11059:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11060:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11061:                 my $item = $fname;
                   11062:                 if ($path ne '') {
                   11063:                     $item = $path.'/'.$fname;
                   11064:                     $subdependencies{$path}{$fname} = 1;
                   11065:                 } else {
                   11066:                     $dependencies{$item} = 1;
                   11067:                 }
                   11068:                 if ($absolutepath) {
                   11069:                     $mapping{$item} = $absolutepath;
                   11070:                 } else {
                   11071:                     $mapping{$item} = $embed_file;
                   11072:                 }
                   11073:             } else {
                   11074:                 $dependencies{$embed_file} = 1;
                   11075:                 if ($absolutepath) {
1.1147    raeburn  11076:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11077:                 } else {
1.1147    raeburn  11078:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11079:                 }
                   11080:             }
1.984     raeburn  11081:         }
                   11082:     }
1.1249    damieng  11083:     
                   11084:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   11085:     # and lists
                   11086:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   11087:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   11088:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   11089:     #                                    the path had to be cleaned up
                   11090:     # $existing: hash clean path -> 1 if the file exists
                   11091:     # $numexisting: number of keys in $existing
                   11092:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   11093:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   11094:     #                                      dependency subdirectories that are
                   11095:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  11096:     my $dirptr = 16384;
1.984     raeburn  11097:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11098:         $currsubfile{$path} = {};
1.1123    raeburn  11099:         if (($actionurl eq '/adm/portfolio') || 
                   11100:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11101:             my ($sublistref,$listerror) =
                   11102:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11103:             if (ref($sublistref) eq 'ARRAY') {
                   11104:                 foreach my $line (@{$sublistref}) {
                   11105:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11106:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11107:                 }
1.984     raeburn  11108:             }
1.987     raeburn  11109:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11110:             if (opendir(my $dir,$url.'/'.$path)) {
                   11111:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11112:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11113:             }
1.1084    raeburn  11114:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11115:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11116:                   ($args->{'context'} eq 'paste')) ||
                   11117:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11118:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  11119:                 my $dir;
                   11120:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11121:                     $dir = $fileloc;
                   11122:                 } else {
                   11123:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11124:                 }
1.1071    raeburn  11125:                 if ($dir ne '') {
                   11126:                     my ($sublistref,$listerror) =
                   11127:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11128:                     if (ref($sublistref) eq 'ARRAY') {
                   11129:                         foreach my $line (@{$sublistref}) {
                   11130:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11131:                                 undef,$mtime)=split(/\&/,$line,12);
                   11132:                             unless (($testdir&$dirptr) ||
                   11133:                                     ($file_name =~ /^\.\.?$/)) {
                   11134:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11135:                             }
                   11136:                         }
                   11137:                     }
                   11138:                 }
1.984     raeburn  11139:             }
                   11140:         }
                   11141:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11142:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11143:                 my $item = $path.'/'.$file;
                   11144:                 unless ($mapping{$item} eq $item) {
                   11145:                     $pathchanges{$item} = 1;
                   11146:                 }
                   11147:                 $existing{$item} = 1;
                   11148:                 $numexisting ++;
                   11149:             } else {
                   11150:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11151:             }
                   11152:         }
1.1071    raeburn  11153:         if ($actionurl eq '/adm/dependencies') {
                   11154:             foreach my $path (keys(%currsubfile)) {
                   11155:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11156:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11157:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  11158:                              next if (($rem ne '') &&
                   11159:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11160:                                        (ref($navmap) &&
                   11161:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11162:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11163:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11164:                              $unused{$path.'/'.$file} = 1; 
                   11165:                          }
                   11166:                     }
                   11167:                 }
                   11168:             }
                   11169:         }
1.984     raeburn  11170:     }
1.1249    damieng  11171:     
                   11172:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   11173:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  11174:     my %currfile;
1.1123    raeburn  11175:     if (($actionurl eq '/adm/portfolio') ||
                   11176:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11177:         my ($dirlistref,$listerror) =
                   11178:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11179:         if (ref($dirlistref) eq 'ARRAY') {
                   11180:             foreach my $line (@{$dirlistref}) {
                   11181:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11182:                 $currfile{$file_name} = 1;
                   11183:             }
1.984     raeburn  11184:         }
1.987     raeburn  11185:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11186:         if (opendir(my $dir,$url)) {
1.987     raeburn  11187:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11188:             map {$currfile{$_} = 1;} @dir_list;
                   11189:         }
1.1084    raeburn  11190:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11191:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11192:               ($args->{'context'} eq 'paste')) ||
                   11193:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11194:         if ($env{'request.course.id'} ne '') {
                   11195:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11196:             if ($dir ne '') {
                   11197:                 my ($dirlistref,$listerror) =
                   11198:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11199:                 if (ref($dirlistref) eq 'ARRAY') {
                   11200:                     foreach my $line (@{$dirlistref}) {
                   11201:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11202:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11203:                         unless (($testdir&$dirptr) ||
                   11204:                                 ($file_name =~ /^\.\.?$/)) {
                   11205:                             $currfile{$file_name} = [$size,$mtime];
                   11206:                         }
                   11207:                     }
                   11208:                 }
                   11209:             }
                   11210:         }
1.984     raeburn  11211:     }
1.1249    damieng  11212:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   11213:     # are not in subdirectories, using $currfile
1.984     raeburn  11214:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11215:         if (exists($currfile{$file})) {
1.987     raeburn  11216:             unless ($mapping{$file} eq $file) {
                   11217:                 $pathchanges{$file} = 1;
                   11218:             }
                   11219:             $existing{$file} = 1;
                   11220:             $numexisting ++;
                   11221:         } else {
1.984     raeburn  11222:             $newfiles{$file} = 1;
                   11223:         }
                   11224:     }
1.1071    raeburn  11225:     foreach my $file (keys(%currfile)) {
                   11226:         unless (($file eq $filename) ||
                   11227:                 ($file eq $filename.'.bak') ||
                   11228:                 ($dependencies{$file})) {
1.1085    raeburn  11229:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  11230:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11231:                     next if (($rem ne '') &&
                   11232:                              (($env{"httpref.$rem".$file} ne '') ||
                   11233:                               (ref($navmap) &&
                   11234:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11235:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11236:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11237:                 }
1.1085    raeburn  11238:             }
1.1071    raeburn  11239:             $unused{$file} = 1;
                   11240:         }
                   11241:     }
1.1249    damieng  11242:     
                   11243:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  11244:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11245:         ($args->{'context'} eq 'paste')) {
                   11246:         $counter = scalar(keys(%existing));
                   11247:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  11248:         return ($output,$counter,$numpathchg,\%existing);
                   11249:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   11250:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11251:         $counter = scalar(keys(%existing));
                   11252:         $numpathchg = scalar(keys(%pathchanges));
                   11253:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  11254:     }
1.1249    damieng  11255:     
                   11256:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   11257:     
                   11258:     # $upload_output: missing dependencies (with upload form)
                   11259:     # $modify_output: uploaded dependencies (in use)
                   11260:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  11261:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11262:         if ($actionurl eq '/adm/dependencies') {
                   11263:             next if ($embed_file =~ m{^\w+://});
                   11264:         }
1.660     raeburn  11265:         $upload_output .= &start_data_table_row().
1.1123    raeburn  11266:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11267:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11268:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  11269:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11270:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11271:         }
1.1123    raeburn  11272:         $upload_output .= '</td>';
1.1071    raeburn  11273:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  11274:             $upload_output.='<td align="right">'.
                   11275:                             '<span class="LC_info LC_fontsize_medium">'.
                   11276:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11277:             $numremref++;
1.660     raeburn  11278:         } elsif ($args->{'error_on_invalid_names'}
                   11279:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  11280:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11281:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11282:             $numinvalid++;
1.660     raeburn  11283:         } else {
1.1123    raeburn  11284:             $upload_output .= '<td>'.
                   11285:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11286:                                                      $embed_file,\%mapping,
1.1071    raeburn  11287:                                                      $allfiles,$codebase,'upload');
                   11288:             $counter ++;
                   11289:             $numnew ++;
1.987     raeburn  11290:         }
                   11291:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11292:     }
                   11293:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11294:         if ($actionurl eq '/adm/dependencies') {
                   11295:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11296:             $modify_output .= &start_data_table_row().
                   11297:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11298:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11299:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11300:                               '<td>'.$size.'</td>'.
                   11301:                               '<td>'.$mtime.'</td>'.
                   11302:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11303:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11304:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11305:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11306:                               &embedded_file_element('upload_embedded',$counter,
                   11307:                                                      $embed_file,\%mapping,
                   11308:                                                      $allfiles,$codebase,'modify').
                   11309:                               '</div></td>'.
                   11310:                               &end_data_table_row()."\n";
                   11311:             $counter ++;
                   11312:         } else {
                   11313:             $upload_output .= &start_data_table_row().
1.1123    raeburn  11314:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11315:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11316:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11317:                               &Apache::loncommon::end_data_table_row()."\n";
                   11318:         }
                   11319:     }
                   11320:     my $delidx = $counter;
                   11321:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11322:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11323:         $delete_output .= &start_data_table_row().
                   11324:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11325:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11326:                           '<td>'.$size.'</td>'.
                   11327:                           '<td>'.$mtime.'</td>'.
                   11328:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11329:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11330:                           &embedded_file_element('upload_embedded',$delidx,
                   11331:                                                  $oldfile,\%mapping,$allfiles,
                   11332:                                                  $codebase,'delete').'</td>'.
                   11333:                           &end_data_table_row()."\n"; 
                   11334:         $numunused ++;
                   11335:         $delidx ++;
1.987     raeburn  11336:     }
                   11337:     if ($upload_output) {
                   11338:         $upload_output = &start_data_table().
                   11339:                          $upload_output.
                   11340:                          &end_data_table()."\n";
                   11341:     }
1.1071    raeburn  11342:     if ($modify_output) {
                   11343:         $modify_output = &start_data_table().
                   11344:                          &start_data_table_header_row().
                   11345:                          '<th>'.&mt('File').'</th>'.
                   11346:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11347:                          '<th>'.&mt('Modified').'</th>'.
                   11348:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11349:                          &end_data_table_header_row().
                   11350:                          $modify_output.
                   11351:                          &end_data_table()."\n";
                   11352:     }
                   11353:     if ($delete_output) {
                   11354:         $delete_output = &start_data_table().
                   11355:                          &start_data_table_header_row().
                   11356:                          '<th>'.&mt('File').'</th>'.
                   11357:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11358:                          '<th>'.&mt('Modified').'</th>'.
                   11359:                          '<th>'.&mt('Delete?').'</th>'.
                   11360:                          &end_data_table_header_row().
                   11361:                          $delete_output.
                   11362:                          &end_data_table()."\n";
                   11363:     }
1.987     raeburn  11364:     my $applies = 0;
                   11365:     if ($numremref) {
                   11366:         $applies ++;
                   11367:     }
                   11368:     if ($numinvalid) {
                   11369:         $applies ++;
                   11370:     }
                   11371:     if ($numexisting) {
                   11372:         $applies ++;
                   11373:     }
1.1071    raeburn  11374:     if ($counter || $numunused) {
1.987     raeburn  11375:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11376:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11377:                   $state.'<h3>'.$heading.'</h3>'; 
                   11378:         if ($actionurl eq '/adm/dependencies') {
                   11379:             if ($numnew) {
                   11380:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11381:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11382:                            $upload_output.'<br />'."\n";
                   11383:             }
                   11384:             if ($numexisting) {
                   11385:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11386:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11387:                            $modify_output.'<br />'."\n";
                   11388:                            $buttontext = &mt('Save changes');
                   11389:             }
                   11390:             if ($numunused) {
                   11391:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11392:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11393:                            $delete_output.'<br />'."\n";
                   11394:                            $buttontext = &mt('Save changes');
                   11395:             }
                   11396:         } else {
                   11397:             $output .= $upload_output.'<br />'."\n";
                   11398:         }
                   11399:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11400:                    $counter.'" />'."\n";
                   11401:         if ($actionurl eq '/adm/dependencies') { 
                   11402:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11403:                        $numnew.'" />'."\n";
                   11404:         } elsif ($actionurl eq '') {
1.987     raeburn  11405:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11406:         }
                   11407:     } elsif ($applies) {
                   11408:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11409:         if ($applies > 1) {
                   11410:             $output .=  
1.1123    raeburn  11411:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11412:             if ($numremref) {
                   11413:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11414:             }
                   11415:             if ($numinvalid) {
                   11416:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11417:             }
                   11418:             if ($numexisting) {
                   11419:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11420:             }
                   11421:             $output .= '</ul><br />';
                   11422:         } elsif ($numremref) {
                   11423:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11424:         } elsif ($numinvalid) {
                   11425:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11426:         } elsif ($numexisting) {
                   11427:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11428:         }
                   11429:         $output .= $upload_output.'<br />';
                   11430:     }
                   11431:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11432:     $chgcount = $counter;
1.987     raeburn  11433:     if (keys(%pathchanges) > 0) {
                   11434:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11435:             if ($counter) {
1.987     raeburn  11436:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11437:                                                   $embed_file,\%mapping,
1.1071    raeburn  11438:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11439:             } else {
                   11440:                 $pathchange_output .= 
                   11441:                     &start_data_table_row().
                   11442:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11443:                     $chgcount.'" checked="checked" /></td>'.
                   11444:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11445:                     '<td>'.$embed_file.
                   11446:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11447:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11448:                     '</td>'.&end_data_table_row();
1.660     raeburn  11449:             }
1.987     raeburn  11450:             $numpathchg ++;
                   11451:             $chgcount ++;
1.660     raeburn  11452:         }
                   11453:     }
1.1127    raeburn  11454:     if (($counter) || ($numunused)) {
1.987     raeburn  11455:         if ($numpathchg) {
                   11456:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11457:                        $numpathchg.'" />'."\n";
                   11458:         }
                   11459:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11460:             ($actionurl eq '/adm/imsimport')) {
                   11461:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11462:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11463:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11464:         } elsif ($actionurl eq '/adm/dependencies') {
                   11465:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11466:         }
1.1123    raeburn  11467:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11468:     } elsif ($numpathchg) {
                   11469:         my %pathchange = ();
                   11470:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11471:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11472:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  11473:         }
1.987     raeburn  11474:     }
1.1071    raeburn  11475:     return ($output,$counter,$numpathchg);
1.987     raeburn  11476: }
                   11477: 
1.1147    raeburn  11478: =pod
                   11479: 
                   11480: =item * clean_path($name)
                   11481: 
                   11482: Performs clean-up of directories, subdirectories and filename in an
                   11483: embedded object, referenced in an HTML file which is being uploaded
                   11484: to a course or portfolio, where 
                   11485: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11486: checked.
                   11487: 
                   11488: Clean-up is similar to replacements in lonnet::clean_filename()
                   11489: except each / between sub-directory and next level is preserved.
                   11490: 
                   11491: =cut
                   11492: 
                   11493: sub clean_path {
                   11494:     my ($embed_file) = @_;
                   11495:     $embed_file =~s{^/+}{};
                   11496:     my @contents;
                   11497:     if ($embed_file =~ m{/}) {
                   11498:         @contents = split(/\//,$embed_file);
                   11499:     } else {
                   11500:         @contents = ($embed_file);
                   11501:     }
                   11502:     my $lastidx = scalar(@contents)-1;
                   11503:     for (my $i=0; $i<=$lastidx; $i++) { 
                   11504:         $contents[$i]=~s{\\}{/}g;
                   11505:         $contents[$i]=~s/\s+/\_/g;
                   11506:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11507:         if ($i == $lastidx) {
                   11508:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11509:         }
                   11510:     }
                   11511:     if ($lastidx > 0) {
                   11512:         return join('/',@contents);
                   11513:     } else {
                   11514:         return $contents[0];
                   11515:     }
                   11516: }
                   11517: 
1.987     raeburn  11518: sub embedded_file_element {
1.1071    raeburn  11519:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11520:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11521:                    (ref($codebase) eq 'HASH'));
                   11522:     my $output;
1.1071    raeburn  11523:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11524:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11525:     }
                   11526:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11527:                &escape($embed_file).'" />';
                   11528:     unless (($context eq 'upload_embedded') && 
                   11529:             ($mapping->{$embed_file} eq $embed_file)) {
                   11530:         $output .='
                   11531:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11532:     }
                   11533:     my $attrib;
                   11534:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11535:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11536:     }
                   11537:     $output .=
                   11538:         "\n\t\t".
                   11539:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11540:         $attrib.'" />';
                   11541:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11542:         $output .=
                   11543:             "\n\t\t".
                   11544:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11545:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11546:     }
1.987     raeburn  11547:     return $output;
1.660     raeburn  11548: }
                   11549: 
1.1071    raeburn  11550: sub get_dependency_details {
                   11551:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11552:     my ($size,$mtime,$showsize,$showmtime);
                   11553:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11554:         if ($embed_file =~ m{/}) {
                   11555:             my ($path,$fname) = split(/\//,$embed_file);
                   11556:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11557:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11558:             }
                   11559:         } else {
                   11560:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11561:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11562:             }
                   11563:         }
                   11564:         $showsize = $size/1024.0;
                   11565:         $showsize = sprintf("%.1f",$showsize);
                   11566:         if ($mtime > 0) {
                   11567:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11568:         }
                   11569:     }
                   11570:     return ($showsize,$showmtime);
                   11571: }
                   11572: 
                   11573: sub ask_embedded_js {
                   11574:     return <<"END";
                   11575: <script type="text/javascript"">
                   11576: // <![CDATA[
                   11577: function toggleBrowse(counter) {
                   11578:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11579:     var fileid = document.getElementById('embedded_item_'+counter);
                   11580:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11581:     if (chkboxid.checked == true) {
                   11582:         uploaddivid.style.display='block';
                   11583:     } else {
                   11584:         uploaddivid.style.display='none';
                   11585:         fileid.value = '';
                   11586:     }
                   11587: }
                   11588: // ]]>
                   11589: </script>
                   11590: 
                   11591: END
                   11592: }
                   11593: 
1.661     raeburn  11594: sub upload_embedded {
                   11595:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11596:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11597:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11598:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11599:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11600:         my $orig_uploaded_filename =
                   11601:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11602:         foreach my $type ('orig','ref','attrib','codebase') {
                   11603:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11604:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11605:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11606:             }
                   11607:         }
1.661     raeburn  11608:         my ($path,$fname) =
                   11609:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11610:         # no path, whole string is fname
                   11611:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11612:         $fname = &Apache::lonnet::clean_filename($fname);
                   11613:         # See if there is anything left
                   11614:         next if ($fname eq '');
                   11615: 
                   11616:         # Check if file already exists as a file or directory.
                   11617:         my ($state,$msg);
                   11618:         if ($context eq 'portfolio') {
                   11619:             my $port_path = $dirpath;
                   11620:             if ($group ne '') {
                   11621:                 $port_path = "groups/$group/$port_path";
                   11622:             }
1.987     raeburn  11623:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11624:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11625:                                               $dir_root,$port_path,$disk_quota,
                   11626:                                               $current_disk_usage,$uname,$udom);
                   11627:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11628:                 || $state eq 'file_locked') {
1.661     raeburn  11629:                 $output .= $msg;
                   11630:                 next;
                   11631:             }
                   11632:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11633:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11634:             if ($state eq 'exists') {
                   11635:                 $output .= $msg;
                   11636:                 next;
                   11637:             }
                   11638:         }
                   11639:         # Check if extension is valid
                   11640:         if (($fname =~ /\.(\w+)$/) &&
                   11641:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   11642:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11643:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11644:             next;
                   11645:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11646:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11647:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11648:             next;
                   11649:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   11650:             $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  11651:             next;
                   11652:         }
                   11653:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  11654:         my $subdir = $path;
                   11655:         $subdir =~ s{/+$}{};
1.661     raeburn  11656:         if ($context eq 'portfolio') {
1.984     raeburn  11657:             my $result;
                   11658:             if ($state eq 'existingfile') {
                   11659:                 $result=
                   11660:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  11661:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11662:             } else {
1.984     raeburn  11663:                 $result=
                   11664:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11665:                                                     $dirpath.
1.1123    raeburn  11666:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11667:                 if ($result !~ m|^/uploaded/|) {
                   11668:                     $output .= '<span class="LC_error">'
                   11669:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11670:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11671:                                .'</span><br />';
                   11672:                     next;
                   11673:                 } else {
1.987     raeburn  11674:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11675:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11676:                 }
1.661     raeburn  11677:             }
1.1123    raeburn  11678:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  11679:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11680:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11681:             my $result =
1.1126    raeburn  11682:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11683:             if ($result !~ m|^/uploaded/|) {
                   11684:                 $output .= '<span class="LC_error">'
                   11685:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11686:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11687:                            .'</span><br />';
                   11688:                     next;
                   11689:             } else {
                   11690:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11691:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  11692:                 if ($context eq 'syllabus') {
                   11693:                     &Apache::lonnet::make_public_indefinitely($result);
                   11694:                 }
1.987     raeburn  11695:             }
1.661     raeburn  11696:         } else {
                   11697: # Save the file
                   11698:             my $target = $env{'form.embedded_item_'.$i};
                   11699:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11700:             my $dest = $fullpath.$fname;
                   11701:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11702:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11703:             my $count;
                   11704:             my $filepath = $dir_root;
1.1027    raeburn  11705:             foreach my $subdir (@parts) {
                   11706:                 $filepath .= "/$subdir";
                   11707:                 if (!-e $filepath) {
1.661     raeburn  11708:                     mkdir($filepath,0770);
                   11709:                 }
                   11710:             }
                   11711:             my $fh;
                   11712:             if (!open($fh,'>'.$dest)) {
                   11713:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11714:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11715:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11716:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11717:                            '</span><br />';
                   11718:             } else {
                   11719:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11720:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11721:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11722:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11723:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11724:                               '</span><br />';
                   11725:                 } else {
1.987     raeburn  11726:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11727:                                $url.'</span>').'<br />';
                   11728:                     unless ($context eq 'testbank') {
                   11729:                         $footer .= &mt('View embedded file: [_1]',
                   11730:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11731:                     }
                   11732:                 }
                   11733:                 close($fh);
                   11734:             }
                   11735:         }
                   11736:         if ($env{'form.embedded_ref_'.$i}) {
                   11737:             $pathchange{$i} = 1;
                   11738:         }
                   11739:     }
                   11740:     if ($output) {
                   11741:         $output = '<p>'.$output.'</p>';
                   11742:     }
                   11743:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11744:     $returnflag = 'ok';
1.1071    raeburn  11745:     my $numpathchgs = scalar(keys(%pathchange));
                   11746:     if ($numpathchgs > 0) {
1.987     raeburn  11747:         if ($context eq 'portfolio') {
                   11748:             $output .= '<p>'.&mt('or').'</p>';
                   11749:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11750:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11751:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11752:             $returnflag = 'modify_orightml';
                   11753:         }
                   11754:     }
1.1071    raeburn  11755:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11756: }
                   11757: 
                   11758: sub modify_html_form {
                   11759:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11760:     my $end = 0;
                   11761:     my $modifyform;
                   11762:     if ($context eq 'upload_embedded') {
                   11763:         return unless (ref($pathchange) eq 'HASH');
                   11764:         if ($env{'form.number_embedded_items'}) {
                   11765:             $end += $env{'form.number_embedded_items'};
                   11766:         }
                   11767:         if ($env{'form.number_pathchange_items'}) {
                   11768:             $end += $env{'form.number_pathchange_items'};
                   11769:         }
                   11770:         if ($end) {
                   11771:             for (my $i=0; $i<$end; $i++) {
                   11772:                 if ($i < $env{'form.number_embedded_items'}) {
                   11773:                     next unless($pathchange->{$i});
                   11774:                 }
                   11775:                 $modifyform .=
                   11776:                     &start_data_table_row().
                   11777:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11778:                     'checked="checked" /></td>'.
                   11779:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11780:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11781:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11782:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11783:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11784:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11785:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11786:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11787:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11788:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11789:                     &end_data_table_row();
1.1071    raeburn  11790:             }
1.987     raeburn  11791:         }
                   11792:     } else {
                   11793:         $modifyform = $pathchgtable;
                   11794:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11795:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11796:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11797:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11798:         }
                   11799:     }
                   11800:     if ($modifyform) {
1.1071    raeburn  11801:         if ($actionurl eq '/adm/dependencies') {
                   11802:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11803:         }
1.987     raeburn  11804:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11805:                '<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".
                   11806:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11807:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11808:                '</ol></p>'."\n".'<p>'.
                   11809:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11810:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11811:                &start_data_table()."\n".
                   11812:                &start_data_table_header_row().
                   11813:                '<th>'.&mt('Change?').'</th>'.
                   11814:                '<th>'.&mt('Current reference').'</th>'.
                   11815:                '<th>'.&mt('Required reference').'</th>'.
                   11816:                &end_data_table_header_row()."\n".
                   11817:                $modifyform.
                   11818:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11819:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11820:                '</form>'."\n";
                   11821:     }
                   11822:     return;
                   11823: }
                   11824: 
                   11825: sub modify_html_refs {
1.1123    raeburn  11826:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11827:     my $container;
                   11828:     if ($context eq 'portfolio') {
                   11829:         $container = $env{'form.container'};
                   11830:     } elsif ($context eq 'coursedoc') {
                   11831:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11832:     } elsif ($context eq 'manage_dependencies') {
                   11833:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11834:         $container = "/$container";
1.1123    raeburn  11835:     } elsif ($context eq 'syllabus') {
                   11836:         $container = $url;
1.987     raeburn  11837:     } else {
1.1027    raeburn  11838:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11839:     }
                   11840:     my (%allfiles,%codebase,$output,$content);
                   11841:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  11842:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  11843:         if (wantarray) {
                   11844:             return ('',0,0); 
                   11845:         } else {
                   11846:             return;
                   11847:         }
                   11848:     }
                   11849:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11850:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11851:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11852:             if (wantarray) {
                   11853:                 return ('',0,0);
                   11854:             } else {
                   11855:                 return;
                   11856:             }
                   11857:         } 
1.987     raeburn  11858:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11859:         if ($content eq '-1') {
                   11860:             if (wantarray) {
                   11861:                 return ('',0,0);
                   11862:             } else {
                   11863:                 return;
                   11864:             }
                   11865:         }
1.987     raeburn  11866:     } else {
1.1071    raeburn  11867:         unless ($container =~ /^\Q$dir_root\E/) {
                   11868:             if (wantarray) {
                   11869:                 return ('',0,0);
                   11870:             } else {
                   11871:                 return;
                   11872:             }
                   11873:         } 
1.987     raeburn  11874:         if (open(my $fh,"<$container")) {
                   11875:             $content = join('', <$fh>);
                   11876:             close($fh);
                   11877:         } else {
1.1071    raeburn  11878:             if (wantarray) {
                   11879:                 return ('',0,0);
                   11880:             } else {
                   11881:                 return;
                   11882:             }
1.987     raeburn  11883:         }
                   11884:     }
                   11885:     my ($count,$codebasecount) = (0,0);
                   11886:     my $mm = new File::MMagic;
                   11887:     my $mime_type = $mm->checktype_contents($content);
                   11888:     if ($mime_type eq 'text/html') {
                   11889:         my $parse_result = 
                   11890:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11891:                                                     \%codebase,\$content);
                   11892:         if ($parse_result eq 'ok') {
                   11893:             foreach my $i (@changes) {
                   11894:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11895:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11896:                 if ($allfiles{$ref}) {
                   11897:                     my $newname =  $orig;
                   11898:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11899:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11900:                     if ($attrib_regexp =~ /:/) {
                   11901:                         $attrib_regexp =~ s/\:/|/g;
                   11902:                     }
                   11903:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11904:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11905:                         $count += $numchg;
1.1123    raeburn  11906:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  11907:                         delete($allfiles{$ref});
1.987     raeburn  11908:                     }
                   11909:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11910:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11911:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11912:                         $codebasecount ++;
                   11913:                     }
                   11914:                 }
                   11915:             }
1.1123    raeburn  11916:             my $skiprewrites;
1.987     raeburn  11917:             if ($count || $codebasecount) {
                   11918:                 my $saveresult;
1.1071    raeburn  11919:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11920:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11921:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11922:                     if ($url eq $container) {
                   11923:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11924:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11925:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11926:                                             $fname.'</span>').'</p>';
1.987     raeburn  11927:                     } else {
                   11928:                          $output = '<p class="LC_error">'.
                   11929:                                    &mt('Error: update failed for: [_1].',
                   11930:                                    '<span class="LC_filename">'.
                   11931:                                    $container.'</span>').'</p>';
                   11932:                     }
1.1123    raeburn  11933:                     if ($context eq 'syllabus') {
                   11934:                         unless ($saveresult eq 'ok') {
                   11935:                             $skiprewrites = 1;
                   11936:                         }
                   11937:                     }
1.987     raeburn  11938:                 } else {
                   11939:                     if (open(my $fh,">$container")) {
                   11940:                         print $fh $content;
                   11941:                         close($fh);
                   11942:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11943:                                   $count,'<span class="LC_filename">'.
                   11944:                                   $container.'</span>').'</p>';
1.661     raeburn  11945:                     } else {
1.987     raeburn  11946:                          $output = '<p class="LC_error">'.
                   11947:                                    &mt('Error: could not update [_1].',
                   11948:                                    '<span class="LC_filename">'.
                   11949:                                    $container.'</span>').'</p>';
1.661     raeburn  11950:                     }
                   11951:                 }
                   11952:             }
1.1123    raeburn  11953:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11954:                 my ($actionurl,$state);
                   11955:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11956:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11957:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11958:                                               \%codebase,
                   11959:                                               {'context' => 'rewrites',
                   11960:                                                'ignore_remote_references' => 1,});
                   11961:                 if (ref($mapping) eq 'HASH') {
                   11962:                     my $rewrites = 0;
                   11963:                     foreach my $key (keys(%{$mapping})) {
                   11964:                         next if ($key =~ m{^https?://});
                   11965:                         my $ref = $mapping->{$key};
                   11966:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11967:                         my $attrib;
                   11968:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11969:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11970:                         }
                   11971:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11972:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11973:                             $rewrites += $numchg;
                   11974:                         }
                   11975:                     }
                   11976:                     if ($rewrites) {
                   11977:                         my $saveresult; 
                   11978:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11979:                         if ($url eq $container) {
                   11980:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11981:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11982:                                             $count,'<span class="LC_filename">'.
                   11983:                                             $fname.'</span>').'</p>';
                   11984:                         } else {
                   11985:                             $output .= '<p class="LC_error">'.
                   11986:                                        &mt('Error: could not update links in [_1].',
                   11987:                                        '<span class="LC_filename">'.
                   11988:                                        $container.'</span>').'</p>';
                   11989: 
                   11990:                         }
                   11991:                     }
                   11992:                 }
                   11993:             }
1.987     raeburn  11994:         } else {
                   11995:             &logthis('Failed to parse '.$container.
                   11996:                      ' to modify references: '.$parse_result);
1.661     raeburn  11997:         }
                   11998:     }
1.1071    raeburn  11999:     if (wantarray) {
                   12000:         return ($output,$count,$codebasecount);
                   12001:     } else {
                   12002:         return $output;
                   12003:     }
1.661     raeburn  12004: }
                   12005: 
                   12006: sub check_for_existing {
                   12007:     my ($path,$fname,$element) = @_;
                   12008:     my ($state,$msg);
                   12009:     if (-d $path.'/'.$fname) {
                   12010:         $state = 'exists';
                   12011:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12012:     } elsif (-e $path.'/'.$fname) {
                   12013:         $state = 'exists';
                   12014:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12015:     }
                   12016:     if ($state eq 'exists') {
                   12017:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12018:     }
                   12019:     return ($state,$msg);
                   12020: }
                   12021: 
                   12022: sub check_for_upload {
                   12023:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12024:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12025:     my $filesize = length($env{'form.'.$element});
                   12026:     if (!$filesize) {
                   12027:         my $msg = '<span class="LC_error">'.
                   12028:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12029:                       '<span class="LC_filename">'.$fname.'</span>',
                   12030:                       $filesize).'<br />'.
1.1007    raeburn  12031:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12032:                   '</span>';
                   12033:         return ('zero_bytes',$msg);
                   12034:     }
                   12035:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12036:     my $getpropath = 1;
1.1021    raeburn  12037:     my ($dirlistref,$listerror) =
                   12038:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12039:     my $found_file = 0;
                   12040:     my $locked_file = 0;
1.991     raeburn  12041:     my @lockers;
                   12042:     my $navmap;
                   12043:     if ($env{'request.course.id'}) {
                   12044:         $navmap = Apache::lonnavmaps::navmap->new();
                   12045:     }
1.1021    raeburn  12046:     if (ref($dirlistref) eq 'ARRAY') {
                   12047:         foreach my $line (@{$dirlistref}) {
                   12048:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12049:             if ($file_name eq $fname){
                   12050:                 $file_name = $path.$file_name;
                   12051:                 if ($group ne '') {
                   12052:                     $file_name = $group.$file_name;
                   12053:                 }
                   12054:                 $found_file = 1;
                   12055:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12056:                     foreach my $lock (@lockers) {
                   12057:                         if (ref($lock) eq 'ARRAY') {
                   12058:                             my ($symb,$crsid) = @{$lock};
                   12059:                             if ($crsid eq $env{'request.course.id'}) {
                   12060:                                 if (ref($navmap)) {
                   12061:                                     my $res = $navmap->getBySymb($symb);
                   12062:                                     foreach my $part (@{$res->parts()}) { 
                   12063:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12064:                                         unless (($slot_status == $res->RESERVED) ||
                   12065:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12066:                                             $locked_file = 1;
                   12067:                                         }
1.991     raeburn  12068:                                     }
1.1021    raeburn  12069:                                 } else {
                   12070:                                     $locked_file = 1;
1.991     raeburn  12071:                                 }
                   12072:                             } else {
                   12073:                                 $locked_file = 1;
                   12074:                             }
                   12075:                         }
1.1021    raeburn  12076:                    }
                   12077:                 } else {
                   12078:                     my @info = split(/\&/,$rest);
                   12079:                     my $currsize = $info[6]/1000;
                   12080:                     if ($currsize < $filesize) {
                   12081:                         my $extra = $filesize - $currsize;
                   12082:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   12083:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12084:                                       &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   12085:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12086:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12087:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12088:                             return ('will_exceed_quota',$msg);
                   12089:                         }
1.984     raeburn  12090:                     }
                   12091:                 }
1.661     raeburn  12092:             }
                   12093:         }
                   12094:     }
                   12095:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   12096:         my $msg = '<p class="LC_warning">'.
                   12097:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  12098:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12099:         return ('will_exceed_quota',$msg);
                   12100:     } elsif ($found_file) {
                   12101:         if ($locked_file) {
1.1179    bisitz   12102:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12103:             $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   12104:             $msg .= '</p>';
1.661     raeburn  12105:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12106:             return ('file_locked',$msg);
                   12107:         } else {
1.1179    bisitz   12108:             my $msg = '<p class="LC_error">';
1.984     raeburn  12109:             $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   12110:             $msg .= '</p>';
1.984     raeburn  12111:             return ('existingfile',$msg);
1.661     raeburn  12112:         }
                   12113:     }
                   12114: }
                   12115: 
1.987     raeburn  12116: sub check_for_traversal {
                   12117:     my ($path,$url,$toplevel) = @_;
                   12118:     my @parts=split(/\//,$path);
                   12119:     my $cleanpath;
                   12120:     my $fullpath = $url;
                   12121:     for (my $i=0;$i<@parts;$i++) {
                   12122:         next if ($parts[$i] eq '.');
                   12123:         if ($parts[$i] eq '..') {
                   12124:             $fullpath =~ s{([^/]+/)$}{};
                   12125:         } else {
                   12126:             $fullpath .= $parts[$i].'/';
                   12127:         }
                   12128:     }
                   12129:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12130:         $cleanpath = $1;
                   12131:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12132:         my $curr_toprel = $1;
                   12133:         my @parts = split(/\//,$curr_toprel);
                   12134:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12135:         my @urlparts = split(/\//,$url_toprel);
                   12136:         my $doubledots;
                   12137:         my $startdiff = -1;
                   12138:         for (my $i=0; $i<@urlparts; $i++) {
                   12139:             if ($startdiff == -1) {
                   12140:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12141:                     $startdiff = $i;
                   12142:                     $doubledots .= '../';
                   12143:                 }
                   12144:             } else {
                   12145:                 $doubledots .= '../';
                   12146:             }
                   12147:         }
                   12148:         if ($startdiff > -1) {
                   12149:             $cleanpath = $doubledots;
                   12150:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12151:                 $cleanpath .= $parts[$i].'/';
                   12152:             }
                   12153:         }
                   12154:     }
                   12155:     $cleanpath =~ s{(/)$}{};
                   12156:     return $cleanpath;
                   12157: }
1.31      albertel 12158: 
1.1053    raeburn  12159: sub is_archive_file {
                   12160:     my ($mimetype) = @_;
                   12161:     if (($mimetype eq 'application/octet-stream') ||
                   12162:         ($mimetype eq 'application/x-stuffit') ||
                   12163:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12164:         return 1;
                   12165:     }
                   12166:     return;
                   12167: }
                   12168: 
                   12169: sub decompress_form {
1.1065    raeburn  12170:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12171:     my %lt = &Apache::lonlocal::texthash (
                   12172:         this => 'This file is an archive file.',
1.1067    raeburn  12173:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12174:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12175:         youm => 'You may wish to extract its contents.',
                   12176:         extr => 'Extract contents',
1.1067    raeburn  12177:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12178:         proa => 'Process automatically?',
1.1053    raeburn  12179:         yes  => 'Yes',
                   12180:         no   => 'No',
1.1067    raeburn  12181:         fold => 'Title for folder containing movie',
                   12182:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12183:     );
1.1065    raeburn  12184:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12185:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12186:     my $info = &list_archive_contents($fileloc,\@paths);
                   12187:     if (@paths) {
                   12188:         foreach my $path (@paths) {
                   12189:             $path =~ s{^/}{};
1.1067    raeburn  12190:             if ($path =~ m{^([^/]+)/$}) {
                   12191:                 $topdir = $1;
                   12192:             }
1.1065    raeburn  12193:             if ($path =~ m{^([^/]+)/}) {
                   12194:                 $toplevel{$1} = $path;
                   12195:             } else {
                   12196:                 $toplevel{$path} = $path;
                   12197:             }
                   12198:         }
                   12199:     }
1.1067    raeburn  12200:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  12201:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12202:                         "$topdir/media/",
                   12203:                         "$topdir/media/$topdir.mp4",
                   12204:                         "$topdir/media/FirstFrame.png",
                   12205:                         "$topdir/media/player.swf",
                   12206:                         "$topdir/media/swfobject.js",
                   12207:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  12208:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  12209:                          "$topdir/$topdir.mp4",
                   12210:                          "$topdir/$topdir\_config.xml",
                   12211:                          "$topdir/$topdir\_controller.swf",
                   12212:                          "$topdir/$topdir\_embed.css",
                   12213:                          "$topdir/$topdir\_First_Frame.png",
                   12214:                          "$topdir/$topdir\_player.html",
                   12215:                          "$topdir/$topdir\_Thumbnails.png",
                   12216:                          "$topdir/playerProductInstall.swf",
                   12217:                          "$topdir/scripts/",
                   12218:                          "$topdir/scripts/config_xml.js",
                   12219:                          "$topdir/scripts/handlebars.js",
                   12220:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12221:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12222:                          "$topdir/scripts/modernizr.js",
                   12223:                          "$topdir/scripts/player-min.js",
                   12224:                          "$topdir/scripts/swfobject.js",
                   12225:                          "$topdir/skins/",
                   12226:                          "$topdir/skins/configuration_express.xml",
                   12227:                          "$topdir/skins/express_show/",
                   12228:                          "$topdir/skins/express_show/player-min.css",
                   12229:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  12230:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12231:                          "$topdir/$topdir.mp4",
                   12232:                          "$topdir/$topdir\_config.xml",
                   12233:                          "$topdir/$topdir\_controller.swf",
                   12234:                          "$topdir/$topdir\_embed.css",
                   12235:                          "$topdir/$topdir\_First_Frame.png",
                   12236:                          "$topdir/$topdir\_player.html",
                   12237:                          "$topdir/$topdir\_Thumbnails.png",
                   12238:                          "$topdir/playerProductInstall.swf",
                   12239:                          "$topdir/scripts/",
                   12240:                          "$topdir/scripts/config_xml.js",
                   12241:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12242:                          "$topdir/skins/",
                   12243:                          "$topdir/skins/configuration_express.xml",
                   12244:                          "$topdir/skins/express_show/",
                   12245:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12246:                          "$topdir/skins/express_show/spritesheet.png",
                   12247:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  12248:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12249:         if (@diffs == 0) {
1.1164    raeburn  12250:             $is_camtasia = 6;
                   12251:         } else {
1.1197    raeburn  12252:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  12253:             if (@diffs == 0) {
                   12254:                 $is_camtasia = 8;
1.1197    raeburn  12255:             } else {
                   12256:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12257:                 if (@diffs == 0) {
                   12258:                     $is_camtasia = 8;
                   12259:                 }
1.1164    raeburn  12260:             }
1.1067    raeburn  12261:         }
                   12262:     }
                   12263:     my $output;
                   12264:     if ($is_camtasia) {
                   12265:         $output = <<"ENDCAM";
                   12266: <script type="text/javascript" language="Javascript">
                   12267: // <![CDATA[
                   12268: 
                   12269: function camtasiaToggle() {
                   12270:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12271:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  12272:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12273:                 document.getElementById('camtasia_titles').style.display='block';
                   12274:             } else {
                   12275:                 document.getElementById('camtasia_titles').style.display='none';
                   12276:             }
                   12277:         }
                   12278:     }
                   12279:     return;
                   12280: }
                   12281: 
                   12282: // ]]>
                   12283: </script>
                   12284: <p>$lt{'camt'}</p>
                   12285: ENDCAM
1.1065    raeburn  12286:     } else {
1.1067    raeburn  12287:         $output = '<p>'.$lt{'this'};
                   12288:         if ($info eq '') {
                   12289:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12290:         } else {
                   12291:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12292:                        '<div><pre>'.$info.'</pre></div>';
                   12293:         }
1.1065    raeburn  12294:     }
1.1067    raeburn  12295:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12296:     my $duplicates;
                   12297:     my $num = 0;
                   12298:     if (ref($dirlist) eq 'ARRAY') {
                   12299:         foreach my $item (@{$dirlist}) {
                   12300:             if (ref($item) eq 'ARRAY') {
                   12301:                 if (exists($toplevel{$item->[0]})) {
                   12302:                     $duplicates .= 
                   12303:                         &start_data_table_row().
                   12304:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12305:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12306:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12307:                         'value="1" />'.&mt('Yes').'</label>'.
                   12308:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12309:                         '<td>'.$item->[0].'</td>';
                   12310:                     if ($item->[2]) {
                   12311:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12312:                     } else {
                   12313:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12314:                     }
                   12315:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12316:                                    '<td>'.
                   12317:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12318:                                    '</td>'.
                   12319:                                    &end_data_table_row();
                   12320:                     $num ++;
                   12321:                 }
                   12322:             }
                   12323:         }
                   12324:     }
                   12325:     my $itemcount;
                   12326:     if (@paths > 0) {
                   12327:         $itemcount = scalar(@paths);
                   12328:     } else {
                   12329:         $itemcount = 1;
                   12330:     }
1.1067    raeburn  12331:     if ($is_camtasia) {
                   12332:         $output .= $lt{'auto'}.'<br />'.
                   12333:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  12334:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12335:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12336:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12337:                    $lt{'no'}.'</label></span><br />'.
                   12338:                    '<div id="camtasia_titles" style="display:block">'.
                   12339:                    &Apache::lonhtmlcommon::start_pick_box().
                   12340:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12341:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12342:                    &Apache::lonhtmlcommon::row_closure().
                   12343:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12344:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12345:                    &Apache::lonhtmlcommon::row_closure(1).
                   12346:                    &Apache::lonhtmlcommon::end_pick_box().
                   12347:                    '</div>';
                   12348:     }
1.1065    raeburn  12349:     $output .= 
                   12350:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12351:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12352:         "\n";
1.1065    raeburn  12353:     if ($duplicates ne '') {
                   12354:         $output .= '<p><span class="LC_warning">'.
                   12355:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12356:                    &start_data_table().
                   12357:                    &start_data_table_header_row().
                   12358:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12359:                    '<th>'.&mt('Name').'</th>'.
                   12360:                    '<th>'.&mt('Type').'</th>'.
                   12361:                    '<th>'.&mt('Size').'</th>'.
                   12362:                    '<th>'.&mt('Last modified').'</th>'.
                   12363:                    &end_data_table_header_row().
                   12364:                    $duplicates.
                   12365:                    &end_data_table().
                   12366:                    '</p>';
                   12367:     }
1.1067    raeburn  12368:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12369:     if (ref($hiddenelements) eq 'HASH') {
                   12370:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12371:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12372:         }
                   12373:     }
                   12374:     $output .= <<"END";
1.1067    raeburn  12375: <br />
1.1053    raeburn  12376: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12377: </form>
                   12378: $noextract
                   12379: END
                   12380:     return $output;
                   12381: }
                   12382: 
1.1065    raeburn  12383: sub decompression_utility {
                   12384:     my ($program) = @_;
                   12385:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12386:     my $location;
                   12387:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12388:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12389:                          '/usr/sbin/') {
                   12390:             if (-x $dir.$program) {
                   12391:                 $location = $dir.$program;
                   12392:                 last;
                   12393:             }
                   12394:         }
                   12395:     }
                   12396:     return $location;
                   12397: }
                   12398: 
                   12399: sub list_archive_contents {
                   12400:     my ($file,$pathsref) = @_;
                   12401:     my (@cmd,$output);
                   12402:     my $needsregexp;
                   12403:     if ($file =~ /\.zip$/) {
                   12404:         @cmd = (&decompression_utility('unzip'),"-l");
                   12405:         $needsregexp = 1;
                   12406:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12407:              ($file =~ /\.tgz$/)) {
                   12408:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12409:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12410:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12411:     } elsif ($file =~ m|\.tar$|) {
                   12412:         @cmd = (&decompression_utility('tar'),"-tf");
                   12413:     }
                   12414:     if (@cmd) {
                   12415:         undef($!);
                   12416:         undef($@);
                   12417:         if (open(my $fh,"-|", @cmd, $file)) {
                   12418:             while (my $line = <$fh>) {
                   12419:                 $output .= $line;
                   12420:                 chomp($line);
                   12421:                 my $item;
                   12422:                 if ($needsregexp) {
                   12423:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12424:                 } else {
                   12425:                     $item = $line;
                   12426:                 }
                   12427:                 if ($item ne '') {
                   12428:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12429:                         push(@{$pathsref},$item);
                   12430:                     } 
                   12431:                 }
                   12432:             }
                   12433:             close($fh);
                   12434:         }
                   12435:     }
                   12436:     return $output;
                   12437: }
                   12438: 
1.1053    raeburn  12439: sub decompress_uploaded_file {
                   12440:     my ($file,$dir) = @_;
                   12441:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12442:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12443:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12444:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12445:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12446:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12447:     my $decompressed = $env{'cgi.decompressed'};
                   12448:     &Apache::lonnet::delenv('cgi.file');
                   12449:     &Apache::lonnet::delenv('cgi.dir');
                   12450:     &Apache::lonnet::delenv('cgi.decompressed');
                   12451:     return ($decompressed,$result);
                   12452: }
                   12453: 
1.1055    raeburn  12454: sub process_decompression {
                   12455:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   12456:     my ($dir,$error,$warning,$output);
1.1180    raeburn  12457:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   12458:         $error = &mt('Filename not a supported archive file type.').
                   12459:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12460:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12461:     } else {
                   12462:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12463:         if ($docuhome eq 'no_host') {
                   12464:             $error = &mt('Could not determine home server for course.');
                   12465:         } else {
                   12466:             my @ids=&Apache::lonnet::current_machine_ids();
                   12467:             my $currdir = "$dir_root/$destination";
                   12468:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12469:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12470:                        "$dir_root/$destination";
                   12471:             } else {
                   12472:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12473:                        "$dir_root/$docudom/$docuname/$destination";
                   12474:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12475:                     $error = &mt('Archive file not found.');
                   12476:                 }
                   12477:             }
1.1065    raeburn  12478:             my (@to_overwrite,@to_skip);
                   12479:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12480:                 my $total = $env{'form.archive_overwrite_total'};
                   12481:                 for (my $i=0; $i<$total; $i++) {
                   12482:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12483:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12484:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12485:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12486:                     }
                   12487:                 }
                   12488:             }
                   12489:             my $numskip = scalar(@to_skip);
                   12490:             if (($numskip > 0) && 
                   12491:                 ($numskip == $env{'form.archive_itemcount'})) {
                   12492:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12493:             } elsif ($dir eq '') {
1.1055    raeburn  12494:                 $error = &mt('Directory containing archive file unavailable.');
                   12495:             } elsif (!$error) {
1.1065    raeburn  12496:                 my ($decompressed,$display);
                   12497:                 if ($numskip > 0) {
                   12498:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12499:                     mkdir("$dir/$tempdir",0755);
                   12500:                     system("mv $dir/$file $dir/$tempdir/$file");
                   12501:                     ($decompressed,$display) = 
                   12502:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   12503:                     foreach my $item (@to_skip) {
                   12504:                         if (($item ne '') && ($item !~ /\.\./)) {
                   12505:                             if (-f "$dir/$tempdir/$item") { 
                   12506:                                 unlink("$dir/$tempdir/$item");
                   12507:                             } elsif (-d "$dir/$tempdir/$item") {
                   12508:                                 system("rm -rf $dir/$tempdir/$item");
                   12509:                             }
                   12510:                         }
                   12511:                     }
                   12512:                     system("mv $dir/$tempdir/* $dir");
                   12513:                     rmdir("$dir/$tempdir");   
                   12514:                 } else {
                   12515:                     ($decompressed,$display) = 
                   12516:                         &decompress_uploaded_file($file,$dir);
                   12517:                 }
1.1055    raeburn  12518:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12519:                     $output = '<p class="LC_info">'.
                   12520:                               &mt('Files extracted successfully from archive.').
                   12521:                               '</p>'."\n";
1.1055    raeburn  12522:                     my ($warning,$result,@contents);
                   12523:                     my ($newdirlistref,$newlisterror) =
                   12524:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12525:                                                  $docuname,1);
                   12526:                     my (%is_dir,%changes,@newitems);
                   12527:                     my $dirptr = 16384;
1.1065    raeburn  12528:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12529:                         foreach my $dir_line (@{$newdirlistref}) {
                   12530:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  12531:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   12532:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  12533:                                 push(@newitems,$item);
                   12534:                                 if ($dirptr&$testdir) {
                   12535:                                     $is_dir{$item} = 1;
                   12536:                                 }
                   12537:                                 $changes{$item} = 1;
                   12538:                             }
                   12539:                         }
                   12540:                     }
                   12541:                     if (keys(%changes) > 0) {
                   12542:                         foreach my $item (sort(@newitems)) {
                   12543:                             if ($changes{$item}) {
                   12544:                                 push(@contents,$item);
                   12545:                             }
                   12546:                         }
                   12547:                     }
                   12548:                     if (@contents > 0) {
1.1067    raeburn  12549:                         my $wantform;
                   12550:                         unless ($env{'form.autoextract_camtasia'}) {
                   12551:                             $wantform = 1;
                   12552:                         }
1.1056    raeburn  12553:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12554:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12555:                                                                 $currdir,\%is_dir,
                   12556:                                                                 \%children,\%parent,
1.1056    raeburn  12557:                                                                 \@contents,\%dirorder,
                   12558:                                                                 \%titles,$wantform);
1.1055    raeburn  12559:                         if ($datatable ne '') {
                   12560:                             $output .= &archive_options_form('decompressed',$datatable,
                   12561:                                                              $count,$hiddenelem);
1.1065    raeburn  12562:                             my $startcount = 6;
1.1055    raeburn  12563:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12564:                                                            \%titles,\%children);
1.1055    raeburn  12565:                         }
1.1067    raeburn  12566:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  12567:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12568:                             my %displayed;
                   12569:                             my $total = 1;
                   12570:                             $env{'form.archive_directory'} = [];
                   12571:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12572:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12573:                                 $path =~ s{/$}{};
                   12574:                                 my $item;
                   12575:                                 if ($path ne '') {
                   12576:                                     $item = "$path/$titles{$i}";
                   12577:                                 } else {
                   12578:                                     $item = $titles{$i};
                   12579:                                 }
                   12580:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12581:                                 if ($item eq $contents[0]) {
                   12582:                                     push(@{$env{'form.archive_directory'}},$i);
                   12583:                                     $env{'form.archive_'.$i} = 'display';
                   12584:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12585:                                     $displayed{'folder'} = $i;
1.1164    raeburn  12586:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12587:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  12588:                                     $env{'form.archive_'.$i} = 'display';
                   12589:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12590:                                     $displayed{'web'} = $i;
                   12591:                                 } else {
1.1164    raeburn  12592:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12593:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12594:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12595:                                         push(@{$env{'form.archive_directory'}},$i);
                   12596:                                     }
                   12597:                                     $env{'form.archive_'.$i} = 'dependency';
                   12598:                                 }
                   12599:                                 $total ++;
                   12600:                             }
                   12601:                             for (my $i=1; $i<$total; $i++) {
                   12602:                                 next if ($i == $displayed{'web'});
                   12603:                                 next if ($i == $displayed{'folder'});
                   12604:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12605:                             }
                   12606:                             $env{'form.phase'} = 'decompress_cleanup';
                   12607:                             $env{'form.archivedelete'} = 1;
                   12608:                             $env{'form.archive_count'} = $total-1;
                   12609:                             $output .=
                   12610:                                 &process_extracted_files('coursedocs',$docudom,
                   12611:                                                          $docuname,$destination,
                   12612:                                                          $dir_root,$hiddenelem);
                   12613:                         }
1.1055    raeburn  12614:                     } else {
                   12615:                         $warning = &mt('No new items extracted from archive file.');
                   12616:                     }
                   12617:                 } else {
                   12618:                     $output = $display;
                   12619:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12620:                 }
                   12621:             }
                   12622:         }
                   12623:     }
                   12624:     if ($error) {
                   12625:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12626:                    $error.'</p>'."\n";
                   12627:     }
                   12628:     if ($warning) {
                   12629:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12630:     }
                   12631:     return $output;
                   12632: }
                   12633: 
                   12634: sub get_extracted {
1.1056    raeburn  12635:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12636:         $titles,$wantform) = @_;
1.1055    raeburn  12637:     my $count = 0;
                   12638:     my $depth = 0;
                   12639:     my $datatable;
1.1056    raeburn  12640:     my @hierarchy;
1.1055    raeburn  12641:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12642:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12643:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12644:     foreach my $item (@{$contents}) {
                   12645:         $count ++;
1.1056    raeburn  12646:         @{$dirorder->{$count}} = @hierarchy;
                   12647:         $titles->{$count} = $item;
1.1055    raeburn  12648:         &archive_hierarchy($depth,$count,$parent,$children);
                   12649:         if ($wantform) {
                   12650:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12651:                                        $currdir,$depth,$count);
                   12652:         }
                   12653:         if ($is_dir->{$item}) {
                   12654:             $depth ++;
1.1056    raeburn  12655:             push(@hierarchy,$count);
                   12656:             $parent->{$depth} = $count;
1.1055    raeburn  12657:             $datatable .=
                   12658:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12659:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12660:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12661:             $depth --;
1.1056    raeburn  12662:             pop(@hierarchy);
1.1055    raeburn  12663:         }
                   12664:     }
                   12665:     return ($count,$datatable);
                   12666: }
                   12667: 
                   12668: sub recurse_extracted_archive {
1.1056    raeburn  12669:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12670:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12671:     my $result='';
1.1056    raeburn  12672:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12673:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12674:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12675:         return $result;
                   12676:     }
                   12677:     my $dirptr = 16384;
                   12678:     my ($newdirlistref,$newlisterror) =
                   12679:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12680:     if (ref($newdirlistref) eq 'ARRAY') {
                   12681:         foreach my $dir_line (@{$newdirlistref}) {
                   12682:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12683:             unless ($item =~ /^\.+$/) {
                   12684:                 $$count ++;
1.1056    raeburn  12685:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12686:                 $titles->{$$count} = $item;
1.1055    raeburn  12687:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12688: 
1.1055    raeburn  12689:                 my $is_dir;
                   12690:                 if ($dirptr&$testdir) {
                   12691:                     $is_dir = 1;
                   12692:                 }
                   12693:                 if ($wantform) {
                   12694:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12695:                 }
                   12696:                 if ($is_dir) {
                   12697:                     $$depth ++;
1.1056    raeburn  12698:                     push(@{$hierarchy},$$count);
                   12699:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12700:                     $result .=
                   12701:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12702:                                                    $docuname,$depth,$count,
1.1056    raeburn  12703:                                                    $hierarchy,$dirorder,$children,
                   12704:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12705:                     $$depth --;
1.1056    raeburn  12706:                     pop(@{$hierarchy});
1.1055    raeburn  12707:                 }
                   12708:             }
                   12709:         }
                   12710:     }
                   12711:     return $result;
                   12712: }
                   12713: 
                   12714: sub archive_hierarchy {
                   12715:     my ($depth,$count,$parent,$children) =@_;
                   12716:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12717:         if (exists($parent->{$depth})) {
                   12718:              $children->{$parent->{$depth}} .= $count.':';
                   12719:         }
                   12720:     }
                   12721:     return;
                   12722: }
                   12723: 
                   12724: sub archive_row {
                   12725:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12726:     my ($name) = ($item =~ m{([^/]+)$});
                   12727:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12728:                                        'display'    => 'Add as file',
1.1055    raeburn  12729:                                        'dependency' => 'Include as dependency',
                   12730:                                        'discard'    => 'Discard',
                   12731:                                       );
                   12732:     if ($is_dir) {
1.1059    raeburn  12733:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12734:     }
1.1056    raeburn  12735:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12736:     my $offset = 0;
1.1055    raeburn  12737:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12738:         $offset ++;
1.1065    raeburn  12739:         if ($action ne 'display') {
                   12740:             $offset ++;
                   12741:         }  
1.1055    raeburn  12742:         $output .= '<td><span class="LC_nobreak">'.
                   12743:                    '<label><input type="radio" name="archive_'.$count.
                   12744:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12745:         my $text = $choices{$action};
                   12746:         if ($is_dir) {
                   12747:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12748:             if ($action eq 'display') {
1.1059    raeburn  12749:                 $text = &mt('Add as folder');
1.1055    raeburn  12750:             }
1.1056    raeburn  12751:         } else {
                   12752:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12753: 
                   12754:         }
                   12755:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12756:         if ($action eq 'dependency') {
                   12757:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12758:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12759:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12760:                        '<option value=""></option>'."\n".
                   12761:                        '</select>'."\n".
                   12762:                        '</div>';
1.1059    raeburn  12763:         } elsif ($action eq 'display') {
                   12764:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12765:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12766:                        '</div>';
1.1055    raeburn  12767:         }
1.1056    raeburn  12768:         $output .= '</td>';
1.1055    raeburn  12769:     }
                   12770:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12771:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12772:     for (my $i=0; $i<$depth; $i++) {
                   12773:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12774:     }
                   12775:     if ($is_dir) {
                   12776:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12777:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12778:     } else {
                   12779:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12780:     }
                   12781:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12782:                &end_data_table_row();
                   12783:     return $output;
                   12784: }
                   12785: 
                   12786: sub archive_options_form {
1.1065    raeburn  12787:     my ($form,$display,$count,$hiddenelem) = @_;
                   12788:     my %lt = &Apache::lonlocal::texthash(
                   12789:                perm => 'Permanently remove archive file?',
                   12790:                hows => 'How should each extracted item be incorporated in the course?',
                   12791:                cont => 'Content actions for all',
                   12792:                addf => 'Add as folder/file',
                   12793:                incd => 'Include as dependency for a displayed file',
                   12794:                disc => 'Discard',
                   12795:                no   => 'No',
                   12796:                yes  => 'Yes',
                   12797:                save => 'Save',
                   12798:     );
                   12799:     my $output = <<"END";
                   12800: <form name="$form" method="post" action="">
                   12801: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12802: <label>
                   12803:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12804: </label>
                   12805: &nbsp;
                   12806: <label>
                   12807:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12808: </span>
                   12809: </p>
                   12810: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12811: <br />$lt{'hows'}
                   12812: <div class="LC_columnSection">
                   12813:   <fieldset>
                   12814:     <legend>$lt{'cont'}</legend>
                   12815:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12816:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12817:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12818:   </fieldset>
                   12819: </div>
                   12820: END
                   12821:     return $output.
1.1055    raeburn  12822:            &start_data_table()."\n".
1.1065    raeburn  12823:            $display."\n".
1.1055    raeburn  12824:            &end_data_table()."\n".
                   12825:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12826:            $hiddenelem.
1.1065    raeburn  12827:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12828:            '</form>';
                   12829: }
                   12830: 
                   12831: sub archive_javascript {
1.1056    raeburn  12832:     my ($startcount,$numitems,$titles,$children) = @_;
                   12833:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12834:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12835:     my $scripttag = <<START;
                   12836: <script type="text/javascript">
                   12837: // <![CDATA[
                   12838: 
                   12839: function checkAll(form,prefix) {
                   12840:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12841:     for (var i=0; i < form.elements.length; i++) {
                   12842:         var id = form.elements[i].id;
                   12843:         if ((id != '') && (id != undefined)) {
                   12844:             if (idstr.test(id)) {
                   12845:                 if (form.elements[i].type == 'radio') {
                   12846:                     form.elements[i].checked = true;
1.1056    raeburn  12847:                     var nostart = i-$startcount;
1.1059    raeburn  12848:                     var offset = nostart%7;
                   12849:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12850:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12851:                 }
                   12852:             }
                   12853:         }
                   12854:     }
                   12855: }
                   12856: 
                   12857: function propagateCheck(form,count) {
                   12858:     if (count > 0) {
1.1059    raeburn  12859:         var startelement = $startcount + ((count-1) * 7);
                   12860:         for (var j=1; j<6; j++) {
                   12861:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12862:                 var item = startelement + j; 
                   12863:                 if (form.elements[item].type == 'radio') {
                   12864:                     if (form.elements[item].checked) {
                   12865:                         containerCheck(form,count,j);
                   12866:                         break;
                   12867:                     }
1.1055    raeburn  12868:                 }
                   12869:             }
                   12870:         }
                   12871:     }
                   12872: }
                   12873: 
                   12874: numitems = $numitems
1.1056    raeburn  12875: var titles = new Array(numitems);
                   12876: var parents = new Array(numitems);
1.1055    raeburn  12877: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12878:     parents[i] = new Array;
1.1055    raeburn  12879: }
1.1059    raeburn  12880: var maintitle = '$maintitle';
1.1055    raeburn  12881: 
                   12882: START
                   12883: 
1.1056    raeburn  12884:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12885:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12886:         for (my $i=0; $i<@contents; $i ++) {
                   12887:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12888:         }
                   12889:     }
                   12890: 
1.1056    raeburn  12891:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12892:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12893:     }
                   12894: 
1.1055    raeburn  12895:     $scripttag .= <<END;
                   12896: 
                   12897: function containerCheck(form,count,offset) {
                   12898:     if (count > 0) {
1.1056    raeburn  12899:         dependencyCheck(form,count,offset);
1.1059    raeburn  12900:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12901:         form.elements[item].checked = true;
                   12902:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12903:             if (parents[count].length > 0) {
                   12904:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12905:                     containerCheck(form,parents[count][j],offset);
                   12906:                 }
                   12907:             }
                   12908:         }
                   12909:     }
                   12910: }
                   12911: 
                   12912: function dependencyCheck(form,count,offset) {
                   12913:     if (count > 0) {
1.1059    raeburn  12914:         var chosen = (offset+$startcount)+7*(count-1);
                   12915:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12916:         var currtype = form.elements[depitem].type;
                   12917:         if (form.elements[chosen].value == 'dependency') {
                   12918:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12919:             form.elements[depitem].options.length = 0;
                   12920:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  12921:             for (var i=1; i<=numitems; i++) {
                   12922:                 if (i == count) {
                   12923:                     continue;
                   12924:                 }
1.1059    raeburn  12925:                 var startelement = $startcount + (i-1) * 7;
                   12926:                 for (var j=1; j<6; j++) {
                   12927:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12928:                         var item = startelement + j;
                   12929:                         if (form.elements[item].type == 'radio') {
                   12930:                             if (form.elements[item].checked) {
                   12931:                                 if (form.elements[item].value == 'display') {
                   12932:                                     var n = form.elements[depitem].options.length;
                   12933:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12934:                                 }
                   12935:                             }
                   12936:                         }
                   12937:                     }
                   12938:                 }
                   12939:             }
                   12940:         } else {
                   12941:             document.getElementById('arc_depon_'+count).style.display='none';
                   12942:             form.elements[depitem].options.length = 0;
                   12943:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12944:         }
1.1059    raeburn  12945:         titleCheck(form,count,offset);
1.1056    raeburn  12946:     }
                   12947: }
                   12948: 
                   12949: function propagateSelect(form,count,offset) {
                   12950:     if (count > 0) {
1.1065    raeburn  12951:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12952:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12953:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12954:             if (parents[count].length > 0) {
                   12955:                 for (var j=0; j<parents[count].length; j++) {
                   12956:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12957:                 }
                   12958:             }
                   12959:         }
                   12960:     }
                   12961: }
1.1056    raeburn  12962: 
                   12963: function containerSelect(form,count,offset,picked) {
                   12964:     if (count > 0) {
1.1065    raeburn  12965:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12966:         if (form.elements[item].type == 'radio') {
                   12967:             if (form.elements[item].value == 'dependency') {
                   12968:                 if (form.elements[item+1].type == 'select-one') {
                   12969:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12970:                         if (form.elements[item+1].options[i].value == picked) {
                   12971:                             form.elements[item+1].selectedIndex = i;
                   12972:                             break;
                   12973:                         }
                   12974:                     }
                   12975:                 }
                   12976:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12977:                     if (parents[count].length > 0) {
                   12978:                         for (var j=0; j<parents[count].length; j++) {
                   12979:                             containerSelect(form,parents[count][j],offset,picked);
                   12980:                         }
                   12981:                     }
                   12982:                 }
                   12983:             }
                   12984:         }
                   12985:     }
                   12986: }
                   12987: 
1.1059    raeburn  12988: function titleCheck(form,count,offset) {
                   12989:     if (count > 0) {
                   12990:         var chosen = (offset+$startcount)+7*(count-1);
                   12991:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12992:         var currtype = form.elements[depitem].type;
                   12993:         if (form.elements[chosen].value == 'display') {
                   12994:             document.getElementById('arc_title_'+count).style.display='block';
                   12995:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12996:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12997:             }
                   12998:         } else {
                   12999:             document.getElementById('arc_title_'+count).style.display='none';
                   13000:             if (currtype == 'text') { 
                   13001:                 document.getElementById('archive_title_'+count).value='';
                   13002:             }
                   13003:         }
                   13004:     }
                   13005:     return;
                   13006: }
                   13007: 
1.1055    raeburn  13008: // ]]>
                   13009: </script>
                   13010: END
                   13011:     return $scripttag;
                   13012: }
                   13013: 
                   13014: sub process_extracted_files {
1.1067    raeburn  13015:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13016:     my $numitems = $env{'form.archive_count'};
                   13017:     return unless ($numitems);
                   13018:     my @ids=&Apache::lonnet::current_machine_ids();
                   13019:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13020:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13021:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13022:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13023:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13024:         $pathtocheck = "$dir_root/$destination";
                   13025:         $dir = $dir_root;
                   13026:         $ishome = 1;
                   13027:     } else {
                   13028:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13029:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   13030:         $dir = "$dir_root/$docudom/$docuname";    
                   13031:     }
                   13032:     my $currdir = "$dir_root/$destination";
                   13033:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13034:     if ($env{'form.folderpath'}) {
                   13035:         my @items = split('&',$env{'form.folderpath'});
                   13036:         $folders{'0'} = $items[-2];
1.1099    raeburn  13037:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13038:             $containers{'0'}='page';
                   13039:         } else {  
                   13040:             $containers{'0'}='sequence';
                   13041:         }
1.1055    raeburn  13042:     }
                   13043:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13044:     if ($numitems) {
                   13045:         for (my $i=1; $i<=$numitems; $i++) {
                   13046:             my $path = $env{'form.archive_content_'.$i};
                   13047:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13048:                 my $item = $1;
                   13049:                 $toplevelitems{$item} = $i;
                   13050:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13051:                     $is_dir{$item} = 1;
                   13052:                 }
                   13053:             }
                   13054:         }
                   13055:     }
1.1067    raeburn  13056:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13057:     if (keys(%toplevelitems) > 0) {
                   13058:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13059:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13060:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13061:     }
1.1066    raeburn  13062:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13063:     if ($numitems) {
                   13064:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  13065:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13066:             my $path = $env{'form.archive_content_'.$i};
                   13067:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13068:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13069:                     if ($prefix ne '' && $path ne '') {
                   13070:                         if (-e $prefix.$path) {
1.1066    raeburn  13071:                             if ((@archdirs > 0) && 
                   13072:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13073:                                 $todeletedir{$prefix.$path} = 1;
                   13074:                             } else {
                   13075:                                 $todelete{$prefix.$path} = 1;
                   13076:                             }
1.1055    raeburn  13077:                         }
                   13078:                     }
                   13079:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13080:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13081:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13082:                     $docstitle = $env{'form.archive_title_'.$i};
                   13083:                     if ($docstitle eq '') {
                   13084:                         $docstitle = $title;
                   13085:                     }
1.1055    raeburn  13086:                     $outer = 0;
1.1056    raeburn  13087:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13088:                         if (@{$dirorder{$i}} > 0) {
                   13089:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13090:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13091:                                     $outer = $item;
                   13092:                                     last;
                   13093:                                 }
                   13094:                             }
                   13095:                         }
                   13096:                     }
                   13097:                     my ($errtext,$fatal) = 
                   13098:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13099:                                                '/'.$folders{$outer}.'.'.
                   13100:                                                $containers{$outer});
                   13101:                     next if ($fatal);
                   13102:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13103:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13104:                             $mapinner{$i} = time;
1.1055    raeburn  13105:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13106:                             $containers{$i} = 'sequence';
                   13107:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13108:                                       $folders{$i}.'.'.$containers{$i};
                   13109:                             my $newidx = &LONCAPA::map::getresidx();
                   13110:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13111:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13112:                             push(@LONCAPA::map::order,$newidx);
                   13113:                             my ($outtext,$errtext) =
                   13114:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13115:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13116:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13117:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13118:                             unless ($errtext) {
                   13119:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   13120:                             }
1.1055    raeburn  13121:                         }
                   13122:                     } else {
                   13123:                         if ($context eq 'coursedocs') {
                   13124:                             my $newidx=&LONCAPA::map::getresidx();
                   13125:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13126:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13127:                                       $title;
                   13128:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13129:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   13130:                             }
                   13131:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13132:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13133:                             }
                   13134:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13135:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  13136:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  13137:                                 unless ($ishome) {
                   13138:                                     my $fetch = "$newdest{$i}/$title";
                   13139:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13140:                                     $prompttofetch{$fetch} = 1;
                   13141:                                 }
1.1055    raeburn  13142:                             }
                   13143:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13144:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13145:                             push(@LONCAPA::map::order, $newidx);
                   13146:                             my ($outtext,$errtext)=
                   13147:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13148:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13149:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  13150:                             unless ($errtext) {
                   13151:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13152:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   13153:                                 }
                   13154:                             }
1.1055    raeburn  13155:                         }
                   13156:                     }
1.1086    raeburn  13157:                 }
                   13158:             } else {
                   13159:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   13160:             }
                   13161:         }
                   13162:         for (my $i=1; $i<=$numitems; $i++) {
                   13163:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13164:             my $path = $env{'form.archive_content_'.$i};
                   13165:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13166:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13167:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13168:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13169:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13170:                         my ($itemidx,$fullpath,$relpath);
                   13171:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13172:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13173:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  13174:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13175:                                     $itemidx = $j;
1.1056    raeburn  13176:                                 }
                   13177:                             }
1.1086    raeburn  13178:                         }
                   13179:                         if ($itemidx eq '') {
                   13180:                             $itemidx =  0;
                   13181:                         } 
                   13182:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13183:                             if ($mapinner{$referrer{$i}}) {
                   13184:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13185:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13186:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13187:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13188:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13189:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13190:                                             if (!-e $fullpath) {
                   13191:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13192:                                             }
                   13193:                                         }
1.1086    raeburn  13194:                                     } else {
                   13195:                                         last;
1.1056    raeburn  13196:                                     }
1.1086    raeburn  13197:                                 }
                   13198:                             }
                   13199:                         } elsif ($newdest{$referrer{$i}}) {
                   13200:                             $fullpath = $newdest{$referrer{$i}};
                   13201:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13202:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13203:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13204:                                     last;
                   13205:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13206:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13207:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13208:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13209:                                         if (!-e $fullpath) {
                   13210:                                             mkdir($fullpath,0755);
1.1056    raeburn  13211:                                         }
                   13212:                                     }
1.1086    raeburn  13213:                                 } else {
                   13214:                                     last;
1.1056    raeburn  13215:                                 }
1.1055    raeburn  13216:                             }
                   13217:                         }
1.1086    raeburn  13218:                         if ($fullpath ne '') {
                   13219:                             if (-e "$prefix$path") {
                   13220:                                 system("mv $prefix$path $fullpath/$title");
                   13221:                             }
                   13222:                             if (-e "$fullpath/$title") {
                   13223:                                 my $showpath;
                   13224:                                 if ($relpath ne '') {
                   13225:                                     $showpath = "$relpath/$title";
                   13226:                                 } else {
                   13227:                                     $showpath = "/$title";
                   13228:                                 } 
                   13229:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   13230:                             } 
                   13231:                             unless ($ishome) {
                   13232:                                 my $fetch = "$fullpath/$title";
                   13233:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   13234:                                 $prompttofetch{$fetch} = 1;
                   13235:                             }
                   13236:                         }
1.1055    raeburn  13237:                     }
1.1086    raeburn  13238:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13239:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   13240:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  13241:                 }
                   13242:             } else {
                   13243:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   13244:             }
                   13245:         }
                   13246:         if (keys(%todelete)) {
                   13247:             foreach my $key (keys(%todelete)) {
                   13248:                 unlink($key);
1.1066    raeburn  13249:             }
                   13250:         }
                   13251:         if (keys(%todeletedir)) {
                   13252:             foreach my $key (keys(%todeletedir)) {
                   13253:                 rmdir($key);
                   13254:             }
                   13255:         }
                   13256:         foreach my $dir (sort(keys(%is_dir))) {
                   13257:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13258:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13259:             }
                   13260:         }
1.1067    raeburn  13261:         if ($result ne '') {
                   13262:             $output .= '<ul>'."\n".
                   13263:                        $result."\n".
                   13264:                        '</ul>';
                   13265:         }
                   13266:         unless ($ishome) {
                   13267:             my $replicationfail;
                   13268:             foreach my $item (keys(%prompttofetch)) {
                   13269:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13270:                 unless ($fetchresult eq 'ok') {
                   13271:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13272:                 }
                   13273:             }
                   13274:             if ($replicationfail) {
                   13275:                 $output .= '<p class="LC_error">'.
                   13276:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13277:                            $replicationfail.
                   13278:                            '</ul></p>';
                   13279:             }
                   13280:         }
1.1055    raeburn  13281:     } else {
                   13282:         $warning = &mt('No items found in archive.');
                   13283:     }
                   13284:     if ($error) {
                   13285:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13286:                    $error.'</p>'."\n";
                   13287:     }
                   13288:     if ($warning) {
                   13289:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13290:     }
                   13291:     return $output;
                   13292: }
                   13293: 
1.1066    raeburn  13294: sub cleanup_empty_dirs {
                   13295:     my ($path) = @_;
                   13296:     if (($path ne '') && (-d $path)) {
                   13297:         if (opendir(my $dirh,$path)) {
                   13298:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13299:             my $numitems = 0;
                   13300:             foreach my $item (@dircontents) {
                   13301:                 if (-d "$path/$item") {
1.1111    raeburn  13302:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13303:                     if (-e "$path/$item") {
                   13304:                         $numitems ++;
                   13305:                     }
                   13306:                 } else {
                   13307:                     $numitems ++;
                   13308:                 }
                   13309:             }
                   13310:             if ($numitems == 0) {
                   13311:                 rmdir($path);
                   13312:             }
                   13313:             closedir($dirh);
                   13314:         }
                   13315:     }
                   13316:     return;
                   13317: }
                   13318: 
1.41      ng       13319: =pod
1.45      matthew  13320: 
1.1162    raeburn  13321: =item * &get_folder_hierarchy()
1.1068    raeburn  13322: 
                   13323: Provides hierarchy of names of folders/sub-folders containing the current
                   13324: item,
                   13325: 
                   13326: Inputs: 3
                   13327:      - $navmap - navmaps object
                   13328: 
                   13329:      - $map - url for map (either the trigger itself, or map containing
                   13330:                            the resource, which is the trigger).
                   13331: 
                   13332:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13333: 
                   13334: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13335: 
                   13336: =cut
                   13337: 
                   13338: sub get_folder_hierarchy {
                   13339:     my ($navmap,$map,$showitem) = @_;
                   13340:     my @pathitems;
                   13341:     if (ref($navmap)) {
                   13342:         my $mapres = $navmap->getResourceByUrl($map);
                   13343:         if (ref($mapres)) {
                   13344:             my $pcslist = $mapres->map_hierarchy();
                   13345:             if ($pcslist ne '') {
                   13346:                 my @pcs = split(/,/,$pcslist);
                   13347:                 foreach my $pc (@pcs) {
                   13348:                     if ($pc == 1) {
1.1129    raeburn  13349:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13350:                     } else {
                   13351:                         my $res = $navmap->getByMapPc($pc);
                   13352:                         if (ref($res)) {
                   13353:                             my $title = $res->compTitle();
                   13354:                             $title =~ s/\W+/_/g;
                   13355:                             if ($title ne '') {
                   13356:                                 push(@pathitems,$title);
                   13357:                             }
                   13358:                         }
                   13359:                     }
                   13360:                 }
                   13361:             }
1.1071    raeburn  13362:             if ($showitem) {
                   13363:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  13364:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13365:                 } else {
                   13366:                     my $maptitle = $mapres->compTitle();
                   13367:                     $maptitle =~ s/\W+/_/g;
                   13368:                     if ($maptitle ne '') {
                   13369:                         push(@pathitems,$maptitle);
                   13370:                     }
1.1068    raeburn  13371:                 }
                   13372:             }
                   13373:         }
                   13374:     }
                   13375:     return @pathitems;
                   13376: }
                   13377: 
                   13378: =pod
                   13379: 
1.1015    raeburn  13380: =item * &get_turnedin_filepath()
                   13381: 
                   13382: Determines path in a user's portfolio file for storage of files uploaded
                   13383: to a specific essayresponse or dropbox item.
                   13384: 
                   13385: Inputs: 3 required + 1 optional.
                   13386: $symb is symb for resource, $uname and $udom are for current user (required).
                   13387: $caller is optional (can be "submission", if routine is called when storing
                   13388: an upoaded file when "Submit Answer" button was pressed).
                   13389: 
                   13390: Returns array containing $path and $multiresp. 
                   13391: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13392: than one file upload item.  Callers of routine should append partid as a 
                   13393: subdirectory to $path in cases where $multiresp is 1.
                   13394: 
                   13395: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13396: 
                   13397: =cut
                   13398: 
                   13399: sub get_turnedin_filepath {
                   13400:     my ($symb,$uname,$udom,$caller) = @_;
                   13401:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13402:     my $turnindir;
                   13403:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13404:     $turnindir = $userhash{'turnindir'};
                   13405:     my ($path,$multiresp);
                   13406:     if ($turnindir eq '') {
                   13407:         if ($caller eq 'submission') {
                   13408:             $turnindir = &mt('turned in');
                   13409:             $turnindir =~ s/\W+/_/g;
                   13410:             my %newhash = (
                   13411:                             'turnindir' => $turnindir,
                   13412:                           );
                   13413:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13414:         }
                   13415:     }
                   13416:     if ($turnindir ne '') {
                   13417:         $path = '/'.$turnindir.'/';
                   13418:         my ($multipart,$turnin,@pathitems);
                   13419:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13420:         if (defined($navmap)) {
                   13421:             my $mapres = $navmap->getResourceByUrl($map);
                   13422:             if (ref($mapres)) {
                   13423:                 my $pcslist = $mapres->map_hierarchy();
                   13424:                 if ($pcslist ne '') {
                   13425:                     foreach my $pc (split(/,/,$pcslist)) {
                   13426:                         my $res = $navmap->getByMapPc($pc);
                   13427:                         if (ref($res)) {
                   13428:                             my $title = $res->compTitle();
                   13429:                             $title =~ s/\W+/_/g;
                   13430:                             if ($title ne '') {
1.1149    raeburn  13431:                                 if (($pc > 1) && (length($title) > 12)) {
                   13432:                                     $title = substr($title,0,12);
                   13433:                                 }
1.1015    raeburn  13434:                                 push(@pathitems,$title);
                   13435:                             }
                   13436:                         }
                   13437:                     }
                   13438:                 }
                   13439:                 my $maptitle = $mapres->compTitle();
                   13440:                 $maptitle =~ s/\W+/_/g;
                   13441:                 if ($maptitle ne '') {
1.1149    raeburn  13442:                     if (length($maptitle) > 12) {
                   13443:                         $maptitle = substr($maptitle,0,12);
                   13444:                     }
1.1015    raeburn  13445:                     push(@pathitems,$maptitle);
                   13446:                 }
                   13447:                 unless ($env{'request.state'} eq 'construct') {
                   13448:                     my $res = $navmap->getBySymb($symb);
                   13449:                     if (ref($res)) {
                   13450:                         my $partlist = $res->parts();
                   13451:                         my $totaluploads = 0;
                   13452:                         if (ref($partlist) eq 'ARRAY') {
                   13453:                             foreach my $part (@{$partlist}) {
                   13454:                                 my @types = $res->responseType($part);
                   13455:                                 my @ids = $res->responseIds($part);
                   13456:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13457:                                     if ($types[$i] eq 'essay') {
                   13458:                                         my $partid = $part.'_'.$ids[$i];
                   13459:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13460:                                             $totaluploads ++;
                   13461:                                         }
                   13462:                                     }
                   13463:                                 }
                   13464:                             }
                   13465:                             if ($totaluploads > 1) {
                   13466:                                 $multiresp = 1;
                   13467:                             }
                   13468:                         }
                   13469:                     }
                   13470:                 }
                   13471:             } else {
                   13472:                 return;
                   13473:             }
                   13474:         } else {
                   13475:             return;
                   13476:         }
                   13477:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13478:         $restitle =~ s/\W+/_/g;
                   13479:         if ($restitle eq '') {
                   13480:             $restitle = ($resurl =~ m{/[^/]+$});
                   13481:             if ($restitle eq '') {
                   13482:                 $restitle = time;
                   13483:             }
                   13484:         }
1.1149    raeburn  13485:         if (length($restitle) > 12) {
                   13486:             $restitle = substr($restitle,0,12);
                   13487:         }
1.1015    raeburn  13488:         push(@pathitems,$restitle);
                   13489:         $path .= join('/',@pathitems);
                   13490:     }
                   13491:     return ($path,$multiresp);
                   13492: }
                   13493: 
                   13494: =pod
                   13495: 
1.464     albertel 13496: =back
1.41      ng       13497: 
1.112     bowersj2 13498: =head1 CSV Upload/Handling functions
1.38      albertel 13499: 
1.41      ng       13500: =over 4
                   13501: 
1.648     raeburn  13502: =item * &upfile_store($r)
1.41      ng       13503: 
                   13504: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13505: needs $env{'form.upfile'}
1.41      ng       13506: returns $datatoken to be put into hidden field
                   13507: 
                   13508: =cut
1.31      albertel 13509: 
                   13510: sub upfile_store {
                   13511:     my $r=shift;
1.258     albertel 13512:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13513:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13514:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13515:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13516: 
1.258     albertel 13517:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   13518: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 13519:     {
1.158     raeburn  13520:         my $datafile = $r->dir_config('lonDaemons').
                   13521:                            '/tmp/'.$datatoken.'.tmp';
                   13522:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 13523:             print $fh $env{'form.upfile'};
1.158     raeburn  13524:             close($fh);
                   13525:         }
1.31      albertel 13526:     }
                   13527:     return $datatoken;
                   13528: }
                   13529: 
1.56      matthew  13530: =pod
                   13531: 
1.648     raeburn  13532: =item * &load_tmp_file($r)
1.41      ng       13533: 
                   13534: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 13535: needs $env{'form.datatoken'},
                   13536: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13537: 
                   13538: =cut
1.31      albertel 13539: 
                   13540: sub load_tmp_file {
                   13541:     my $r=shift;
                   13542:     my @studentdata=();
                   13543:     {
1.158     raeburn  13544:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 13545:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  13546:         if ( open(my $fh,"<$studentfile") ) {
                   13547:             @studentdata=<$fh>;
                   13548:             close($fh);
                   13549:         }
1.31      albertel 13550:     }
1.258     albertel 13551:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13552: }
                   13553: 
1.56      matthew  13554: =pod
                   13555: 
1.648     raeburn  13556: =item * &upfile_record_sep()
1.41      ng       13557: 
                   13558: Separate uploaded file into records
                   13559: returns array of records,
1.258     albertel 13560: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13561: 
                   13562: =cut
1.31      albertel 13563: 
                   13564: sub upfile_record_sep {
1.258     albertel 13565:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13566:     } else {
1.248     albertel 13567: 	my @records;
1.258     albertel 13568: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13569: 	    if ($line=~/^\s*$/) { next; }
                   13570: 	    push(@records,$line);
                   13571: 	}
                   13572: 	return @records;
1.31      albertel 13573:     }
                   13574: }
                   13575: 
1.56      matthew  13576: =pod
                   13577: 
1.648     raeburn  13578: =item * &record_sep($record)
1.41      ng       13579: 
1.258     albertel 13580: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13581: 
                   13582: =cut
                   13583: 
1.263     www      13584: sub takeleft {
                   13585:     my $index=shift;
                   13586:     return substr('0000'.$index,-4,4);
                   13587: }
                   13588: 
1.31      albertel 13589: sub record_sep {
                   13590:     my $record=shift;
                   13591:     my %components=();
1.258     albertel 13592:     if ($env{'form.upfiletype'} eq 'xml') {
                   13593:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13594:         my $i=0;
1.356     albertel 13595:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13596:             $field=~s/^(\"|\')//;
                   13597:             $field=~s/(\"|\')$//;
1.263     www      13598:             $components{&takeleft($i)}=$field;
1.31      albertel 13599:             $i++;
                   13600:         }
1.258     albertel 13601:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13602:         my $i=0;
1.356     albertel 13603:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13604:             $field=~s/^(\"|\')//;
                   13605:             $field=~s/(\"|\')$//;
1.263     www      13606:             $components{&takeleft($i)}=$field;
1.31      albertel 13607:             $i++;
                   13608:         }
                   13609:     } else {
1.561     www      13610:         my $separator=',';
1.480     banghart 13611:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13612:             $separator=';';
1.480     banghart 13613:         }
1.31      albertel 13614:         my $i=0;
1.561     www      13615: # the character we are looking for to indicate the end of a quote or a record 
                   13616:         my $looking_for=$separator;
                   13617: # do not add the characters to the fields
                   13618:         my $ignore=0;
                   13619: # we just encountered a separator (or the beginning of the record)
                   13620:         my $just_found_separator=1;
                   13621: # store the field we are working on here
                   13622:         my $field='';
                   13623: # work our way through all characters in record
                   13624:         foreach my $character ($record=~/(.)/g) {
                   13625:             if ($character eq $looking_for) {
                   13626:                if ($character ne $separator) {
                   13627: # Found the end of a quote, again looking for separator
                   13628:                   $looking_for=$separator;
                   13629:                   $ignore=1;
                   13630:                } else {
                   13631: # Found a separator, store away what we got
                   13632:                   $components{&takeleft($i)}=$field;
                   13633: 	          $i++;
                   13634:                   $just_found_separator=1;
                   13635:                   $ignore=0;
                   13636:                   $field='';
                   13637:                }
                   13638:                next;
                   13639:             }
                   13640: # single or double quotation marks after a separator indicate beginning of a quote
                   13641: # we are now looking for the end of the quote and need to ignore separators
                   13642:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13643:                $looking_for=$character;
                   13644:                next;
                   13645:             }
                   13646: # ignore would be true after we reached the end of a quote
                   13647:             if ($ignore) { next; }
                   13648:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13649:             $field.=$character;
                   13650:             $just_found_separator=0; 
1.31      albertel 13651:         }
1.561     www      13652: # catch the very last entry, since we never encountered the separator
                   13653:         $components{&takeleft($i)}=$field;
1.31      albertel 13654:     }
                   13655:     return %components;
                   13656: }
                   13657: 
1.144     matthew  13658: ######################################################
                   13659: ######################################################
                   13660: 
1.56      matthew  13661: =pod
                   13662: 
1.648     raeburn  13663: =item * &upfile_select_html()
1.41      ng       13664: 
1.144     matthew  13665: Return HTML code to select a file from the users machine and specify 
                   13666: the file type.
1.41      ng       13667: 
                   13668: =cut
                   13669: 
1.144     matthew  13670: ######################################################
                   13671: ######################################################
1.31      albertel 13672: sub upfile_select_html {
1.144     matthew  13673:     my %Types = (
                   13674:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13675:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13676:                  space => &mt('Space separated'),
                   13677:                  tab   => &mt('Tabulator separated'),
                   13678: #                 xml   => &mt('HTML/XML'),
                   13679:                  );
                   13680:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13681:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13682:     foreach my $type (sort(keys(%Types))) {
                   13683:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13684:     }
                   13685:     $Str .= "</select>\n";
                   13686:     return $Str;
1.31      albertel 13687: }
                   13688: 
1.301     albertel 13689: sub get_samples {
                   13690:     my ($records,$toget) = @_;
                   13691:     my @samples=({});
                   13692:     my $got=0;
                   13693:     foreach my $rec (@$records) {
                   13694: 	my %temp = &record_sep($rec);
                   13695: 	if (! grep(/\S/, values(%temp))) { next; }
                   13696: 	if (%temp) {
                   13697: 	    $samples[$got]=\%temp;
                   13698: 	    $got++;
                   13699: 	    if ($got == $toget) { last; }
                   13700: 	}
                   13701:     }
                   13702:     return \@samples;
                   13703: }
                   13704: 
1.144     matthew  13705: ######################################################
                   13706: ######################################################
                   13707: 
1.56      matthew  13708: =pod
                   13709: 
1.648     raeburn  13710: =item * &csv_print_samples($r,$records)
1.41      ng       13711: 
                   13712: Prints a table of sample values from each column uploaded $r is an
                   13713: Apache Request ref, $records is an arrayref from
                   13714: &Apache::loncommon::upfile_record_sep
                   13715: 
                   13716: =cut
                   13717: 
1.144     matthew  13718: ######################################################
                   13719: ######################################################
1.31      albertel 13720: sub csv_print_samples {
                   13721:     my ($r,$records) = @_;
1.662     bisitz   13722:     my $samples = &get_samples($records,5);
1.301     albertel 13723: 
1.594     raeburn  13724:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13725:               &start_data_table_header_row());
1.356     albertel 13726:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13727:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13728:     $r->print(&end_data_table_header_row());
1.301     albertel 13729:     foreach my $hash (@$samples) {
1.594     raeburn  13730: 	$r->print(&start_data_table_row());
1.356     albertel 13731: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13732: 	    $r->print('<td>');
1.356     albertel 13733: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13734: 	    $r->print('</td>');
                   13735: 	}
1.594     raeburn  13736: 	$r->print(&end_data_table_row());
1.31      albertel 13737:     }
1.594     raeburn  13738:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13739: }
                   13740: 
1.144     matthew  13741: ######################################################
                   13742: ######################################################
                   13743: 
1.56      matthew  13744: =pod
                   13745: 
1.648     raeburn  13746: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13747: 
                   13748: Prints a table to create associations between values and table columns.
1.144     matthew  13749: 
1.41      ng       13750: $r is an Apache Request ref,
                   13751: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13752: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13753: 
                   13754: =cut
                   13755: 
1.144     matthew  13756: ######################################################
                   13757: ######################################################
1.31      albertel 13758: sub csv_print_select_table {
                   13759:     my ($r,$records,$d) = @_;
1.301     albertel 13760:     my $i=0;
                   13761:     my $samples = &get_samples($records,1);
1.144     matthew  13762:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13763: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13764:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13765:               '<th>'.&mt('Column').'</th>'.
                   13766:               &end_data_table_header_row()."\n");
1.356     albertel 13767:     foreach my $array_ref (@$d) {
                   13768: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13769: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13770: 
1.875     bisitz   13771: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13772: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13773: 	$r->print('<option value="none"></option>');
1.356     albertel 13774: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13775: 	    $r->print('<option value="'.$sample.'"'.
                   13776:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13777:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13778: 	}
1.594     raeburn  13779: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13780: 	$i++;
                   13781:     }
1.594     raeburn  13782:     $r->print(&end_data_table());
1.31      albertel 13783:     $i--;
                   13784:     return $i;
                   13785: }
1.56      matthew  13786: 
1.144     matthew  13787: ######################################################
                   13788: ######################################################
                   13789: 
1.56      matthew  13790: =pod
1.31      albertel 13791: 
1.648     raeburn  13792: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13793: 
                   13794: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13795: 
                   13796: $r is an Apache Request ref,
                   13797: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13798: $d is an array of 2 element arrays (internal name, displayed name)
                   13799: 
                   13800: =cut
                   13801: 
1.144     matthew  13802: ######################################################
                   13803: ######################################################
1.31      albertel 13804: sub csv_samples_select_table {
                   13805:     my ($r,$records,$d) = @_;
                   13806:     my $i=0;
1.144     matthew  13807:     #
1.662     bisitz   13808:     my $max_samples = 5;
                   13809:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13810:     $r->print(&start_data_table().
                   13811:               &start_data_table_header_row().'<th>'.
                   13812:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13813:               &end_data_table_header_row());
1.301     albertel 13814: 
                   13815:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13816: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13817: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13818: 	foreach my $option (@$d) {
                   13819: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13820: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13821:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13822:                       $display.'</option>');
1.31      albertel 13823: 	}
                   13824: 	$r->print('</select></td><td>');
1.662     bisitz   13825: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13826: 	    if (defined($samples->[$line]{$key})) { 
                   13827: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13828: 	    }
                   13829: 	}
1.594     raeburn  13830: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13831: 	$i++;
                   13832:     }
1.594     raeburn  13833:     $r->print(&end_data_table());
1.31      albertel 13834:     $i--;
                   13835:     return($i);
1.115     matthew  13836: }
                   13837: 
1.144     matthew  13838: ######################################################
                   13839: ######################################################
                   13840: 
1.115     matthew  13841: =pod
                   13842: 
1.648     raeburn  13843: =item * &clean_excel_name($name)
1.115     matthew  13844: 
                   13845: Returns a replacement for $name which does not contain any illegal characters.
                   13846: 
                   13847: =cut
                   13848: 
1.144     matthew  13849: ######################################################
                   13850: ######################################################
1.115     matthew  13851: sub clean_excel_name {
                   13852:     my ($name) = @_;
                   13853:     $name =~ s/[:\*\?\/\\]//g;
                   13854:     if (length($name) > 31) {
                   13855:         $name = substr($name,0,31);
                   13856:     }
                   13857:     return $name;
1.25      albertel 13858: }
1.84      albertel 13859: 
1.85      albertel 13860: =pod
                   13861: 
1.648     raeburn  13862: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13863: 
                   13864: Returns either 1 or undef
                   13865: 
                   13866: 1 if the part is to be hidden, undef if it is to be shown
                   13867: 
                   13868: Arguments are:
                   13869: 
                   13870: $id the id of the part to be checked
                   13871: $symb, optional the symb of the resource to check
                   13872: $udom, optional the domain of the user to check for
                   13873: $uname, optional the username of the user to check for
                   13874: 
                   13875: =cut
1.84      albertel 13876: 
                   13877: sub check_if_partid_hidden {
                   13878:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13879:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13880: 					 $symb,$udom,$uname);
1.141     albertel 13881:     my $truth=1;
                   13882:     #if the string starts with !, then the list is the list to show not hide
                   13883:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13884:     my @hiddenlist=split(/,/,$hiddenparts);
                   13885:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13886: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13887:     }
1.141     albertel 13888:     return !$truth;
1.84      albertel 13889: }
1.127     matthew  13890: 
1.138     matthew  13891: 
                   13892: ############################################################
                   13893: ############################################################
                   13894: 
                   13895: =pod
                   13896: 
1.157     matthew  13897: =back 
                   13898: 
1.138     matthew  13899: =head1 cgi-bin script and graphing routines
                   13900: 
1.157     matthew  13901: =over 4
                   13902: 
1.648     raeburn  13903: =item * &get_cgi_id()
1.138     matthew  13904: 
                   13905: Inputs: none
                   13906: 
                   13907: Returns an id which can be used to pass environment variables
                   13908: to various cgi-bin scripts.  These environment variables will
                   13909: be removed from the users environment after a given time by
                   13910: the routine &Apache::lonnet::transfer_profile_to_env.
                   13911: 
                   13912: =cut
                   13913: 
                   13914: ############################################################
                   13915: ############################################################
1.152     albertel 13916: my $uniq=0;
1.136     matthew  13917: sub get_cgi_id {
1.154     albertel 13918:     $uniq=($uniq+1)%100000;
1.280     albertel 13919:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13920: }
                   13921: 
1.127     matthew  13922: ############################################################
                   13923: ############################################################
                   13924: 
                   13925: =pod
                   13926: 
1.648     raeburn  13927: =item * &DrawBarGraph()
1.127     matthew  13928: 
1.138     matthew  13929: Facilitates the plotting of data in a (stacked) bar graph.
                   13930: Puts plot definition data into the users environment in order for 
                   13931: graph.png to plot it.  Returns an <img> tag for the plot.
                   13932: The bars on the plot are labeled '1','2',...,'n'.
                   13933: 
                   13934: Inputs:
                   13935: 
                   13936: =over 4
                   13937: 
                   13938: =item $Title: string, the title of the plot
                   13939: 
                   13940: =item $xlabel: string, text describing the X-axis of the plot
                   13941: 
                   13942: =item $ylabel: string, text describing the Y-axis of the plot
                   13943: 
                   13944: =item $Max: scalar, the maximum Y value to use in the plot
                   13945: If $Max is < any data point, the graph will not be rendered.
                   13946: 
1.140     matthew  13947: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13948: they are plotted.  If undefined, default values will be used.
                   13949: 
1.178     matthew  13950: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13951: 
1.138     matthew  13952: =item @Values: An array of array references.  Each array reference holds data
                   13953: to be plotted in a stacked bar chart.
                   13954: 
1.239     matthew  13955: =item If the final element of @Values is a hash reference the key/value
                   13956: pairs will be added to the graph definition.
                   13957: 
1.138     matthew  13958: =back
                   13959: 
                   13960: Returns:
                   13961: 
                   13962: An <img> tag which references graph.png and the appropriate identifying
                   13963: information for the plot.
                   13964: 
1.127     matthew  13965: =cut
                   13966: 
                   13967: ############################################################
                   13968: ############################################################
1.134     matthew  13969: sub DrawBarGraph {
1.178     matthew  13970:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13971:     #
                   13972:     if (! defined($colors)) {
                   13973:         $colors = ['#33ff00', 
                   13974:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13975:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13976:                   ]; 
                   13977:     }
1.228     matthew  13978:     my $extra_settings = {};
                   13979:     if (ref($Values[-1]) eq 'HASH') {
                   13980:         $extra_settings = pop(@Values);
                   13981:     }
1.127     matthew  13982:     #
1.136     matthew  13983:     my $identifier = &get_cgi_id();
                   13984:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13985:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13986:         return '';
                   13987:     }
1.225     matthew  13988:     #
                   13989:     my @Labels;
                   13990:     if (defined($labels)) {
                   13991:         @Labels = @$labels;
                   13992:     } else {
                   13993:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   13994:             push (@Labels,$i+1);
                   13995:         }
                   13996:     }
                   13997:     #
1.129     matthew  13998:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13999:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14000:     my %ValuesHash;
                   14001:     my $NumSets=1;
                   14002:     foreach my $array (@Values) {
                   14003:         next if (! ref($array));
1.136     matthew  14004:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14005:             join(',',@$array);
1.129     matthew  14006:     }
1.127     matthew  14007:     #
1.136     matthew  14008:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14009:     if ($NumBars < 3) {
                   14010:         $width = 120+$NumBars*32;
1.220     matthew  14011:         $xskip = 1;
1.225     matthew  14012:         $bar_width = 30;
                   14013:     } elsif ($NumBars < 5) {
                   14014:         $width = 120+$NumBars*20;
                   14015:         $xskip = 1;
                   14016:         $bar_width = 20;
1.220     matthew  14017:     } elsif ($NumBars < 10) {
1.136     matthew  14018:         $width = 120+$NumBars*15;
                   14019:         $xskip = 1;
                   14020:         $bar_width = 15;
                   14021:     } elsif ($NumBars <= 25) {
                   14022:         $width = 120+$NumBars*11;
                   14023:         $xskip = 5;
                   14024:         $bar_width = 8;
                   14025:     } elsif ($NumBars <= 50) {
                   14026:         $width = 120+$NumBars*8;
                   14027:         $xskip = 5;
                   14028:         $bar_width = 4;
                   14029:     } else {
                   14030:         $width = 120+$NumBars*8;
                   14031:         $xskip = 5;
                   14032:         $bar_width = 4;
                   14033:     }
                   14034:     #
1.137     matthew  14035:     $Max = 1 if ($Max < 1);
                   14036:     if ( int($Max) < $Max ) {
                   14037:         $Max++;
                   14038:         $Max = int($Max);
                   14039:     }
1.127     matthew  14040:     $Title  = '' if (! defined($Title));
                   14041:     $xlabel = '' if (! defined($xlabel));
                   14042:     $ylabel = '' if (! defined($ylabel));
1.369     www      14043:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14044:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14045:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14046:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14047:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14048:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14049:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14050:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14051:     $ValuesHash{$id.'.height'}   = $height;
                   14052:     $ValuesHash{$id.'.width'}    = $width;
                   14053:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14054:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14055:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14056:     #
1.228     matthew  14057:     # Deal with other parameters
                   14058:     while (my ($key,$value) = each(%$extra_settings)) {
                   14059:         $ValuesHash{$id.'.'.$key} = $value;
                   14060:     }
                   14061:     #
1.646     raeburn  14062:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14063:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14064: }
                   14065: 
                   14066: ############################################################
                   14067: ############################################################
                   14068: 
                   14069: =pod
                   14070: 
1.648     raeburn  14071: =item * &DrawXYGraph()
1.137     matthew  14072: 
1.138     matthew  14073: Facilitates the plotting of data in an XY graph.
                   14074: Puts plot definition data into the users environment in order for 
                   14075: graph.png to plot it.  Returns an <img> tag for the plot.
                   14076: 
                   14077: Inputs:
                   14078: 
                   14079: =over 4
                   14080: 
                   14081: =item $Title: string, the title of the plot
                   14082: 
                   14083: =item $xlabel: string, text describing the X-axis of the plot
                   14084: 
                   14085: =item $ylabel: string, text describing the Y-axis of the plot
                   14086: 
                   14087: =item $Max: scalar, the maximum Y value to use in the plot
                   14088: If $Max is < any data point, the graph will not be rendered.
                   14089: 
                   14090: =item $colors: Array ref containing the hex color codes for the data to be 
                   14091: plotted in.  If undefined, default values will be used.
                   14092: 
                   14093: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14094: 
                   14095: =item $Ydata: Array ref containing Array refs.  
1.185     www      14096: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14097: 
                   14098: =item %Values: hash indicating or overriding any default values which are 
                   14099: passed to graph.png.  
                   14100: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14101: 
                   14102: =back
                   14103: 
                   14104: Returns:
                   14105: 
                   14106: An <img> tag which references graph.png and the appropriate identifying
                   14107: information for the plot.
                   14108: 
1.137     matthew  14109: =cut
                   14110: 
                   14111: ############################################################
                   14112: ############################################################
                   14113: sub DrawXYGraph {
                   14114:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14115:     #
                   14116:     # Create the identifier for the graph
                   14117:     my $identifier = &get_cgi_id();
                   14118:     my $id = 'cgi.'.$identifier;
                   14119:     #
                   14120:     $Title  = '' if (! defined($Title));
                   14121:     $xlabel = '' if (! defined($xlabel));
                   14122:     $ylabel = '' if (! defined($ylabel));
                   14123:     my %ValuesHash = 
                   14124:         (
1.369     www      14125:          $id.'.title'  => &escape($Title),
                   14126:          $id.'.xlabel' => &escape($xlabel),
                   14127:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14128:          $id.'.y_max_value'=> $Max,
                   14129:          $id.'.labels'     => join(',',@$Xlabels),
                   14130:          $id.'.PlotType'   => 'XY',
                   14131:          );
                   14132:     #
                   14133:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14134:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14135:     }
                   14136:     #
                   14137:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14138:         return '';
                   14139:     }
                   14140:     my $NumSets=1;
1.138     matthew  14141:     foreach my $array (@{$Ydata}){
1.137     matthew  14142:         next if (! ref($array));
                   14143:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14144:     }
1.138     matthew  14145:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14146:     #
                   14147:     # Deal with other parameters
                   14148:     while (my ($key,$value) = each(%Values)) {
                   14149:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14150:     }
                   14151:     #
1.646     raeburn  14152:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14153:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14154: }
                   14155: 
                   14156: ############################################################
                   14157: ############################################################
                   14158: 
                   14159: =pod
                   14160: 
1.648     raeburn  14161: =item * &DrawXYYGraph()
1.138     matthew  14162: 
                   14163: Facilitates the plotting of data in an XY graph with two Y axes.
                   14164: Puts plot definition data into the users environment in order for 
                   14165: graph.png to plot it.  Returns an <img> tag for the plot.
                   14166: 
                   14167: Inputs:
                   14168: 
                   14169: =over 4
                   14170: 
                   14171: =item $Title: string, the title of the plot
                   14172: 
                   14173: =item $xlabel: string, text describing the X-axis of the plot
                   14174: 
                   14175: =item $ylabel: string, text describing the Y-axis of the plot
                   14176: 
                   14177: =item $colors: Array ref containing the hex color codes for the data to be 
                   14178: plotted in.  If undefined, default values will be used.
                   14179: 
                   14180: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14181: 
                   14182: =item $Ydata1: The first data set
                   14183: 
                   14184: =item $Min1: The minimum value of the left Y-axis
                   14185: 
                   14186: =item $Max1: The maximum value of the left Y-axis
                   14187: 
                   14188: =item $Ydata2: The second data set
                   14189: 
                   14190: =item $Min2: The minimum value of the right Y-axis
                   14191: 
                   14192: =item $Max2: The maximum value of the left Y-axis
                   14193: 
                   14194: =item %Values: hash indicating or overriding any default values which are 
                   14195: passed to graph.png.  
                   14196: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14197: 
                   14198: =back
                   14199: 
                   14200: Returns:
                   14201: 
                   14202: An <img> tag which references graph.png and the appropriate identifying
                   14203: information for the plot.
1.136     matthew  14204: 
                   14205: =cut
                   14206: 
                   14207: ############################################################
                   14208: ############################################################
1.137     matthew  14209: sub DrawXYYGraph {
                   14210:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14211:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14212:     #
                   14213:     # Create the identifier for the graph
                   14214:     my $identifier = &get_cgi_id();
                   14215:     my $id = 'cgi.'.$identifier;
                   14216:     #
                   14217:     $Title  = '' if (! defined($Title));
                   14218:     $xlabel = '' if (! defined($xlabel));
                   14219:     $ylabel = '' if (! defined($ylabel));
                   14220:     my %ValuesHash = 
                   14221:         (
1.369     www      14222:          $id.'.title'  => &escape($Title),
                   14223:          $id.'.xlabel' => &escape($xlabel),
                   14224:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14225:          $id.'.labels' => join(',',@$Xlabels),
                   14226:          $id.'.PlotType' => 'XY',
                   14227:          $id.'.NumSets' => 2,
1.137     matthew  14228:          $id.'.two_axes' => 1,
                   14229:          $id.'.y1_max_value' => $Max1,
                   14230:          $id.'.y1_min_value' => $Min1,
                   14231:          $id.'.y2_max_value' => $Max2,
                   14232:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14233:          );
                   14234:     #
1.137     matthew  14235:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14236:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14237:     }
                   14238:     #
                   14239:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14240:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14241:         return '';
                   14242:     }
                   14243:     my $NumSets=1;
1.137     matthew  14244:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14245:         next if (! ref($array));
                   14246:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14247:     }
                   14248:     #
                   14249:     # Deal with other parameters
                   14250:     while (my ($key,$value) = each(%Values)) {
                   14251:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14252:     }
                   14253:     #
1.646     raeburn  14254:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14255:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14256: }
                   14257: 
                   14258: ############################################################
                   14259: ############################################################
                   14260: 
                   14261: =pod
                   14262: 
1.157     matthew  14263: =back 
                   14264: 
1.139     matthew  14265: =head1 Statistics helper routines?  
                   14266: 
                   14267: Bad place for them but what the hell.
                   14268: 
1.157     matthew  14269: =over 4
                   14270: 
1.648     raeburn  14271: =item * &chartlink()
1.139     matthew  14272: 
                   14273: Returns a link to the chart for a specific student.  
                   14274: 
                   14275: Inputs:
                   14276: 
                   14277: =over 4
                   14278: 
                   14279: =item $linktext: The text of the link
                   14280: 
                   14281: =item $sname: The students username
                   14282: 
                   14283: =item $sdomain: The students domain
                   14284: 
                   14285: =back
                   14286: 
1.157     matthew  14287: =back
                   14288: 
1.139     matthew  14289: =cut
                   14290: 
                   14291: ############################################################
                   14292: ############################################################
                   14293: sub chartlink {
                   14294:     my ($linktext, $sname, $sdomain) = @_;
                   14295:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14296:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14297:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14298:        '">'.$linktext.'</a>';
1.153     matthew  14299: }
                   14300: 
                   14301: #######################################################
                   14302: #######################################################
                   14303: 
                   14304: =pod
                   14305: 
                   14306: =head1 Course Environment Routines
1.157     matthew  14307: 
                   14308: =over 4
1.153     matthew  14309: 
1.648     raeburn  14310: =item * &restore_course_settings()
1.153     matthew  14311: 
1.648     raeburn  14312: =item * &store_course_settings()
1.153     matthew  14313: 
                   14314: Restores/Store indicated form parameters from the course environment.
                   14315: Will not overwrite existing values of the form parameters.
                   14316: 
                   14317: Inputs: 
                   14318: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14319: 
                   14320: a hash ref describing the data to be stored.  For example:
                   14321:    
                   14322: %Save_Parameters = ('Status' => 'scalar',
                   14323:     'chartoutputmode' => 'scalar',
                   14324:     'chartoutputdata' => 'scalar',
                   14325:     'Section' => 'array',
1.373     raeburn  14326:     'Group' => 'array',
1.153     matthew  14327:     'StudentData' => 'array',
                   14328:     'Maps' => 'array');
                   14329: 
                   14330: Returns: both routines return nothing
                   14331: 
1.631     raeburn  14332: =back
                   14333: 
1.153     matthew  14334: =cut
                   14335: 
                   14336: #######################################################
                   14337: #######################################################
                   14338: sub store_course_settings {
1.496     albertel 14339:     return &store_settings($env{'request.course.id'},@_);
                   14340: }
                   14341: 
                   14342: sub store_settings {
1.153     matthew  14343:     # save to the environment
                   14344:     # appenv the same items, just to be safe
1.300     albertel 14345:     my $udom  = $env{'user.domain'};
                   14346:     my $uname = $env{'user.name'};
1.496     albertel 14347:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14348:     my %SaveHash;
                   14349:     my %AppHash;
                   14350:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14351:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14352:         my $envname = 'environment.'.$basename;
1.258     albertel 14353:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14354:             # Save this value away
                   14355:             if ($type eq 'scalar' &&
1.258     albertel 14356:                 (! exists($env{$envname}) || 
                   14357:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14358:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14359:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14360:             } elsif ($type eq 'array') {
                   14361:                 my $stored_form;
1.258     albertel 14362:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14363:                     $stored_form = join(',',
                   14364:                                         map {
1.369     www      14365:                                             &escape($_);
1.258     albertel 14366:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14367:                 } else {
                   14368:                     $stored_form = 
1.369     www      14369:                         &escape($env{'form.'.$setting});
1.153     matthew  14370:                 }
                   14371:                 # Determine if the array contents are the same.
1.258     albertel 14372:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14373:                     $SaveHash{$basename} = $stored_form;
                   14374:                     $AppHash{$envname}   = $stored_form;
                   14375:                 }
                   14376:             }
                   14377:         }
                   14378:     }
                   14379:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14380:                                           $udom,$uname);
1.153     matthew  14381:     if ($put_result !~ /^(ok|delayed)/) {
                   14382:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14383:                                  'got error:'.$put_result);
                   14384:     }
                   14385:     # Make sure these settings stick around in this session, too
1.646     raeburn  14386:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14387:     return;
                   14388: }
                   14389: 
                   14390: sub restore_course_settings {
1.499     albertel 14391:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14392: }
                   14393: 
                   14394: sub restore_settings {
                   14395:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14396:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14397:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14398:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14399:             '.'.$setting;
1.258     albertel 14400:         if (exists($env{$envname})) {
1.153     matthew  14401:             if ($type eq 'scalar') {
1.258     albertel 14402:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14403:             } elsif ($type eq 'array') {
1.258     albertel 14404:                 $env{'form.'.$setting} = [ 
1.153     matthew  14405:                                            map { 
1.369     www      14406:                                                &unescape($_); 
1.258     albertel 14407:                                            } split(',',$env{$envname})
1.153     matthew  14408:                                            ];
                   14409:             }
                   14410:         }
                   14411:     }
1.127     matthew  14412: }
                   14413: 
1.618     raeburn  14414: #######################################################
                   14415: #######################################################
                   14416: 
                   14417: =pod
                   14418: 
                   14419: =head1 Domain E-mail Routines  
                   14420: 
                   14421: =over 4
                   14422: 
1.648     raeburn  14423: =item * &build_recipient_list()
1.618     raeburn  14424: 
1.1144    raeburn  14425: Build recipient lists for following types of e-mail:
1.766     raeburn  14426: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  14427: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14428: module change checking, student/employee ID conflict checks, as
                   14429: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14430: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14431: 
                   14432: Inputs:
1.619     raeburn  14433: defmail (scalar - email address of default recipient), 
1.1144    raeburn  14434: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14435: requestsmail, updatesmail, or idconflictsmail).
                   14436: 
1.619     raeburn  14437: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  14438: 
1.619     raeburn  14439: origmail (scalar - email address of recipient from loncapa.conf, 
                   14440: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  14441: 
1.655     raeburn  14442: Returns: comma separated list of addresses to which to send e-mail.
                   14443: 
                   14444: =back
1.618     raeburn  14445: 
                   14446: =cut
                   14447: 
                   14448: ############################################################
                   14449: ############################################################
                   14450: sub build_recipient_list {
1.619     raeburn  14451:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  14452:     my @recipients;
                   14453:     my $otheremails;
                   14454:     my %domconfig =
                   14455:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   14456:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14457:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14458:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14459:                 my @contacts = ('adminemail','supportemail');
                   14460:                 foreach my $item (@contacts) {
                   14461:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14462:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14463:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14464:                             push(@recipients,$addr);
                   14465:                         }
1.619     raeburn  14466:                     }
1.766     raeburn  14467:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  14468:                 }
                   14469:             }
1.766     raeburn  14470:         } elsif ($origmail ne '') {
                   14471:             push(@recipients,$origmail);
1.618     raeburn  14472:         }
1.619     raeburn  14473:     } elsif ($origmail ne '') {
                   14474:         push(@recipients,$origmail);
1.618     raeburn  14475:     }
1.688     raeburn  14476:     if (defined($defmail)) {
                   14477:         if ($defmail ne '') {
                   14478:             push(@recipients,$defmail);
                   14479:         }
1.618     raeburn  14480:     }
                   14481:     if ($otheremails) {
1.619     raeburn  14482:         my @others;
                   14483:         if ($otheremails =~ /,/) {
                   14484:             @others = split(/,/,$otheremails);
1.618     raeburn  14485:         } else {
1.619     raeburn  14486:             push(@others,$otheremails);
                   14487:         }
                   14488:         foreach my $addr (@others) {
                   14489:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14490:                 push(@recipients,$addr);
                   14491:             }
1.618     raeburn  14492:         }
                   14493:     }
1.619     raeburn  14494:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  14495:     return $recipientlist;
                   14496: }
                   14497: 
1.127     matthew  14498: ############################################################
                   14499: ############################################################
1.154     albertel 14500: 
1.655     raeburn  14501: =pod
                   14502: 
1.1224    musolffc 14503: =over 4
                   14504: 
1.1223    musolffc 14505: =item * &mime_email()
                   14506: 
                   14507: Sends an email with a possible attachment
                   14508: 
                   14509: Inputs:
                   14510: 
                   14511: =over 4
                   14512: 
                   14513: from -              Sender's email address
                   14514: 
                   14515: to -                Email address of recipient
                   14516: 
                   14517: subject -           Subject of email
                   14518: 
                   14519: body -              Body of email
                   14520: 
                   14521: cc_string -         Carbon copy email address
                   14522: 
                   14523: bcc -               Blind carbon copy email address
                   14524: 
                   14525: type -              File type of attachment
                   14526: 
                   14527: attachment_path -   Path of file to be attached
                   14528: 
                   14529: file_name -         Name of file to be attached
                   14530: 
                   14531: attachment_text -   The body of an attachment of type "TEXT"
                   14532: 
                   14533: =back
                   14534: 
                   14535: =back
                   14536: 
                   14537: =cut
                   14538: 
                   14539: ############################################################
                   14540: ############################################################
                   14541: 
                   14542: sub mime_email {
                   14543:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
                   14544:         $file_name, $attachment_text) = @_;
                   14545:     my $msg = MIME::Lite->new(
                   14546:              From    => $from,
                   14547:              To      => $to,
                   14548:              Subject => $subject,
                   14549:              Type    =>'TEXT',
                   14550:              Data    => $body,
                   14551:              );
                   14552:     if ($cc_string ne '') {
                   14553:         $msg->add("Cc" => $cc_string);
                   14554:     }
                   14555:     if ($bcc ne '') {
                   14556:         $msg->add("Bcc" => $bcc);
                   14557:     }
                   14558:     $msg->attr("content-type"         => "text/plain");
                   14559:     $msg->attr("content-type.charset" => "UTF-8");
                   14560:     # Attach file if given
                   14561:     if ($attachment_path) {
                   14562:         unless ($file_name) {
                   14563:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   14564:         }
                   14565:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   14566:         $msg->attach(Type     => $type,
                   14567:                      Path     => $attachment_path,
                   14568:                      Filename => $file_name
                   14569:                      );
                   14570:     # Otherwise attach text if given
                   14571:     } elsif ($attachment_text) {
                   14572:         $msg->attach(Type => 'TEXT',
                   14573:                      Data => $attachment_text);
                   14574:     }
                   14575:     # Send it
                   14576:     $msg->send('sendmail');
                   14577: }
                   14578: 
                   14579: ############################################################
                   14580: ############################################################
                   14581: 
                   14582: =pod
                   14583: 
1.655     raeburn  14584: =head1 Course Catalog Routines
                   14585: 
                   14586: =over 4
                   14587: 
                   14588: =item * &gather_categories()
                   14589: 
                   14590: Converts category definitions - keys of categories hash stored in  
                   14591: coursecategories in configuration.db on the primary library server in a 
                   14592: domain - to an array.  Also generates javascript and idx hash used to 
                   14593: generate Domain Coordinator interface for editing Course Categories.
                   14594: 
                   14595: Inputs:
1.663     raeburn  14596: 
1.655     raeburn  14597: categories (reference to hash of category definitions).
1.663     raeburn  14598: 
1.655     raeburn  14599: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14600:       categories and subcategories).
1.663     raeburn  14601: 
1.655     raeburn  14602: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14603:       editing Course Categories).
1.663     raeburn  14604: 
1.655     raeburn  14605: jsarray (reference to array of categories used to create Javascript arrays for
                   14606:          Domain Coordinator interface for editing Course Categories).
                   14607: 
                   14608: Returns: nothing
                   14609: 
                   14610: Side effects: populates cats, idx and jsarray. 
                   14611: 
                   14612: =cut
                   14613: 
                   14614: sub gather_categories {
                   14615:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14616:     my %counters;
                   14617:     my $num = 0;
                   14618:     foreach my $item (keys(%{$categories})) {
                   14619:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14620:         if ($container eq '' && $depth == 0) {
                   14621:             $cats->[$depth][$categories->{$item}] = $cat;
                   14622:         } else {
                   14623:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14624:         }
                   14625:         my ($escitem,$tail) = split(/:/,$item,2);
                   14626:         if ($counters{$tail} eq '') {
                   14627:             $counters{$tail} = $num;
                   14628:             $num ++;
                   14629:         }
                   14630:         if (ref($idx) eq 'HASH') {
                   14631:             $idx->{$item} = $counters{$tail};
                   14632:         }
                   14633:         if (ref($jsarray) eq 'ARRAY') {
                   14634:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14635:         }
                   14636:     }
                   14637:     return;
                   14638: }
                   14639: 
                   14640: =pod
                   14641: 
                   14642: =item * &extract_categories()
                   14643: 
                   14644: Used to generate breadcrumb trails for course categories.
                   14645: 
                   14646: Inputs:
1.663     raeburn  14647: 
1.655     raeburn  14648: categories (reference to hash of category definitions).
1.663     raeburn  14649: 
1.655     raeburn  14650: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14651:       categories and subcategories).
1.663     raeburn  14652: 
1.655     raeburn  14653: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14654: 
1.655     raeburn  14655: allitems (reference to hash - key is category key 
                   14656:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14657: 
1.655     raeburn  14658: idx (reference to hash of counters used in Domain Coordinator interface for
                   14659:       editing Course Categories).
1.663     raeburn  14660: 
1.655     raeburn  14661: jsarray (reference to array of categories used to create Javascript arrays for
                   14662:          Domain Coordinator interface for editing Course Categories).
                   14663: 
1.665     raeburn  14664: subcats (reference to hash of arrays containing all subcategories within each 
                   14665:          category, -recursive)
                   14666: 
1.655     raeburn  14667: Returns: nothing
                   14668: 
                   14669: Side effects: populates trails and allitems hash references.
                   14670: 
                   14671: =cut
                   14672: 
                   14673: sub extract_categories {
1.665     raeburn  14674:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  14675:     if (ref($categories) eq 'HASH') {
                   14676:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14677:         if (ref($cats->[0]) eq 'ARRAY') {
                   14678:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14679:                 my $name = $cats->[0][$i];
                   14680:                 my $item = &escape($name).'::0';
                   14681:                 my $trailstr;
                   14682:                 if ($name eq 'instcode') {
                   14683:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14684:                 } elsif ($name eq 'communities') {
                   14685:                     $trailstr = &mt('Communities');
1.1239    raeburn  14686:                 } elsif ($name eq 'placement') {
                   14687:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  14688:                 } else {
                   14689:                     $trailstr = $name;
                   14690:                 }
                   14691:                 if ($allitems->{$item} eq '') {
                   14692:                     push(@{$trails},$trailstr);
                   14693:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14694:                 }
                   14695:                 my @parents = ($name);
                   14696:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14697:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14698:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14699:                         if (ref($subcats) eq 'HASH') {
                   14700:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14701:                         }
                   14702:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   14703:                     }
                   14704:                 } else {
                   14705:                     if (ref($subcats) eq 'HASH') {
                   14706:                         $subcats->{$item} = [];
1.655     raeburn  14707:                     }
                   14708:                 }
                   14709:             }
                   14710:         }
                   14711:     }
                   14712:     return;
                   14713: }
                   14714: 
                   14715: =pod
                   14716: 
1.1162    raeburn  14717: =item * &recurse_categories()
1.655     raeburn  14718: 
                   14719: Recursively used to generate breadcrumb trails for course categories.
                   14720: 
                   14721: Inputs:
1.663     raeburn  14722: 
1.655     raeburn  14723: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14724:       categories and subcategories).
1.663     raeburn  14725: 
1.655     raeburn  14726: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14727: 
                   14728: category (current course category, for which breadcrumb trail is being generated).
                   14729: 
                   14730: trails (reference to array of breadcrumb trails for each category).
                   14731: 
1.655     raeburn  14732: allitems (reference to hash - key is category key
                   14733:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14734: 
1.655     raeburn  14735: parents (array containing containers directories for current category, 
                   14736:          back to top level). 
                   14737: 
                   14738: Returns: nothing
                   14739: 
                   14740: Side effects: populates trails and allitems hash references
                   14741: 
                   14742: =cut
                   14743: 
                   14744: sub recurse_categories {
1.665     raeburn  14745:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  14746:     my $shallower = $depth - 1;
                   14747:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14748:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14749:             my $name = $cats->[$depth]{$category}[$k];
                   14750:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14751:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14752:             if ($allitems->{$item} eq '') {
                   14753:                 push(@{$trails},$trailstr);
                   14754:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14755:             }
                   14756:             my $deeper = $depth+1;
                   14757:             push(@{$parents},$category);
1.665     raeburn  14758:             if (ref($subcats) eq 'HASH') {
                   14759:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14760:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14761:                     my $higher;
                   14762:                     if ($j > 0) {
                   14763:                         $higher = &escape($parents->[$j]).':'.
                   14764:                                   &escape($parents->[$j-1]).':'.$j;
                   14765:                     } else {
                   14766:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14767:                     }
                   14768:                     push(@{$subcats->{$higher}},$subcat);
                   14769:                 }
                   14770:             }
                   14771:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14772:                                 $subcats);
1.655     raeburn  14773:             pop(@{$parents});
                   14774:         }
                   14775:     } else {
                   14776:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14777:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14778:         if ($allitems->{$item} eq '') {
                   14779:             push(@{$trails},$trailstr);
                   14780:             $allitems->{$item} = scalar(@{$trails})-1;
                   14781:         }
                   14782:     }
                   14783:     return;
                   14784: }
                   14785: 
1.663     raeburn  14786: =pod
                   14787: 
1.1162    raeburn  14788: =item * &assign_categories_table()
1.663     raeburn  14789: 
                   14790: Create a datatable for display of hierarchical categories in a domain,
                   14791: with checkboxes to allow a course to be categorized. 
                   14792: 
                   14793: Inputs:
                   14794: 
                   14795: cathash - reference to hash of categories defined for the domain (from
                   14796:           configuration.db)
                   14797: 
                   14798: currcat - scalar with an & separated list of categories assigned to a course. 
                   14799: 
1.919     raeburn  14800: type    - scalar contains course type (Course or Community).
                   14801: 
1.663     raeburn  14802: Returns: $output (markup to be displayed) 
                   14803: 
                   14804: =cut
                   14805: 
                   14806: sub assign_categories_table {
1.919     raeburn  14807:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  14808:     my $output;
                   14809:     if (ref($cathash) eq 'HASH') {
                   14810:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   14811:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   14812:         $maxdepth = scalar(@cats);
                   14813:         if (@cats > 0) {
                   14814:             my $itemcount = 0;
                   14815:             if (ref($cats[0]) eq 'ARRAY') {
                   14816:                 my @currcategories;
                   14817:                 if ($currcat ne '') {
                   14818:                     @currcategories = split('&',$currcat);
                   14819:                 }
1.919     raeburn  14820:                 my $table;
1.663     raeburn  14821:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14822:                     my $parent = $cats[0][$i];
1.919     raeburn  14823:                     next if ($parent eq 'instcode');
                   14824:                     if ($type eq 'Community') {
                   14825:                         next unless ($parent eq 'communities');
1.1239    raeburn  14826:                     } elsif ($type eq 'Placement') {
                   14827:                         next unless ($parent eq 'placement');
1.919     raeburn  14828:                     } else {
1.1239    raeburn  14829:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  14830:                     }
1.663     raeburn  14831:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14832:                     my $item = &escape($parent).'::0';
                   14833:                     my $checked = '';
                   14834:                     if (@currcategories > 0) {
                   14835:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14836:                             $checked = ' checked="checked"';
1.663     raeburn  14837:                         }
                   14838:                     }
1.919     raeburn  14839:                     my $parent_title = $parent;
                   14840:                     if ($parent eq 'communities') {
                   14841:                         $parent_title = &mt('Communities');
1.1239    raeburn  14842:                     } elsif ($parent eq 'placement') {
                   14843:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  14844:                     }
                   14845:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14846:                               '<input type="checkbox" name="usecategory" value="'.
                   14847:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   14848:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14849:                     my $depth = 1;
                   14850:                     push(@path,$parent);
1.919     raeburn  14851:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  14852:                     pop(@path);
1.919     raeburn  14853:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14854:                     $itemcount ++;
                   14855:                 }
1.919     raeburn  14856:                 if ($itemcount) {
                   14857:                     $output = &Apache::loncommon::start_data_table().
                   14858:                               $table.
                   14859:                               &Apache::loncommon::end_data_table();
                   14860:                 }
1.663     raeburn  14861:             }
                   14862:         }
                   14863:     }
                   14864:     return $output;
                   14865: }
                   14866: 
                   14867: =pod
                   14868: 
1.1162    raeburn  14869: =item * &assign_category_rows()
1.663     raeburn  14870: 
                   14871: Create a datatable row for display of nested categories in a domain,
                   14872: with checkboxes to allow a course to be categorized,called recursively.
                   14873: 
                   14874: Inputs:
                   14875: 
                   14876: itemcount - track row number for alternating colors
                   14877: 
                   14878: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14879:       categories and subcategories.
                   14880: 
                   14881: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14882: 
                   14883: parent - parent of current category item
                   14884: 
                   14885: path - Array containing all categories back up through the hierarchy from the
                   14886:        current category to the top level.
                   14887: 
                   14888: currcategories - reference to array of current categories assigned to the course
                   14889: 
                   14890: Returns: $output (markup to be displayed).
                   14891: 
                   14892: =cut
                   14893: 
                   14894: sub assign_category_rows {
                   14895:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   14896:     my ($text,$name,$item,$chgstr);
                   14897:     if (ref($cats) eq 'ARRAY') {
                   14898:         my $maxdepth = scalar(@{$cats});
                   14899:         if (ref($cats->[$depth]) eq 'HASH') {
                   14900:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14901:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14902:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  14903:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14904:                 for (my $j=0; $j<$numchildren; $j++) {
                   14905:                     $name = $cats->[$depth]{$parent}[$j];
                   14906:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14907:                     my $deeper = $depth+1;
                   14908:                     my $checked = '';
                   14909:                     if (ref($currcategories) eq 'ARRAY') {
                   14910:                         if (@{$currcategories} > 0) {
                   14911:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14912:                                 $checked = ' checked="checked"';
1.663     raeburn  14913:                             }
                   14914:                         }
                   14915:                     }
1.664     raeburn  14916:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14917:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  14918:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   14919:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14920:                              '</td><td>';
1.663     raeburn  14921:                     if (ref($path) eq 'ARRAY') {
                   14922:                         push(@{$path},$name);
                   14923:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   14924:                         pop(@{$path});
                   14925:                     }
                   14926:                     $text .= '</td></tr>';
                   14927:                 }
                   14928:                 $text .= '</table></td>';
                   14929:             }
                   14930:         }
                   14931:     }
                   14932:     return $text;
                   14933: }
                   14934: 
1.1181    raeburn  14935: =pod
                   14936: 
                   14937: =back
                   14938: 
                   14939: =cut
                   14940: 
1.655     raeburn  14941: ############################################################
                   14942: ############################################################
                   14943: 
                   14944: 
1.443     albertel 14945: sub commit_customrole {
1.664     raeburn  14946:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14947:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14948:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14949:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14950:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14951:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14952:                  '</b><br />';
                   14953:     return $output;
                   14954: }
                   14955: 
                   14956: sub commit_standardrole {
1.1116    raeburn  14957:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14958:     my ($output,$logmsg,$linefeed);
                   14959:     if ($context eq 'auto') {
                   14960:         $linefeed = "\n";
                   14961:     } else {
                   14962:         $linefeed = "<br />\n";
                   14963:     }  
1.443     albertel 14964:     if ($three eq 'st') {
1.541     raeburn  14965:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  14966:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14967:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14968:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14969:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14970:         } else {
1.541     raeburn  14971:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14972:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14973:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14974:             if ($context eq 'auto') {
                   14975:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14976:             } else {
                   14977:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14978:                &mt('Add to classlist').': <b>ok</b>';
                   14979:             }
                   14980:             $output .= $linefeed;
1.443     albertel 14981:         }
                   14982:     } else {
                   14983:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14984:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14985:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14986:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14987:         if ($context eq 'auto') {
                   14988:             $output .= $result.$linefeed;
                   14989:         } else {
                   14990:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14991:         }
1.443     albertel 14992:     }
                   14993:     return $output;
                   14994: }
                   14995: 
                   14996: sub commit_studentrole {
1.1116    raeburn  14997:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14998:         $credits) = @_;
1.626     raeburn  14999:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15000:     if ($context eq 'auto') {
                   15001:         $linefeed = "\n";
                   15002:     } else {
                   15003:         $linefeed = '<br />'."\n";
                   15004:     }
1.443     albertel 15005:     if (defined($one) && defined($two)) {
                   15006:         my $cid=$one.'_'.$two;
                   15007:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15008:         my $secchange = 0;
                   15009:         my $expire_role_result;
                   15010:         my $modify_section_result;
1.628     raeburn  15011:         if ($oldsec ne '-1') { 
                   15012:             if ($oldsec ne $sec) {
1.443     albertel 15013:                 $secchange = 1;
1.628     raeburn  15014:                 my $now = time;
1.443     albertel 15015:                 my $uurl='/'.$cid;
                   15016:                 $uurl=~s/\_/\//g;
                   15017:                 if ($oldsec) {
                   15018:                     $uurl.='/'.$oldsec;
                   15019:                 }
1.626     raeburn  15020:                 $oldsecurl = $uurl;
1.628     raeburn  15021:                 $expire_role_result = 
1.652     raeburn  15022:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15023:                 if ($env{'request.course.sec'} ne '') { 
                   15024:                     if ($expire_role_result eq 'refused') {
                   15025:                         my @roles = ('st');
                   15026:                         my @statuses = ('previous');
                   15027:                         my @roledoms = ($one);
                   15028:                         my $withsec = 1;
                   15029:                         my %roleshash = 
                   15030:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15031:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15032:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15033:                             my ($oldstart,$oldend) = 
                   15034:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15035:                             if ($oldend > 0 && $oldend <= $now) {
                   15036:                                 $expire_role_result = 'ok';
                   15037:                             }
                   15038:                         }
                   15039:                     }
                   15040:                 }
1.443     albertel 15041:                 $result = $expire_role_result;
                   15042:             }
                   15043:         }
                   15044:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  15045:             $modify_section_result = 
                   15046:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15047:                                                            undef,undef,undef,$sec,
                   15048:                                                            $end,$start,'','',$cid,
                   15049:                                                            '',$context,$credits);
1.443     albertel 15050:             if ($modify_section_result =~ /^ok/) {
                   15051:                 if ($secchange == 1) {
1.628     raeburn  15052:                     if ($sec eq '') {
                   15053:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15054:                     } else {
                   15055:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15056:                     }
1.443     albertel 15057:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15058:                     if ($sec eq '') {
                   15059:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15060:                     } else {
                   15061:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15062:                     }
1.443     albertel 15063:                 } else {
1.628     raeburn  15064:                     if ($sec eq '') {
                   15065:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15066:                     } else {
                   15067:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15068:                     }
1.443     albertel 15069:                 }
                   15070:             } else {
1.1115    raeburn  15071:                 if ($secchange) { 
1.628     raeburn  15072:                     $$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;
                   15073:                 } else {
                   15074:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15075:                 }
1.443     albertel 15076:             }
                   15077:             $result = $modify_section_result;
                   15078:         } elsif ($secchange == 1) {
1.628     raeburn  15079:             if ($oldsec eq '') {
1.1103    raeburn  15080:                 $$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  15081:             } else {
                   15082:                 $$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;
                   15083:             }
1.626     raeburn  15084:             if ($expire_role_result eq 'refused') {
                   15085:                 my $newsecurl = '/'.$cid;
                   15086:                 $newsecurl =~ s/\_/\//g;
                   15087:                 if ($sec ne '') {
                   15088:                     $newsecurl.='/'.$sec;
                   15089:                 }
                   15090:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15091:                     if ($sec eq '') {
                   15092:                         $$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;
                   15093:                     } else {
                   15094:                         $$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;
                   15095:                     }
                   15096:                 }
                   15097:             }
1.443     albertel 15098:         }
                   15099:     } else {
1.626     raeburn  15100:         $$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 15101:         $result = "error: incomplete course id\n";
                   15102:     }
                   15103:     return $result;
                   15104: }
                   15105: 
1.1108    raeburn  15106: sub show_role_extent {
                   15107:     my ($scope,$context,$role) = @_;
                   15108:     $scope =~ s{^/}{};
                   15109:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15110:     push(@courseroles,'co');
                   15111:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15112:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15113:         $scope =~ s{/}{_};
                   15114:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15115:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15116:         my ($audom,$auname) = split(/\//,$scope);
                   15117:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15118:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15119:     } else {
                   15120:         $scope =~ s{/$}{};
                   15121:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15122:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15123:     }
                   15124: }
                   15125: 
1.443     albertel 15126: ############################################################
                   15127: ############################################################
                   15128: 
1.566     albertel 15129: sub check_clone {
1.578     raeburn  15130:     my ($args,$linefeed) = @_;
1.566     albertel 15131:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15132:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15133:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   15134:     my $clonemsg;
                   15135:     my $can_clone = 0;
1.944     raeburn  15136:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15137:     if ($lctype ne 'community') {
                   15138:         $lctype = 'course';
                   15139:     }
1.566     albertel 15140:     if ($clonehome eq 'no_host') {
1.944     raeburn  15141:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15142:             $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'});
                   15143:         } else {
                   15144:             $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'});
                   15145:         }     
1.566     albertel 15146:     } else {
                   15147: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  15148:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15149:             if ($clonedesc{'type'} ne 'Community') {
                   15150:                  $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'});
                   15151:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15152:             }
                   15153:         }
1.882     raeburn  15154: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   15155:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15156: 	    $can_clone = 1;
                   15157: 	} else {
1.1221    raeburn  15158: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15159: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  15160:             if ($clonehash{'cloners'} eq '') {
                   15161:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15162:                 if ($domdefs{'canclone'}) {
                   15163:                     unless ($domdefs{'canclone'} eq 'none') {
                   15164:                         if ($domdefs{'canclone'} eq 'domain') {
                   15165:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15166:                                 $can_clone = 1;
                   15167:                             }
                   15168:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15169:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15170:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15171:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15172:                                 $can_clone = 1;
                   15173:                             }
                   15174:                         }
                   15175:                     }
                   15176:                 }
1.578     raeburn  15177:             } else {
1.1221    raeburn  15178: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15179:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15180:                     $can_clone = 1;
1.1221    raeburn  15181:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15182:                     $can_clone = 1;
1.1225    raeburn  15183:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15184:                     $can_clone = 1;
1.1221    raeburn  15185:                 }
                   15186:                 unless ($can_clone) {
1.1225    raeburn  15187:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15188:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  15189:                         my (%gotdomdefaults,%gotcodedefaults);
                   15190:                         foreach my $cloner (@cloners) {
                   15191:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15192:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15193:                                 my (%codedefaults,@code_order);
                   15194:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15195:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15196:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15197:                                     }
                   15198:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15199:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15200:                                     }
                   15201:                                 } else {
                   15202:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15203:                                                                             \%codedefaults,
                   15204:                                                                             \@code_order);
                   15205:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15206:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15207:                                 }
                   15208:                                 if (@code_order > 0) {
                   15209:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15210:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15211:                                                                                 $args->{'crscode'})) {
                   15212:                                         $can_clone = 1;
                   15213:                                         last;
                   15214:                                     }
                   15215:                                 }
                   15216:                             }
                   15217:                         }
                   15218:                     }
1.1225    raeburn  15219:                 }
                   15220:             }
                   15221:             unless ($can_clone) {
                   15222:                 my $ccrole = 'cc';
                   15223:                 if ($args->{'crstype'} eq 'Community') {
                   15224:                     $ccrole = 'co';
                   15225:                 }
                   15226: 	        my %roleshash =
                   15227: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15228: 					          $args->{'ccdomain'},
                   15229:                                                   'userroles',['active'],[$ccrole],
                   15230: 					          [$args->{'clonedomain'}]);
                   15231: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15232:                     $can_clone = 1;
                   15233:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15234:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15235:                     $can_clone = 1;
1.1221    raeburn  15236:                 }
                   15237:             }
                   15238:             unless ($can_clone) {
                   15239:                 if ($args->{'crstype'} eq 'Community') {
                   15240:                     $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  15241:                 } else {
1.1221    raeburn  15242:                     $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'});
                   15243:                 }
1.566     albertel 15244: 	    }
1.578     raeburn  15245:         }
1.566     albertel 15246:     }
                   15247:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15248: }
                   15249: 
1.444     albertel 15250: sub construct_course {
1.1166    raeburn  15251:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 15252:     my $outcome;
1.541     raeburn  15253:     my $linefeed =  '<br />'."\n";
                   15254:     if ($context eq 'auto') {
                   15255:         $linefeed = "\n";
                   15256:     }
1.566     albertel 15257: 
                   15258: #
                   15259: # Are we cloning?
                   15260: #
                   15261:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15262:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  15263: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 15264: 	if ($context ne 'auto') {
1.578     raeburn  15265:             if ($clonemsg ne '') {
                   15266: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   15267:             }
1.566     albertel 15268: 	}
                   15269: 	$outcome .= $clonemsg.$linefeed;
                   15270: 
                   15271:         if (!$can_clone) {
                   15272: 	    return (0,$outcome);
                   15273: 	}
                   15274:     }
                   15275: 
1.444     albertel 15276: #
                   15277: # Open course
                   15278: #
1.1239    raeburn  15279:     my $showncrstype;
                   15280:     if ($args->{'crstype'} eq 'Placement') {
                   15281:         $showncrstype = 'placement test'; 
                   15282:     } else {  
                   15283:         $showncrstype = lc($args->{'crstype'});
                   15284:     }
1.444     albertel 15285:     my %cenv=();
                   15286:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15287:                                              $args->{'cdescr'},
                   15288:                                              $args->{'curl'},
                   15289:                                              $args->{'course_home'},
                   15290:                                              $args->{'nonstandard'},
                   15291:                                              $args->{'crscode'},
                   15292:                                              $args->{'ccuname'}.':'.
                   15293:                                              $args->{'ccdomain'},
1.882     raeburn  15294:                                              $args->{'crstype'},
1.885     raeburn  15295:                                              $cnum,$context,$category);
1.444     albertel 15296: 
                   15297:     # Note: The testing routines depend on this being output; see 
                   15298:     # Utils::Course. This needs to at least be output as a comment
                   15299:     # if anyone ever decides to not show this, and Utils::Course::new
                   15300:     # will need to be suitably modified.
1.1239    raeburn  15301:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
1.943     raeburn  15302:     if ($$courseid =~ /^error:/) {
                   15303:         return (0,$outcome);
                   15304:     }
                   15305: 
1.444     albertel 15306: #
                   15307: # Check if created correctly
                   15308: #
1.479     albertel 15309:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15310:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15311:     if ($crsuhome eq 'no_host') {
                   15312:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   15313:         return (0,$outcome);
                   15314:     }
1.541     raeburn  15315:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15316: 
1.444     albertel 15317: #
1.566     albertel 15318: # Do the cloning
                   15319: #   
                   15320:     if ($can_clone && $cloneid) {
1.1239    raeburn  15321: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
1.566     albertel 15322: 	if ($context ne 'auto') {
                   15323: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   15324: 	}
                   15325: 	$outcome .= $clonemsg.$linefeed;
                   15326: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15327: # Copy all files
1.637     www      15328: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 15329: # Restore URL
1.566     albertel 15330: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15331: # Restore title
1.566     albertel 15332: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15333: # Restore creation date, creator and creation context.
                   15334:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15335:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15336:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15337: # Mark as cloned
1.566     albertel 15338: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15339: # Need to clone grading mode
                   15340:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15341:         $cenv{'grading'}=$newenv{'grading'};
                   15342: # Do not clone these environment entries
                   15343:         &Apache::lonnet::del('environment',
                   15344:                   ['default_enrollment_start_date',
                   15345:                    'default_enrollment_end_date',
                   15346:                    'question.email',
                   15347:                    'policy.email',
                   15348:                    'comment.email',
                   15349:                    'pch.users.denied',
1.725     raeburn  15350:                    'plc.users.denied',
                   15351:                    'hidefromcat',
1.1121    raeburn  15352:                    'checkforpriv',
1.1166    raeburn  15353:                    'categories',
                   15354:                    'internal.uniquecode'],
1.638     www      15355:                    $$crsudom,$$crsunum);
1.1170    raeburn  15356:         if ($args->{'textbook'}) {
                   15357:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15358:         }
1.444     albertel 15359:     }
1.566     albertel 15360: 
1.444     albertel 15361: #
                   15362: # Set environment (will override cloned, if existing)
                   15363: #
                   15364:     my @sections = ();
                   15365:     my @xlists = ();
                   15366:     if ($args->{'crstype'}) {
                   15367:         $cenv{'type'}=$args->{'crstype'};
                   15368:     }
                   15369:     if ($args->{'crsid'}) {
                   15370:         $cenv{'courseid'}=$args->{'crsid'};
                   15371:     }
                   15372:     if ($args->{'crscode'}) {
                   15373:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15374:     }
                   15375:     if ($args->{'crsquota'} ne '') {
                   15376:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15377:     } else {
                   15378:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15379:     }
                   15380:     if ($args->{'ccuname'}) {
                   15381:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15382:                                         ':'.$args->{'ccdomain'};
                   15383:     } else {
                   15384:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15385:     }
1.1116    raeburn  15386:     if ($args->{'defaultcredits'}) {
                   15387:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15388:     }
1.444     albertel 15389:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15390:     if ($args->{'crssections'}) {
                   15391:         $cenv{'internal.sectionnums'} = '';
                   15392:         if ($args->{'crssections'} =~ m/,/) {
                   15393:             @sections = split/,/,$args->{'crssections'};
                   15394:         } else {
                   15395:             $sections[0] = $args->{'crssections'};
                   15396:         }
                   15397:         if (@sections > 0) {
                   15398:             foreach my $item (@sections) {
                   15399:                 my ($sec,$gp) = split/:/,$item;
                   15400:                 my $class = $args->{'crscode'}.$sec;
                   15401:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15402:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15403:                 unless ($addcheck eq 'ok') {
                   15404:                     push @badclasses, $class;
                   15405:                 }
                   15406:             }
                   15407:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15408:         }
                   15409:     }
                   15410: # do not hide course coordinator from staff listing, 
                   15411: # even if privileged
                   15412:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  15413: # add course coordinator's domain to domains to check for privileged users
                   15414: # if different to course domain
                   15415:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15416:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15417:     }
1.444     albertel 15418: # add crosslistings
                   15419:     if ($args->{'crsxlist'}) {
                   15420:         $cenv{'internal.crosslistings'}='';
                   15421:         if ($args->{'crsxlist'} =~ m/,/) {
                   15422:             @xlists = split/,/,$args->{'crsxlist'};
                   15423:         } else {
                   15424:             $xlists[0] = $args->{'crsxlist'};
                   15425:         }
                   15426:         if (@xlists > 0) {
                   15427:             foreach my $item (@xlists) {
                   15428:                 my ($xl,$gp) = split/:/,$item;
                   15429:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15430:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15431:                 unless ($addcheck eq 'ok') {
                   15432:                     push @badclasses, $xl;
                   15433:                 }
                   15434:             }
                   15435:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15436:         }
                   15437:     }
                   15438:     if ($args->{'autoadds'}) {
                   15439:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15440:     }
                   15441:     if ($args->{'autodrops'}) {
                   15442:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15443:     }
                   15444: # check for notification of enrollment changes
                   15445:     my @notified = ();
                   15446:     if ($args->{'notify_owner'}) {
                   15447:         if ($args->{'ccuname'} ne '') {
                   15448:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15449:         }
                   15450:     }
                   15451:     if ($args->{'notify_dc'}) {
                   15452:         if ($uname ne '') { 
1.630     raeburn  15453:             push(@notified,$uname.':'.$udom);
1.444     albertel 15454:         }
                   15455:     }
                   15456:     if (@notified > 0) {
                   15457:         my $notifylist;
                   15458:         if (@notified > 1) {
                   15459:             $notifylist = join(',',@notified);
                   15460:         } else {
                   15461:             $notifylist = $notified[0];
                   15462:         }
                   15463:         $cenv{'internal.notifylist'} = $notifylist;
                   15464:     }
                   15465:     if (@badclasses > 0) {
                   15466:         my %lt=&Apache::lonlocal::texthash(
                   15467:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
                   15468:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   15469:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   15470:         );
1.541     raeburn  15471:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   15472:                            ' ('.$lt{'adby'}.')';
                   15473:         if ($context eq 'auto') {
                   15474:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 15475:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  15476:             foreach my $item (@badclasses) {
                   15477:                 if ($context eq 'auto') {
                   15478:                     $outcome .= " - $item\n";
                   15479:                 } else {
                   15480:                     $outcome .= "<li>$item</li>\n";
                   15481:                 }
                   15482:             }
                   15483:             if ($context eq 'auto') {
                   15484:                 $outcome .= $linefeed;
                   15485:             } else {
1.566     albertel 15486:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  15487:             }
                   15488:         } 
1.444     albertel 15489:     }
                   15490:     if ($args->{'no_end_date'}) {
                   15491:         $args->{'endaccess'} = 0;
                   15492:     }
                   15493:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15494:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15495:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15496:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15497:     if ($args->{'showphotos'}) {
                   15498:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15499:     }
                   15500:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15501:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15502:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15503:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15504:             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'); 
                   15505:             if ($context eq 'auto') {
                   15506:                 $outcome .= $krb_msg;
                   15507:             } else {
1.566     albertel 15508:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15509:             }
                   15510:             $outcome .= $linefeed;
1.444     albertel 15511:         }
                   15512:     }
                   15513:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15514:        if ($args->{'setpolicy'}) {
                   15515:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15516:        }
                   15517:        if ($args->{'setcontent'}) {
                   15518:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15519:        }
1.1251    raeburn  15520:        if ($args->{'setcomment'}) {
                   15521:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15522:        }
1.444     albertel 15523:     }
                   15524:     if ($args->{'reshome'}) {
                   15525: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15526: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15527:     }
                   15528: #
                   15529: # course has keyed access
                   15530: #
                   15531:     if ($args->{'setkeys'}) {
                   15532:        $cenv{'keyaccess'}='yes';
                   15533:     }
                   15534: # if specified, key authority is not course, but user
                   15535: # only active if keyaccess is yes
                   15536:     if ($args->{'keyauth'}) {
1.487     albertel 15537: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15538: 	$user = &LONCAPA::clean_username($user);
                   15539: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15540: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15541: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15542: 	}
                   15543:     }
                   15544: 
1.1166    raeburn  15545: #
1.1167    raeburn  15546: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  15547: #
                   15548:     if ($args->{'uniquecode'}) {
                   15549:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15550:         if ($code) {
                   15551:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  15552:             my %crsinfo =
                   15553:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15554:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15555:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15556:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15557:             } 
1.1166    raeburn  15558:             if (ref($coderef)) {
                   15559:                 $$coderef = $code;
                   15560:             }
                   15561:         }
                   15562:     }
                   15563: 
1.444     albertel 15564:     if ($args->{'disresdis'}) {
                   15565:         $cenv{'pch.roles.denied'}='st';
                   15566:     }
                   15567:     if ($args->{'disablechat'}) {
                   15568:         $cenv{'plc.roles.denied'}='st';
                   15569:     }
                   15570: 
                   15571:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15572:     # course
                   15573:     $cenv{'course.helper.not.run'} = 1;
                   15574:     #
                   15575:     # Use new Randomseed
                   15576:     #
                   15577:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15578:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15579:     #
                   15580:     # The encryption code and receipt prefix for this course
                   15581:     #
                   15582:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15583:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15584:     #
                   15585:     # By default, use standard grading
                   15586:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15587: 
1.541     raeburn  15588:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15589:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15590: #
                   15591: # Open all assignments
                   15592: #
                   15593:     if ($args->{'openall'}) {
                   15594:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   15595:        my %storecontent = ($storeunder         => time,
                   15596:                            $storeunder.'.type' => 'date_start');
                   15597:        
                   15598:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  15599:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15600:    }
                   15601: #
                   15602: # Set first page
                   15603: #
                   15604:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15605: 	    || ($cloneid)) {
1.445     albertel 15606: 	use LONCAPA::map;
1.444     albertel 15607: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15608: 
                   15609: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15610:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15611: 
1.444     albertel 15612:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15613:         my $title; my $url;
                   15614:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15615: 	    $title=&mt('Syllabus');
1.444     albertel 15616:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15617:         } else {
1.963     raeburn  15618:             $title=&mt('Table of Contents');
1.444     albertel 15619:             $url='/adm/navmaps';
                   15620:         }
1.445     albertel 15621: 
                   15622:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15623: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15624: 
                   15625: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15626:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15627:     }
1.566     albertel 15628: 
1.1237    raeburn  15629: # 
                   15630: # Set params for Placement Tests
                   15631: #
1.1239    raeburn  15632:     if ($args->{'crstype'} eq 'Placement') {
                   15633:        my %storecontent; 
                   15634:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   15635:        my %defaults = (
                   15636:                         buttonshide   => { value => 'yes',
                   15637:                                            type => 'string_yesno',},
                   15638:                         type          => { value => 'randomizetry',
                   15639:                                            type  => 'string_questiontype',},
                   15640:                         maxtries      => { value => 1,
                   15641:                                            type => 'int_pos',},
                   15642:                         problemstatus => { value => 'no',
                   15643:                                            type  => 'string_problemstatus',},
                   15644:                       );
                   15645:        foreach my $key (keys(%defaults)) {
                   15646:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   15647:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   15648:        }
1.1237    raeburn  15649:        &Apache::lonnet::cput
                   15650:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   15651:     }
                   15652: 
1.566     albertel 15653:     return (1,$outcome);
1.444     albertel 15654: }
                   15655: 
1.1166    raeburn  15656: sub make_unique_code {
                   15657:     my ($cdom,$cnum) = @_;
                   15658:     # get lock on uniquecodes db
                   15659:     my $lockhash = {
                   15660:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15661:                                                   ':'.$env{'user.domain'},
                   15662:                    };
                   15663:     my $tries = 0;
                   15664:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15665:     my ($code,$error);
                   15666:   
                   15667:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15668:         $tries ++;
                   15669:         sleep 1;
                   15670:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15671:     }
                   15672:     if ($gotlock eq 'ok') {
                   15673:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15674:         my $gotcode;
                   15675:         my $attempts = 0;
                   15676:         while ((!$gotcode) && ($attempts < 100)) {
                   15677:             $code = &generate_code();
                   15678:             if (!exists($currcodes{$code})) {
                   15679:                 $gotcode = 1;
                   15680:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15681:                     $error = 'nostore';
                   15682:                 }
                   15683:             }
                   15684:             $attempts ++;
                   15685:         }
                   15686:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15687:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15688:     } else {
                   15689:         $error = 'nolock';
                   15690:     }
                   15691:     return ($code,$error);
                   15692: }
                   15693: 
                   15694: sub generate_code {
                   15695:     my $code;
                   15696:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15697:     for (my $i=0; $i<6; $i++) {
                   15698:         my $lettnum = int (rand 2);
                   15699:         my $item = '';
                   15700:         if ($lettnum) {
                   15701:             $item = $letts[int( rand(18) )];
                   15702:         } else {
                   15703:             $item = 1+int( rand(8) );
                   15704:         }
                   15705:         $code .= $item;
                   15706:     }
                   15707:     return $code;
                   15708: }
                   15709: 
1.444     albertel 15710: ############################################################
                   15711: ############################################################
                   15712: 
1.1237    raeburn  15713: # Community, Course and Placement Test
1.378     raeburn  15714: sub course_type {
                   15715:     my ($cid) = @_;
                   15716:     if (!defined($cid)) {
                   15717:         $cid = $env{'request.course.id'};
                   15718:     }
1.404     albertel 15719:     if (defined($env{'course.'.$cid.'.type'})) {
                   15720:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15721:     } else {
                   15722:         return 'Course';
1.377     raeburn  15723:     }
                   15724: }
1.156     albertel 15725: 
1.406     raeburn  15726: sub group_term {
                   15727:     my $crstype = &course_type();
                   15728:     my %names = (
                   15729:                   'Course' => 'group',
1.865     raeburn  15730:                   'Community' => 'group',
1.1237    raeburn  15731:                   'Placement' => 'group',
1.406     raeburn  15732:                 );
                   15733:     return $names{$crstype};
                   15734: }
                   15735: 
1.902     raeburn  15736: sub course_types {
1.1237    raeburn  15737:     my @types = ('official','unofficial','community','textbook','placement');
1.902     raeburn  15738:     my %typename = (
                   15739:                          official   => 'Official course',
                   15740:                          unofficial => 'Unofficial course',
                   15741:                          community  => 'Community',
1.1165    raeburn  15742:                          textbook   => 'Textbook course',
1.1237    raeburn  15743:                          placement  => 'Placement test',
1.902     raeburn  15744:                    );
                   15745:     return (\@types,\%typename);
                   15746: }
                   15747: 
1.156     albertel 15748: sub icon {
                   15749:     my ($file)=@_;
1.505     albertel 15750:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15751:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15752:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15753:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15754: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15755: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15756: 	            $curfext.".gif") {
                   15757: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15758: 		$curfext.".gif";
                   15759: 	}
                   15760:     }
1.249     albertel 15761:     return &lonhttpdurl($iconname);
1.154     albertel 15762: } 
1.84      albertel 15763: 
1.575     albertel 15764: sub lonhttpdurl {
1.692     www      15765: #
                   15766: # Had been used for "small fry" static images on separate port 8080.
                   15767: # Modify here if lightweight http functionality desired again.
                   15768: # Currently eliminated due to increasing firewall issues.
                   15769: #
1.575     albertel 15770:     my ($url)=@_;
1.692     www      15771:     return $url;
1.215     albertel 15772: }
                   15773: 
1.213     albertel 15774: sub connection_aborted {
                   15775:     my ($r)=@_;
                   15776:     $r->print(" ");$r->rflush();
                   15777:     my $c = $r->connection;
                   15778:     return $c->aborted();
                   15779: }
                   15780: 
1.221     foxr     15781: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15782: #    strings as 'strings'.
                   15783: sub escape_single {
1.221     foxr     15784:     my ($input) = @_;
1.223     albertel 15785:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15786:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15787:     return $input;
                   15788: }
1.223     albertel 15789: 
1.222     foxr     15790: #  Same as escape_single, but escape's "'s  This 
                   15791: #  can be used for  "strings"
                   15792: sub escape_double {
                   15793:     my ($input) = @_;
                   15794:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15795:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15796:     return $input;
                   15797: }
1.223     albertel 15798:  
1.222     foxr     15799: #   Escapes the last element of a full URL.
                   15800: sub escape_url {
                   15801:     my ($url)   = @_;
1.238     raeburn  15802:     my @urlslices = split(/\//, $url,-1);
1.369     www      15803:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  15804:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15805: }
1.462     albertel 15806: 
1.820     raeburn  15807: sub compare_arrays {
                   15808:     my ($arrayref1,$arrayref2) = @_;
                   15809:     my (@difference,%count);
                   15810:     @difference = ();
                   15811:     %count = ();
                   15812:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15813:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15814:         foreach my $element (keys(%count)) {
                   15815:             if ($count{$element} == 1) {
                   15816:                 push(@difference,$element);
                   15817:             }
                   15818:         }
                   15819:     }
                   15820:     return @difference;
                   15821: }
                   15822: 
1.817     bisitz   15823: # -------------------------------------------------------- Initialize user login
1.462     albertel 15824: sub init_user_environment {
1.463     albertel 15825:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15826:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15827: 
                   15828:     my $public=($username eq 'public' && $domain eq 'public');
                   15829: 
                   15830: # See if old ID present, if so, remove
                   15831: 
1.1062    raeburn  15832:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15833:     my $now=time;
                   15834: 
                   15835:     if ($public) {
                   15836: 	my $max_public=100;
                   15837: 	my $oldest;
                   15838: 	my $oldest_time=0;
                   15839: 	for(my $next=1;$next<=$max_public;$next++) {
                   15840: 	    if (-e $lonids."/publicuser_$next.id") {
                   15841: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15842: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15843: 		    $oldest_time=$mtime;
                   15844: 		    $oldest=$next;
                   15845: 		}
                   15846: 	    } else {
                   15847: 		$cookie="publicuser_$next";
                   15848: 		last;
                   15849: 	    }
                   15850: 	}
                   15851: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15852:     } else {
1.463     albertel 15853: 	# if this isn't a robot, kill any existing non-robot sessions
                   15854: 	if (!$args->{'robot'}) {
                   15855: 	    opendir(DIR,$lonids);
                   15856: 	    while ($filename=readdir(DIR)) {
                   15857: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   15858: 		    unlink($lonids.'/'.$filename);
                   15859: 		}
1.462     albertel 15860: 	    }
1.463     albertel 15861: 	    closedir(DIR);
1.1204    raeburn  15862: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15863:             my $namespace = 'nohist_courseeditor';
                   15864:             my $lockingkey = 'paste'."\0".'locked_num';
                   15865:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15866:                                                 $domain,$username);
                   15867:             if (exists($lockhash{$lockingkey})) {
                   15868:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15869:                 unless ($delresult eq 'ok') {
                   15870:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15871:                 }
                   15872:             }
1.462     albertel 15873: 	}
                   15874: # Give them a new cookie
1.463     albertel 15875: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15876: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15877: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15878:     
                   15879: # Initialize roles
                   15880: 
1.1062    raeburn  15881: 	($userroles,$firstaccenv,$timerintenv) = 
                   15882:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15883:     }
                   15884: # ------------------------------------ Check browser type and MathML capability
                   15885: 
1.1194    raeburn  15886:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15887:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15888: 
                   15889: # ------------------------------------------------------------- Get environment
                   15890: 
                   15891:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15892:     my ($tmp) = keys(%userenv);
                   15893:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15894:     } else {
                   15895: 	undef(%userenv);
                   15896:     }
                   15897:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15898: 	$form->{'interface'}=$userenv{'interface'};
                   15899:     }
                   15900:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15901: 
                   15902: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15903:     foreach my $option ('interface','localpath','localres') {
                   15904:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15905:     }
                   15906: # --------------------------------------------------------- Write first profile
                   15907: 
                   15908:     {
                   15909: 	my %initial_env = 
                   15910: 	    ("user.name"          => $username,
                   15911: 	     "user.domain"        => $domain,
                   15912: 	     "user.home"          => $authhost,
                   15913: 	     "browser.type"       => $clientbrowser,
                   15914: 	     "browser.version"    => $clientversion,
                   15915: 	     "browser.mathml"     => $clientmathml,
                   15916: 	     "browser.unicode"    => $clientunicode,
                   15917: 	     "browser.os"         => $clientos,
1.1137    raeburn  15918:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  15919:              "browser.info"       => $clientinfo,
1.1194    raeburn  15920:              "browser.osversion"  => $clientosversion,
1.462     albertel 15921: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15922: 	     "request.course.fn"  => '',
                   15923: 	     "request.course.uri" => '',
                   15924: 	     "request.course.sec" => '',
                   15925: 	     "request.role"       => 'cm',
                   15926: 	     "request.role.adv"   => $env{'user.adv'},
                   15927: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15928: 
                   15929:         if ($form->{'localpath'}) {
                   15930: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15931: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15932:         }
                   15933: 	
                   15934: 	if ($form->{'interface'}) {
                   15935: 	    $form->{'interface'}=~s/\W//gs;
                   15936: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15937: 	    $env{'browser.interface'}=$form->{'interface'};
                   15938: 	}
                   15939: 
1.1157    raeburn  15940:         if ($form->{'iptoken'}) {
                   15941:             my $lonhost = $r->dir_config('lonHostID');
                   15942:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15943:             $env{'user.noloadbalance'} = $lonhost;
                   15944:         }
                   15945: 
1.981     raeburn  15946:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  15947:         my %domdef;
                   15948:         unless ($domain eq 'public') {
                   15949:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   15950:         }
1.980     raeburn  15951: 
1.1081    raeburn  15952:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  15953:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  15954:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15955:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  15956:         }
                   15957: 
1.1237    raeburn  15958:         foreach my $crstype ('official','unofficial','community','textbook','placement') {
1.765     raeburn  15959:             $userenv{'canrequest.'.$crstype} =
                   15960:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  15961:                                                   'reload','requestcourses',
                   15962:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  15963:         }
                   15964: 
1.1092    raeburn  15965:         $userenv{'canrequest.author'} =
                   15966:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15967:                                         'reload','requestauthor',
                   15968:                                         \%userenv,\%domdef,\%is_adv);
                   15969:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15970:                                              $domain,$username);
                   15971:         my $reqstatus = $reqauthor{'author_status'};
                   15972:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   15973:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   15974:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15975:                                                   $reqauthor{'author'}{'timestamp'};
                   15976:             }
                   15977:         }
                   15978: 
1.462     albertel 15979: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15980: 
1.462     albertel 15981: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15982: 		 &GDBM_WRCREAT(),0640)) {
                   15983: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15984: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15985: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15986:             if (ref($firstaccenv) eq 'HASH') {
                   15987:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15988:             }
                   15989:             if (ref($timerintenv) eq 'HASH') {
                   15990:                 &_add_to_env(\%disk_env,$timerintenv);
                   15991:             }
1.463     albertel 15992: 	    if (ref($args->{'extra_env'})) {
                   15993: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15994: 	    }
1.462     albertel 15995: 	    untie(%disk_env);
                   15996: 	} else {
1.705     tempelho 15997: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15998: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15999: 	    return 'error: '.$!;
                   16000: 	}
                   16001:     }
                   16002:     $env{'request.role'}='cm';
                   16003:     $env{'request.role.adv'}=$env{'user.adv'};
                   16004:     $env{'browser.type'}=$clientbrowser;
                   16005: 
                   16006:     return $cookie;
                   16007: 
                   16008: }
                   16009: 
                   16010: sub _add_to_env {
                   16011:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16012:     if (ref($env_data) eq 'HASH') {
                   16013:         while (my ($key,$value) = each(%$env_data)) {
                   16014: 	    $idf->{$prefix.$key} = $value;
                   16015: 	    $env{$prefix.$key}   = $value;
                   16016:         }
1.462     albertel 16017:     }
                   16018: }
                   16019: 
1.685     tempelho 16020: # --- Get the symbolic name of a problem and the url
                   16021: sub get_symb {
                   16022:     my ($request,$silent) = @_;
1.726     raeburn  16023:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16024:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16025:     if ($symb eq '') {
                   16026:         if (!$silent) {
1.1071    raeburn  16027:             if (ref($request)) { 
                   16028:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16029:             }
1.685     tempelho 16030:             return ();
                   16031:         }
                   16032:     }
                   16033:     &Apache::lonenc::check_decrypt(\$symb);
                   16034:     return ($symb);
                   16035: }
                   16036: 
                   16037: # --------------------------------------------------------------Get annotation
                   16038: 
                   16039: sub get_annotation {
                   16040:     my ($symb,$enc) = @_;
                   16041: 
                   16042:     my $key = $symb;
                   16043:     if (!$enc) {
                   16044:         $key =
                   16045:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16046:     }
                   16047:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16048:     return $annotation{$key};
                   16049: }
                   16050: 
                   16051: sub clean_symb {
1.731     raeburn  16052:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16053: 
                   16054:     &Apache::lonenc::check_decrypt(\$symb);
                   16055:     my $enc = $env{'request.enc'};
1.731     raeburn  16056:     if ($delete_enc) {
1.730     raeburn  16057:         delete($env{'request.enc'});
                   16058:     }
1.685     tempelho 16059: 
                   16060:     return ($symb,$enc);
                   16061: }
1.462     albertel 16062: 
1.1181    raeburn  16063: ############################################################
                   16064: ############################################################
                   16065: 
                   16066: =pod
                   16067: 
                   16068: =head1 Routines for building display used to search for courses
                   16069: 
                   16070: 
                   16071: =over 4
                   16072: 
                   16073: =item * &build_filters()
                   16074: 
                   16075: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  16076: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16077: and quotacheck.pl
                   16078: 
1.1181    raeburn  16079: 
                   16080: Inputs:
                   16081: 
                   16082: filterlist - anonymous array of fields to include as potential filters 
                   16083: 
                   16084: crstype - course type
                   16085: 
                   16086: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16087:               to pop-open a course selector (will contain "extra element"). 
                   16088: 
                   16089: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16090: 
                   16091: filter - anonymous hash of criteria and their values
                   16092: 
                   16093: action - form action
                   16094: 
                   16095: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16096: 
1.1182    raeburn  16097: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  16098: 
                   16099: cloneruname - username of owner of new course who wants to clone
                   16100: 
                   16101: clonerudom - domain of owner of new course who wants to clone
                   16102: 
                   16103: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   16104: 
                   16105: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16106: 
                   16107: codedom - domain
                   16108: 
                   16109: formname - value of form element named "form". 
                   16110: 
                   16111: fixeddom - domain, if fixed.
                   16112: 
                   16113: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   16114: 
                   16115: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   16116: 
                   16117: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16118: 
                   16119: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16120: 
                   16121: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16122: 
                   16123: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16124: 
                   16125: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16126: 
1.1182    raeburn  16127: 
1.1181    raeburn  16128: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16129: 
1.1182    raeburn  16130: 
1.1181    raeburn  16131: Side Effects: None
                   16132: 
                   16133: =cut
                   16134: 
                   16135: # ---------------------------------------------- search for courses based on last activity etc.
                   16136: 
                   16137: sub build_filters {
                   16138:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16139:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16140:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16141:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16142:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  16143:     my ($list,$jscript);
1.1181    raeburn  16144:     my $onchange = 'javascript:updateFilters(this)';
                   16145:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16146:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16147:         $typeselectform,$instcodetitle);
                   16148:     if ($formname eq '') {
                   16149:         $formname = $caller;
                   16150:     }
                   16151:     foreach my $item (@{$filterlist}) {
                   16152:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16153:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16154:             if ($item eq 'domainfilter') {
                   16155:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16156:             } elsif ($item eq 'coursefilter') {
                   16157:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16158:             } elsif ($item eq 'ownerfilter') {
                   16159:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16160:             } elsif ($item eq 'ownerdomfilter') {
                   16161:                 $filter->{'ownerdomfilter'} =
                   16162:                     &LONCAPA::clean_domain($filter->{$item});
                   16163:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16164:                                                        'ownerdomfilter',1);
                   16165:             } elsif ($item eq 'personfilter') {
                   16166:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16167:             } elsif ($item eq 'persondomfilter') {
                   16168:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16169:                                                         'persondomfilter',1);
                   16170:             } else {
                   16171:                 $filter->{$item} =~ s/\W//g;
                   16172:             }
                   16173:             if (!$filter->{$item}) {
                   16174:                 $filter->{$item} = '';
                   16175:             }
                   16176:         }
                   16177:         if ($item eq 'domainfilter') {
                   16178:             my $allow_blank = 1;
                   16179:             if ($formname eq 'portform') {
                   16180:                 $allow_blank=0;
                   16181:             } elsif ($formname eq 'studentform') {
                   16182:                 $allow_blank=0;
                   16183:             }
                   16184:             if ($fixeddom) {
                   16185:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16186:                                     ' value="'.$codedom.'" />'.
                   16187:                                     &Apache::lonnet::domain($codedom,'description');
                   16188:             } else {
                   16189:                 $domainselectform = &select_dom_form($filter->{$item},
                   16190:                                                      'domainfilter',
                   16191:                                                       $allow_blank,'',$onchange);
                   16192:             }
                   16193:         } else {
                   16194:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16195:         }
                   16196:     }
                   16197: 
                   16198:     # last course activity filter and selection
                   16199:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16200: 
                   16201:     # course created filter and selection
                   16202:     if (exists($filter->{'createdfilter'})) {
                   16203:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16204:     }
                   16205: 
1.1239    raeburn  16206:     my $prefix = $crstype;
                   16207:     if ($crstype eq 'Placement') {
                   16208:         $prefix = 'Placement Test'
                   16209:     }
1.1181    raeburn  16210:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  16211:                 'cac' => "$prefix Activity",
                   16212:                 'ccr' => "$prefix Created",
                   16213:                 'cde' => "$prefix Title",
                   16214:                 'cdo' => "$prefix Domain",
1.1181    raeburn  16215:                 'ins' => 'Institutional Code',
                   16216:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  16217:                 'cow' => "$prefix Owner/Co-owner",
                   16218:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  16219:                 'cog' => 'Type',
                   16220:              );
                   16221: 
                   16222:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16223:         my $typeval = 'Course';
                   16224:         if ($crstype eq 'Community') {
                   16225:             $typeval = 'Community';
1.1239    raeburn  16226:         } elsif ($crstype eq 'Placement') {
                   16227:             $typeval = 'Placement';
1.1181    raeburn  16228:         }
                   16229:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16230:     } else {
                   16231:         $typeselectform =  '<select name="type" size="1"';
                   16232:         if ($onchange) {
                   16233:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16234:         }
                   16235:         $typeselectform .= '>'."\n";
1.1237    raeburn  16236:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  16237:             my $shown;
                   16238:             if ($posstype eq 'Placement') {
                   16239:                 $shown = &mt('Placement Test');
                   16240:             } else {
                   16241:                 $shown = &mt($posstype);
                   16242:             }
1.1181    raeburn  16243:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  16244:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  16245:         }
                   16246:         $typeselectform.="</select>";
                   16247:     }
                   16248: 
                   16249:     my ($cloneableonlyform,$cloneabletitle);
                   16250:     if (exists($filter->{'cloneableonly'})) {
                   16251:         my $cloneableon = '';
                   16252:         my $cloneableoff = ' checked="checked"';
                   16253:         if ($filter->{'cloneableonly'}) {
                   16254:             $cloneableon = $cloneableoff;
                   16255:             $cloneableoff = '';
                   16256:         }
                   16257:         $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>';
                   16258:         if ($formname eq 'ccrs') {
1.1187    bisitz   16259:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  16260:         } else {
                   16261:             $cloneabletitle = &mt('Cloneable by you');
                   16262:         }
                   16263:     }
                   16264:     my $officialjs;
                   16265:     if ($crstype eq 'Course') {
                   16266:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  16267: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16268: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16269:             if ($codedom) { 
1.1181    raeburn  16270:                 $officialjs = 1;
                   16271:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16272:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16273:                                                                   $officialjs,$codetitlesref);
                   16274:                 if ($jscript) {
1.1182    raeburn  16275:                     $jscript = '<script type="text/javascript">'."\n".
                   16276:                                '// <![CDATA['."\n".
                   16277:                                $jscript."\n".
                   16278:                                '// ]]>'."\n".
                   16279:                                '</script>'."\n";
1.1181    raeburn  16280:                 }
                   16281:             }
                   16282:             if ($instcodeform eq '') {
                   16283:                 $instcodeform =
                   16284:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16285:                     $list->{'instcodefilter'}.'" />';
                   16286:                 $instcodetitle = $lt{'ins'};
                   16287:             } else {
                   16288:                 $instcodetitle = $lt{'inc'};
                   16289:             }
                   16290:             if ($fixeddom) {
                   16291:                 $instcodetitle .= '<br />('.$codedom.')';
                   16292:             }
                   16293:         }
                   16294:     }
                   16295:     my $output = qq|
                   16296: <form method="post" name="filterpicker" action="$action">
                   16297: <input type="hidden" name="form" value="$formname" />
                   16298: |;
                   16299:     if ($formname eq 'modifycourse') {
                   16300:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16301:                    '<input type="hidden" name="prevphase" value="'.
                   16302:                    $prevphase.'" />'."\n";
1.1198    musolffc 16303:     } elsif ($formname eq 'quotacheck') {
                   16304:         $output .= qq|
                   16305: <input type="hidden" name="sortby" value="" />
                   16306: <input type="hidden" name="sortorder" value="" />
                   16307: |;
                   16308:     } else {
1.1181    raeburn  16309:         my $name_input;
                   16310:         if ($cnameelement ne '') {
                   16311:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16312:                           $cnameelement.'" />';
                   16313:         }
                   16314:         $output .= qq|
1.1182    raeburn  16315: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16316: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  16317: $name_input
                   16318: $roleelement
                   16319: $multelement
                   16320: $typeelement
                   16321: |;
                   16322:         if ($formname eq 'portform') {
                   16323:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16324:         }
                   16325:     }
                   16326:     if ($fixeddom) {
                   16327:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16328:     }
                   16329:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16330:     if ($sincefilterform) {
                   16331:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16332:                   .$sincefilterform
                   16333:                   .&Apache::lonhtmlcommon::row_closure();
                   16334:     }
                   16335:     if ($createdfilterform) {
                   16336:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16337:                   .$createdfilterform
                   16338:                   .&Apache::lonhtmlcommon::row_closure();
                   16339:     }
                   16340:     if ($domainselectform) {
                   16341:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16342:                   .$domainselectform
                   16343:                   .&Apache::lonhtmlcommon::row_closure();
                   16344:     }
                   16345:     if ($typeselectform) {
                   16346:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16347:             $output .= $typeselectform;
                   16348:         } else {
                   16349:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16350:                       .$typeselectform
                   16351:                       .&Apache::lonhtmlcommon::row_closure();
                   16352:         }
                   16353:     }
                   16354:     if ($instcodeform) {
                   16355:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16356:                   .$instcodeform
                   16357:                   .&Apache::lonhtmlcommon::row_closure();
                   16358:     }
                   16359:     if (exists($filter->{'ownerfilter'})) {
                   16360:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16361:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16362:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16363:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16364:                    $ownerdomselectform.'</td></tr></table>'.
                   16365:                    &Apache::lonhtmlcommon::row_closure();
                   16366:     }
                   16367:     if (exists($filter->{'personfilter'})) {
                   16368:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16369:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16370:                    '<input type="text" name="personfilter" size="20" value="'.
                   16371:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16372:                    $persondomselectform.'</td></tr></table>'.
                   16373:                    &Apache::lonhtmlcommon::row_closure();
                   16374:     }
                   16375:     if (exists($filter->{'coursefilter'})) {
                   16376:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16377:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16378:                   .$list->{'coursefilter'}.'" />'
                   16379:                   .&Apache::lonhtmlcommon::row_closure();
                   16380:     }
                   16381:     if ($cloneableonlyform) {
                   16382:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16383:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16384:     }
                   16385:     if (exists($filter->{'descriptfilter'})) {
                   16386:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16387:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16388:                   .$list->{'descriptfilter'}.'" />'
                   16389:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16390:     }
                   16391:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16392:                '<input type="hidden" name="updater" value="" />'."\n".
                   16393:                '<input type="submit" name="gosearch" value="'.
                   16394:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16395:     return $jscript.$clonewarning.$output;
                   16396: }
                   16397: 
                   16398: =pod 
                   16399: 
                   16400: =item * &timebased_select_form()
                   16401: 
1.1182    raeburn  16402: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  16403: filter e.g., Course Activity, Course Created, when searching for courses
                   16404: or communities
                   16405: 
                   16406: Inputs:
                   16407: 
                   16408: item - name of form element (sincefilter or createdfilter)
                   16409: 
                   16410: filter - anonymous hash of criteria and their values
                   16411: 
                   16412: Returns: HTML for a select box contained a blank, then six time selections,
                   16413:          with value set in incoming form variables currently selected. 
                   16414: 
                   16415: Side Effects: None
                   16416: 
                   16417: =cut
                   16418: 
                   16419: sub timebased_select_form {
                   16420:     my ($item,$filter) = @_;
                   16421:     if (ref($filter) eq 'HASH') {
                   16422:         $filter->{$item} =~ s/[^\d-]//g;
                   16423:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16424:         return &select_form(
                   16425:                             $filter->{$item},
                   16426:                             $item,
                   16427:                             {      '-1' => '',
                   16428:                                 '86400' => &mt('today'),
                   16429:                                '604800' => &mt('last week'),
                   16430:                               '2592000' => &mt('last month'),
                   16431:                               '7776000' => &mt('last three months'),
                   16432:                              '15552000' => &mt('last six months'),
                   16433:                              '31104000' => &mt('last year'),
                   16434:                     'select_form_order' =>
                   16435:                            ['-1','86400','604800','2592000','7776000',
                   16436:                             '15552000','31104000']});
                   16437:     }
                   16438: }
                   16439: 
                   16440: =pod
                   16441: 
                   16442: =item * &js_changer()
                   16443: 
                   16444: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  16445: when course type or domain is changed, and also to hide 'Searching ...' on
                   16446: page load completion for page showing search result.
1.1181    raeburn  16447: 
                   16448: Inputs: None
                   16449: 
1.1183    raeburn  16450: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  16451: 
                   16452: Side Effects: None
                   16453: 
                   16454: =cut
                   16455: 
                   16456: sub js_changer {
                   16457:     return <<ENDJS;
                   16458: <script type="text/javascript">
                   16459: // <![CDATA[
                   16460: function updateFilters(caller) {
                   16461:     if (typeof(caller) != "undefined") {
                   16462:         document.filterpicker.updater.value = caller.name;
                   16463:     }
                   16464:     document.filterpicker.submit();
                   16465: }
1.1183    raeburn  16466: 
                   16467: function hideSearching() {
                   16468:     if (document.getElementById('searching')) {
                   16469:         document.getElementById('searching').style.display = 'none';
                   16470:     }
                   16471:     return;
                   16472: }
                   16473: 
1.1181    raeburn  16474: // ]]>
                   16475: </script>
                   16476: 
                   16477: ENDJS
                   16478: }
                   16479: 
                   16480: =pod
                   16481: 
1.1182    raeburn  16482: =item * &search_courses()
                   16483: 
                   16484: Process selected filters form course search form and pass to lonnet::courseiddump
                   16485: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16486: 
                   16487: Inputs:
                   16488: 
                   16489: dom - domain being searched 
                   16490: 
                   16491: type - course type ('Course' or 'Community' or '.' if any).
                   16492: 
                   16493: filter - anonymous hash of criteria and their values
                   16494: 
                   16495: numtitles - for institutional codes - number of categories
                   16496: 
                   16497: cloneruname - optional username of new course owner
                   16498: 
                   16499: clonerudom - optional domain of new course owner
                   16500: 
1.1221    raeburn  16501: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  16502:             (used when DC is using course creation form)
                   16503: 
                   16504: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16505: 
1.1221    raeburn  16506: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16507:            (and so can clone automatically)
                   16508: 
                   16509: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16510: 
                   16511: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   16512:               courses to clone 
1.1182    raeburn  16513: 
                   16514: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16515: 
                   16516: 
                   16517: Side Effects: None
                   16518: 
                   16519: =cut
                   16520: 
                   16521: 
                   16522: sub search_courses {
1.1221    raeburn  16523:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16524:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  16525:     my (%courses,%showcourses,$cloner);
                   16526:     if (($filter->{'ownerfilter'} ne '') ||
                   16527:         ($filter->{'ownerdomfilter'} ne '')) {
                   16528:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16529:                                        $filter->{'ownerdomfilter'};
                   16530:     }
                   16531:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16532:         if (!$filter->{$item}) {
                   16533:             $filter->{$item}='.';
                   16534:         }
                   16535:     }
                   16536:     my $now = time;
                   16537:     my $timefilter =
                   16538:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16539:     my ($createdbefore,$createdafter);
                   16540:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16541:         $createdbefore = $now;
                   16542:         $createdafter = $now-$filter->{'createdfilter'};
                   16543:     }
                   16544:     my ($instcodefilter,$regexpok);
                   16545:     if ($numtitles) {
                   16546:         if ($env{'form.official'} eq 'on') {
                   16547:             $instcodefilter =
                   16548:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16549:             $regexpok = 1;
                   16550:         } elsif ($env{'form.official'} eq 'off') {
                   16551:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16552:             unless ($instcodefilter eq '') {
                   16553:                 $regexpok = -1;
                   16554:             }
                   16555:         }
                   16556:     } else {
                   16557:         $instcodefilter = $filter->{'instcodefilter'};
                   16558:     }
                   16559:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16560:     if ($type eq '') { $type = '.'; }
                   16561: 
                   16562:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16563:         $cloner = $cloneruname.':'.$clonerudom;
                   16564:     }
                   16565:     %courses = &Apache::lonnet::courseiddump($dom,
                   16566:                                              $filter->{'descriptfilter'},
                   16567:                                              $timefilter,
                   16568:                                              $instcodefilter,
                   16569:                                              $filter->{'combownerfilter'},
                   16570:                                              $filter->{'coursefilter'},
                   16571:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  16572:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  16573:                                              $filter->{'cloneableonly'},
                   16574:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  16575:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  16576:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16577:         my $ccrole;
                   16578:         if ($type eq 'Community') {
                   16579:             $ccrole = 'co';
                   16580:         } else {
                   16581:             $ccrole = 'cc';
                   16582:         }
                   16583:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16584:                                                      $filter->{'persondomfilter'},
                   16585:                                                      'userroles',undef,
                   16586:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16587:                                                      $dom);
                   16588:         foreach my $role (keys(%rolehash)) {
                   16589:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16590:             my $cid = $cdom.'_'.$cnum;
                   16591:             if (exists($courses{$cid})) {
                   16592:                 if (ref($courses{$cid}) eq 'HASH') {
                   16593:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16594:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
                   16595:                             push (@{$courses{$cid}{roles}},$courserole);
                   16596:                         }
                   16597:                     } else {
                   16598:                         $courses{$cid}{roles} = [$courserole];
                   16599:                     }
                   16600:                     $showcourses{$cid} = $courses{$cid};
                   16601:                 }
                   16602:             }
                   16603:         }
                   16604:         %courses = %showcourses;
                   16605:     }
                   16606:     return %courses;
                   16607: }
                   16608: 
                   16609: =pod
                   16610: 
1.1181    raeburn  16611: =back
                   16612: 
1.1207    raeburn  16613: =head1 Routines for version requirements for current course.
                   16614: 
                   16615: =over 4
                   16616: 
                   16617: =item * &check_release_required()
                   16618: 
                   16619: Compares required LON-CAPA version with version on server, and
                   16620: if required version is newer looks for a server with the required version.
                   16621: 
                   16622: Looks first at servers in user's owen domain; if none suitable, looks at
                   16623: servers in course's domain are permitted to host sessions for user's domain.
                   16624: 
                   16625: Inputs:
                   16626: 
                   16627: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16628: 
                   16629: $courseid - Course ID of current course
                   16630: 
                   16631: $rolecode - User's current role in course (for switchserver query string).
                   16632: 
                   16633: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16634: 
                   16635: 
                   16636: Returns:
                   16637: 
                   16638: $switchserver - query string tp append to /adm/switchserver call (if 
                   16639:                 current server's LON-CAPA version is too old. 
                   16640: 
                   16641: $warning - Message is displayed if no suitable server could be found.
                   16642: 
                   16643: =cut
                   16644: 
                   16645: sub check_release_required {
                   16646:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16647:     my ($switchserver,$warning);
                   16648:     if ($required ne '') {
                   16649:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16650:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16651:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16652:             my $otherserver;
                   16653:             if (($major eq '' && $minor eq '') ||
                   16654:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16655:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16656:                 my $switchlcrev =
                   16657:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16658:                                                            $userdomserver);
                   16659:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16660:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16661:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16662:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16663:                     if ($cdom ne $env{'user.domain'}) {
                   16664:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16665:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16666:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16667:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16668:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16669:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16670:                         my $canhost =
                   16671:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16672:                                                               $coursedomserver,
                   16673:                                                               $remoterev,
                   16674:                                                               $udomdefaults{'remotesessions'},
                   16675:                                                               $defdomdefaults{'hostedsessions'});
                   16676: 
                   16677:                         if ($canhost) {
                   16678:                             $otherserver = $coursedomserver;
                   16679:                         } else {
                   16680:                             $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.");
                   16681:                         }
                   16682:                     } else {
                   16683:                         $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).");
                   16684:                     }
                   16685:                 } else {
                   16686:                     $otherserver = $userdomserver;
                   16687:                 }
                   16688:             }
                   16689:             if ($otherserver ne '') {
                   16690:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16691:             }
                   16692:         }
                   16693:     }
                   16694:     return ($switchserver,$warning);
                   16695: }
                   16696: 
                   16697: =pod
                   16698: 
                   16699: =item * &check_release_result()
                   16700: 
                   16701: Inputs:
                   16702: 
                   16703: $switchwarning - Warning message if no suitable server found to host session.
                   16704: 
                   16705: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16706:                 and current role.
                   16707: 
                   16708: Returns: HTML to display with information about requirement to switch server.
                   16709:          Either displaying warning with link to Roles/Courses screen or
                   16710:          display link to switchserver.
                   16711: 
1.1181    raeburn  16712: =cut
                   16713: 
1.1207    raeburn  16714: sub check_release_result {
                   16715:     my ($switchwarning,$switchserver) = @_;
                   16716:     my $output = &start_page('Selected course unavailable on this server').
                   16717:                  '<p class="LC_warning">';
                   16718:     if ($switchwarning) {
                   16719:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16720:         if (&show_course()) {
                   16721:             $output .= &mt('Display courses');
                   16722:         } else {
                   16723:             $output .= &mt('Display roles');
                   16724:         }
                   16725:         $output .= '</a>';
                   16726:     } elsif ($switchserver) {
                   16727:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16728:                    '<br />'.
                   16729:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16730:                    &mt('Switch Server').
                   16731:                    '</a>';
                   16732:     }
                   16733:     $output .= '</p>'.&end_page();
                   16734:     return $output;
                   16735: }
                   16736: 
                   16737: =pod
                   16738: 
                   16739: =item * &needs_coursereinit()
                   16740: 
                   16741: Determine if course contents stored for user's session needs to be
                   16742: refreshed, because content has changed since "Big Hash" last tied.
                   16743: 
                   16744: Check for change is made if time last checked is more than 10 minutes ago
                   16745: (by default).
                   16746: 
                   16747: Inputs:
                   16748: 
                   16749: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16750: 
                   16751: $interval (optional) - Time which may elapse (in s) between last check for content
                   16752:                        change in current course. (default: 600 s).  
                   16753: 
                   16754: Returns: an array; first element is:
                   16755: 
                   16756: =over 4
                   16757: 
                   16758: 'switch' - if content updates mean user's session
                   16759:            needs to be switched to a server running a newer LON-CAPA version
                   16760:  
                   16761: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16762:            on current server hosting user's session                
                   16763: 
                   16764: ''       - if no action required.
                   16765: 
                   16766: =back
                   16767: 
                   16768: If first item element is 'switch':
                   16769: 
                   16770: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   16771: 
                   16772: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16773:                               and current role. 
                   16774: 
                   16775: otherwise: no other elements returned.
                   16776: 
                   16777: =back
                   16778: 
                   16779: =cut
                   16780: 
                   16781: sub needs_coursereinit {
                   16782:     my ($loncaparev,$interval) = @_;
                   16783:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16784:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16785:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16786:     my $now = time;
                   16787:     if ($interval eq '') {
                   16788:         $interval = 600;
                   16789:     }
                   16790:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16791:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16792:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16793:         if ($lastchange > $env{'request.course.tied'}) {
                   16794:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16795:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16796:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16797:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16798:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16799:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16800:                     my ($switchserver,$switchwarning) =
                   16801:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16802:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16803:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16804:                         return ('switch',$switchwarning,$switchserver);
                   16805:                     }
                   16806:                 }
                   16807:             }
                   16808:             return ('update');
                   16809:         }
                   16810:     }
                   16811:     return ();
                   16812: }
1.1181    raeburn  16813: 
1.1083    raeburn  16814: sub update_content_constraints {
                   16815:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16816:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16817:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16818:     my %checkresponsetypes;
                   16819:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  16820:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  16821:         if ($item eq 'resourcetag') {
                   16822:             if ($name eq 'responsetype') {
                   16823:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16824:             }
                   16825:         }
                   16826:     }
                   16827:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16828:     if (defined($navmap)) {
                   16829:         my %allresponses;
                   16830:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16831:             my %responses = $res->responseTypes();
                   16832:             foreach my $key (keys(%responses)) {
                   16833:                 next unless(exists($checkresponsetypes{$key}));
                   16834:                 $allresponses{$key} += $responses{$key};
                   16835:             }
                   16836:         }
                   16837:         foreach my $key (keys(%allresponses)) {
                   16838:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16839:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16840:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16841:             }
                   16842:         }
                   16843:         undef($navmap);
                   16844:     }
                   16845:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16846:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16847:     }
                   16848:     return;
                   16849: }
                   16850: 
1.1110    raeburn  16851: sub allmaps_incourse {
                   16852:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16853:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16854:         $cid = $env{'request.course.id'};
                   16855:         $cdom = $env{'course.'.$cid.'.domain'};
                   16856:         $cnum = $env{'course.'.$cid.'.num'};
                   16857:         $chome = $env{'course.'.$cid.'.home'};
                   16858:     }
                   16859:     my %allmaps = ();
                   16860:     my $lastchange =
                   16861:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16862:     if ($lastchange > $env{'request.course.tied'}) {
                   16863:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16864:         unless ($ferr) {
                   16865:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16866:         }
                   16867:     }
                   16868:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16869:     if (defined($navmap)) {
                   16870:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16871:             $allmaps{$res->src()} = 1;
                   16872:         }
                   16873:     }
                   16874:     return \%allmaps;
                   16875: }
                   16876: 
1.1083    raeburn  16877: sub parse_supplemental_title {
                   16878:     my ($title) = @_;
                   16879: 
                   16880:     my ($foldertitle,$renametitle);
                   16881:     if ($title =~ /&amp;&amp;&amp;/) {
                   16882:         $title = &HTML::Entites::decode($title);
                   16883:     }
                   16884:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16885:         $renametitle=$4;
                   16886:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16887:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16888:         my $name =  &plainname($uname,$udom);
                   16889:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16890:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16891:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16892:             $name.': <br />'.$foldertitle;
                   16893:     }
                   16894:     if (wantarray) {
                   16895:         return ($title,$foldertitle,$renametitle);
                   16896:     }
                   16897:     return $title;
                   16898: }
                   16899: 
1.1143    raeburn  16900: sub recurse_supplemental {
                   16901:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16902:     if ($suppmap) {
                   16903:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16904:         if ($fatal) {
                   16905:             $errors ++;
                   16906:         } else {
                   16907:             if ($#LONCAPA::map::resources > 0) {
                   16908:                 foreach my $res (@LONCAPA::map::resources) {
                   16909:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16910:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  16911:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16912:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1143    raeburn  16913:                         } else {
                   16914:                             $numfiles ++;
                   16915:                         }
                   16916:                     }
                   16917:                 }
                   16918:             }
                   16919:         }
                   16920:     }
                   16921:     return ($numfiles,$errors);
                   16922: }
                   16923: 
1.1101    raeburn  16924: sub symb_to_docspath {
                   16925:     my ($symb) = @_;
                   16926:     return unless ($symb);
                   16927:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16928:     if ($resurl=~/\.(sequence|page)$/) {
                   16929:         $mapurl=$resurl;
                   16930:     } elsif ($resurl eq 'adm/navmaps') {
                   16931:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16932:     }
                   16933:     my $mapresobj;
                   16934:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16935:     if (ref($navmap)) {
                   16936:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   16937:     }
                   16938:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16939:     my $type=$2;
                   16940:     my $path;
                   16941:     if (ref($mapresobj)) {
                   16942:         my $pcslist = $mapresobj->map_hierarchy();
                   16943:         if ($pcslist ne '') {
                   16944:             foreach my $pc (split(/,/,$pcslist)) {
                   16945:                 next if ($pc <= 1);
                   16946:                 my $res = $navmap->getByMapPc($pc);
                   16947:                 if (ref($res)) {
                   16948:                     my $thisurl = $res->src();
                   16949:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16950:                     my $thistitle = $res->title();
                   16951:                     $path .= '&'.
                   16952:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  16953:                              &escape($thistitle).
1.1101    raeburn  16954:                              ':'.$res->randompick().
                   16955:                              ':'.$res->randomout().
                   16956:                              ':'.$res->encrypted().
                   16957:                              ':'.$res->randomorder().
                   16958:                              ':'.$res->is_page();
                   16959:                 }
                   16960:             }
                   16961:         }
                   16962:         $path =~ s/^\&//;
                   16963:         my $maptitle = $mapresobj->title();
                   16964:         if ($mapurl eq 'default') {
1.1129    raeburn  16965:             $maptitle = 'Main Content';
1.1101    raeburn  16966:         }
                   16967:         $path .= (($path ne '')? '&' : '').
                   16968:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  16969:                  &escape($maptitle).
1.1101    raeburn  16970:                  ':'.$mapresobj->randompick().
                   16971:                  ':'.$mapresobj->randomout().
                   16972:                  ':'.$mapresobj->encrypted().
                   16973:                  ':'.$mapresobj->randomorder().
                   16974:                  ':'.$mapresobj->is_page();
                   16975:     } else {
                   16976:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16977:         my $ispage = (($type eq 'page')? 1 : '');
                   16978:         if ($mapurl eq 'default') {
1.1129    raeburn  16979:             $maptitle = 'Main Content';
1.1101    raeburn  16980:         }
                   16981:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  16982:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  16983:     }
                   16984:     unless ($mapurl eq 'default') {
                   16985:         $path = 'default&'.
1.1146    raeburn  16986:                 &escape('Main Content').
1.1101    raeburn  16987:                 ':::::&'.$path;
                   16988:     }
                   16989:     return $path;
                   16990: }
                   16991: 
1.1094    raeburn  16992: sub captcha_display {
                   16993:     my ($context,$lonhost) = @_;
                   16994:     my ($output,$error);
1.1234    raeburn  16995:     my ($captcha,$pubkey,$privkey,$version) = 
                   16996:         &get_captcha_config($context,$lonhost);
1.1095    raeburn  16997:     if ($captcha eq 'original') {
1.1094    raeburn  16998:         $output = &create_captcha();
                   16999:         unless ($output) {
1.1172    raeburn  17000:             $error = 'captcha';
1.1094    raeburn  17001:         }
                   17002:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17003:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  17004:         unless ($output) {
1.1172    raeburn  17005:             $error = 'recaptcha';
1.1094    raeburn  17006:         }
                   17007:     }
1.1234    raeburn  17008:     return ($output,$error,$captcha,$version);
1.1094    raeburn  17009: }
                   17010: 
                   17011: sub captcha_response {
                   17012:     my ($context,$lonhost) = @_;
                   17013:     my ($captcha_chk,$captcha_error);
1.1234    raeburn  17014:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  17015:     if ($captcha eq 'original') {
1.1094    raeburn  17016:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17017:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17018:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  17019:     } else {
                   17020:         $captcha_chk = 1;
                   17021:     }
                   17022:     return ($captcha_chk,$captcha_error);
                   17023: }
                   17024: 
                   17025: sub get_captcha_config {
                   17026:     my ($context,$lonhost) = @_;
1.1234    raeburn  17027:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  17028:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17029:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17030:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  17031:     if ($context eq 'usercreation') {
                   17032:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17033:         if (ref($domconfig{$context}) eq 'HASH') {
                   17034:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17035:             if (ref($hashtocheck) eq 'HASH') {
                   17036:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17037:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17038:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17039:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17040:                     }
                   17041:                     if ($privkey && $pubkey) {
                   17042:                         $captcha = 'recaptcha';
1.1234    raeburn  17043:                         $version = $hashtocheck->{'recaptchaversion'};
                   17044:                         if ($version ne '2') {
                   17045:                             $version = 1;
                   17046:                         }
1.1095    raeburn  17047:                     } else {
                   17048:                         $captcha = 'original';
                   17049:                     }
                   17050:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17051:                     $captcha = 'original';
                   17052:                 }
1.1094    raeburn  17053:             }
1.1095    raeburn  17054:         } else {
                   17055:             $captcha = 'captcha';
                   17056:         }
                   17057:     } elsif ($context eq 'login') {
                   17058:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17059:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17060:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17061:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  17062:             if ($privkey && $pubkey) {
                   17063:                 $captcha = 'recaptcha';
1.1234    raeburn  17064:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17065:                 if ($version ne '2') {
                   17066:                     $version = 1; 
                   17067:                 }
1.1095    raeburn  17068:             } else {
                   17069:                 $captcha = 'original';
1.1094    raeburn  17070:             }
1.1095    raeburn  17071:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17072:             $captcha = 'original';
1.1094    raeburn  17073:         }
                   17074:     }
1.1234    raeburn  17075:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  17076: }
                   17077: 
                   17078: sub create_captcha {
                   17079:     my %captcha_params = &captcha_settings();
                   17080:     my ($output,$maxtries,$tries) = ('',10,0);
                   17081:     while ($tries < $maxtries) {
                   17082:         $tries ++;
                   17083:         my $captcha = Authen::Captcha->new (
                   17084:                                            output_folder => $captcha_params{'output_dir'},
                   17085:                                            data_folder   => $captcha_params{'db_dir'},
                   17086:                                           );
                   17087:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17088: 
                   17089:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17090:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17091:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  17092:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17093:                       '<br />'.
                   17094:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  17095:             last;
                   17096:         }
                   17097:     }
                   17098:     return $output;
                   17099: }
                   17100: 
                   17101: sub captcha_settings {
                   17102:     my %captcha_params = (
                   17103:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17104:                            www_output_dir => "/captchaspool",
                   17105:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17106:                            numchars       => '5',
                   17107:                          );
                   17108:     return %captcha_params;
                   17109: }
                   17110: 
                   17111: sub check_captcha {
                   17112:     my ($captcha_chk,$captcha_error);
                   17113:     my $code = $env{'form.code'};
                   17114:     my $md5sum = $env{'form.crypt'};
                   17115:     my %captcha_params = &captcha_settings();
                   17116:     my $captcha = Authen::Captcha->new(
                   17117:                       output_folder => $captcha_params{'output_dir'},
                   17118:                       data_folder   => $captcha_params{'db_dir'},
                   17119:                   );
1.1109    raeburn  17120:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  17121:     my %captcha_hash = (
                   17122:                         0       => 'Code not checked (file error)',
                   17123:                        -1      => 'Failed: code expired',
                   17124:                        -2      => 'Failed: invalid code (not in database)',
                   17125:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17126:     );
                   17127:     if ($captcha_chk != 1) {
                   17128:         $captcha_error = $captcha_hash{$captcha_chk}
                   17129:     }
                   17130:     return ($captcha_chk,$captcha_error);
                   17131: }
                   17132: 
                   17133: sub create_recaptcha {
1.1234    raeburn  17134:     my ($pubkey,$version) = @_;
                   17135:     if ($version >= 2) {
                   17136:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17137:     } else {
                   17138:         my $use_ssl;
                   17139:         if ($ENV{'SERVER_PORT'} == 443) {
                   17140:             $use_ssl = 1;
                   17141:         }
                   17142:         my $captcha = Captcha::reCAPTCHA->new;
                   17143:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17144:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17145:                &mt('If the text is hard to read, [_1] will replace them.',
                   17146:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17147:                '<br /><br />';
                   17148:     }
1.1094    raeburn  17149: }
                   17150: 
                   17151: sub check_recaptcha {
1.1234    raeburn  17152:     my ($privkey,$version) = @_;
1.1094    raeburn  17153:     my $captcha_chk;
1.1234    raeburn  17154:     if ($version >= 2) {
                   17155:         my $ua = LWP::UserAgent->new;
                   17156:         $ua->timeout(10);
                   17157:         my %info = (
                   17158:                      secret   => $privkey, 
                   17159:                      response => $env{'form.g-recaptcha-response'},
                   17160:                      remoteip => $ENV{'REMOTE_ADDR'},
                   17161:                    );
                   17162:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   17163:         if ($response->is_success)  {
                   17164:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17165:             if (ref($data) eq 'HASH') {
                   17166:                 if ($data->{'success'}) {
                   17167:                     $captcha_chk = 1;
                   17168:                 }
                   17169:             }
                   17170:         }
                   17171:     } else {
                   17172:         my $captcha = Captcha::reCAPTCHA->new;
                   17173:         my $captcha_result =
                   17174:             $captcha->check_answer(
                   17175:                                     $privkey,
                   17176:                                     $ENV{'REMOTE_ADDR'},
                   17177:                                     $env{'form.recaptcha_challenge_field'},
                   17178:                                     $env{'form.recaptcha_response_field'},
                   17179:                                   );
                   17180:         if ($captcha_result->{is_valid}) {
                   17181:             $captcha_chk = 1;
                   17182:         }
1.1094    raeburn  17183:     }
                   17184:     return $captcha_chk;
                   17185: }
                   17186: 
1.1174    raeburn  17187: sub emailusername_info {
1.1244    raeburn  17188:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  17189:     my %titles = &Apache::lonlocal::texthash (
                   17190:                      lastname      => 'Last Name',
                   17191:                      firstname     => 'First Name',
                   17192:                      institution   => 'School/college/university',
                   17193:                      location      => "School's city, state/province, country",
                   17194:                      web           => "School's web address",
                   17195:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  17196:                      id            => 'Student/Employee ID',
1.1174    raeburn  17197:                  );
                   17198:     return (\@fields,\%titles);
                   17199: }
                   17200: 
1.1161    raeburn  17201: sub cleanup_html {
                   17202:     my ($incoming) = @_;
                   17203:     my $outgoing;
                   17204:     if ($incoming ne '') {
                   17205:         $outgoing = $incoming;
                   17206:         $outgoing =~ s/;/&#059;/g;
                   17207:         $outgoing =~ s/\#/&#035;/g;
                   17208:         $outgoing =~ s/\&/&#038;/g;
                   17209:         $outgoing =~ s/</&#060;/g;
                   17210:         $outgoing =~ s/>/&#062;/g;
                   17211:         $outgoing =~ s/\(/&#040/g;
                   17212:         $outgoing =~ s/\)/&#041;/g;
                   17213:         $outgoing =~ s/"/&#034;/g;
                   17214:         $outgoing =~ s/'/&#039;/g;
                   17215:         $outgoing =~ s/\$/&#036;/g;
                   17216:         $outgoing =~ s{/}{&#047;}g;
                   17217:         $outgoing =~ s/=/&#061;/g;
                   17218:         $outgoing =~ s/\\/&#092;/g
                   17219:     }
                   17220:     return $outgoing;
                   17221: }
                   17222: 
1.1190    musolffc 17223: # Checks for critical messages and returns a redirect url if one exists.
                   17224: # $interval indicates how often to check for messages.
                   17225: sub critical_redirect {
                   17226:     my ($interval) = @_;
                   17227:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   17228:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   17229:                                         $env{'user.name'});
                   17230:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  17231:         my $redirecturl;
1.1190    musolffc 17232:         if ($what[0]) {
                   17233: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   17234: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  17235: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17236:                 return (1, $url);
1.1190    musolffc 17237:             }
1.1191    raeburn  17238:         }
                   17239:     } 
                   17240:     return ();
1.1190    musolffc 17241: }
                   17242: 
1.1174    raeburn  17243: # Use:
                   17244: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17245: #
                   17246: ##################################################
                   17247: #          password associated functions         #
                   17248: ##################################################
                   17249: sub des_keys {
                   17250:     # Make a new key for DES encryption.
                   17251:     # Each key has two parts which are returned separately.
                   17252:     # Please note:  Each key must be passed through the &hex function
                   17253:     # before it is output to the web browser.  The hex versions cannot
                   17254:     # be used to decrypt.
                   17255:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17256:                 '8','9','a','b','c','d','e','f');
                   17257:     my $lkey='';
                   17258:     for (0..7) {
                   17259:         $lkey.=$hexstr[rand(15)];
                   17260:     }
                   17261:     my $ukey='';
                   17262:     for (0..7) {
                   17263:         $ukey.=$hexstr[rand(15)];
                   17264:     }
                   17265:     return ($lkey,$ukey);
                   17266: }
                   17267: 
                   17268: sub des_decrypt {
                   17269:     my ($key,$cyphertext) = @_;
                   17270:     my $keybin=pack("H16",$key);
                   17271:     my $cypher;
                   17272:     if ($Crypt::DES::VERSION>=2.03) {
                   17273:         $cypher=new Crypt::DES $keybin;
                   17274:     } else {
                   17275:         $cypher=new DES $keybin;
                   17276:     }
1.1233    raeburn  17277:     my $plaintext='';
                   17278:     my $cypherlength = length($cyphertext);
                   17279:     my $numchunks = int($cypherlength/32);
                   17280:     for (my $j=0; $j<$numchunks; $j++) {
                   17281:         my $start = $j*32;
                   17282:         my $cypherblock = substr($cyphertext,$start,32);
                   17283:         my $chunk =
                   17284:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17285:         $chunk .=
                   17286:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17287:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17288:         $plaintext .= $chunk;
                   17289:     }
1.1174    raeburn  17290:     return $plaintext;
                   17291: }
                   17292: 
1.112     bowersj2 17293: 1;
                   17294: __END__;
1.41      ng       17295: 

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