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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1075.2.127.  .1(raebu    4:17): # $Id: loncommon.pm,v 1.1075.2.127 2017/04/02 03:09:27 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1075.2.25  raeburn    70: use Apache::lonuserutils();
1.1075.2.27  raeburn    71: use Apache::lonuserstate();
1.1075.2.69  raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    74: use DateTime::TimeZone;
1.1075.2.102  raeburn    75: use DateTime::Locale;
1.1075.2.94  raeburn    76: use Encode();
1.1075.2.14  raeburn    77: use Authen::Captcha;
                     78: use Captcha::reCAPTCHA;
1.1075.2.107  raeburn    79: use JSON::DWIW;
                     80: use LWP::UserAgent;
1.1075.2.64  raeburn    81: use Crypt::DES;
                     82: use DynaLoader; # for Crypt::DES version
1.117     www        83: 
1.517     raeburn    84: # ---------------------------------------------- Designs
                     85: use vars qw(%defaultdesign);
                     86: 
1.22      www        87: my $readit;
                     88: 
1.517     raeburn    89: 
1.157     matthew    90: ##
                     91: ## Global Variables
                     92: ##
1.46      matthew    93: 
1.643     foxr       94: 
                     95: # ----------------------------------------------- SSI with retries:
                     96: #
                     97: 
                     98: =pod
                     99: 
1.648     raeburn   100: =head1 Server Side include with retries:
1.643     foxr      101: 
                    102: =over 4
                    103: 
1.648     raeburn   104: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      105: 
                    106: Performs an ssi with some number of retries.  Retries continue either
                    107: until the result is ok or until the retry count supplied by the
                    108: caller is exhausted.  
                    109: 
                    110: Inputs:
1.648     raeburn   111: 
                    112: =over 4
                    113: 
1.643     foxr      114: resource   - Identifies the resource to insert.
1.648     raeburn   115: 
1.643     foxr      116: retries    - Count of the number of retries allowed.
1.648     raeburn   117: 
1.643     foxr      118: form       - Hash that identifies the rendering options.
                    119: 
1.648     raeburn   120: =back
                    121: 
                    122: Returns:
                    123: 
                    124: =over 4
                    125: 
1.643     foxr      126: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   127: 
1.643     foxr      128: response   - The response from the last attempt (which may or may not have been successful.
                    129: 
1.648     raeburn   130: =back
                    131: 
                    132: =back
                    133: 
1.643     foxr      134: =cut
                    135: 
                    136: sub ssi_with_retries {
                    137:     my ($resource, $retries, %form) = @_;
                    138: 
                    139: 
                    140:     my $ok = 0;			# True if we got a good response.
                    141:     my $content;
                    142:     my $response;
                    143: 
                    144:     # Try to get the ssi done. within the retries count:
                    145: 
                    146:     do {
                    147: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    148: 	$ok      = $response->is_success;
1.650     www       149:         if (!$ok) {
                    150:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    151:         }
1.643     foxr      152: 	$retries--;
                    153:     } while (!$ok && ($retries > 0));
                    154: 
                    155:     if (!$ok) {
                    156: 	$content = '';		# On error return an empty content.
                    157:     }
                    158:     return ($content, $response);
                    159: 
                    160: }
                    161: 
                    162: 
                    163: 
1.20      www       164: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  165: my %language;
1.124     www       166: my %supported_language;
1.1048    foxr      167: my %latex_language;		# For choosing hyphenation in <transl..>
                    168: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  169: my %cprtag;
1.192     taceyjo1  170: my %scprtag;
1.351     www       171: my %fe; my %fd; my %fm;
1.41      ng        172: my %category_extensions;
1.12      harris41  173: 
1.46      matthew   174: # ---------------------------------------------- Thesaurus variables
1.144     matthew   175: #
                    176: # %Keywords:
                    177: #      A hash used by &keyword to determine if a word is considered a keyword.
                    178: # $thesaurus_db_file 
                    179: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   180: 
                    181: my %Keywords;
                    182: my $thesaurus_db_file;
                    183: 
1.144     matthew   184: #
                    185: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    186: # thesaurus.tab, and filecategories.tab.
                    187: #
1.18      www       188: BEGIN {
1.46      matthew   189:     # Variable initialization
                    190:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    191:     #
1.22      www       192:     unless ($readit) {
1.12      harris41  193: # ------------------------------------------------------------------- languages
                    194:     {
1.158     raeburn   195:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    196:                                    '/language.tab';
                    197:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  198:             while (my $line = <$fh>) {
                    199:                 next if ($line=~/^\#/);
                    200:                 chomp($line);
1.1048    foxr      201:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   202:                 $language{$key}=$val.' - '.$enc;
                    203:                 if ($sup) {
                    204:                     $supported_language{$key}=$sup;
                    205:                 }
1.1048    foxr      206: 		if ($latex) {
                    207: 		    $latex_language_bykey{$key} = $latex;
                    208: 		    $latex_language{$two} = $latex;
                    209: 		}
1.158     raeburn   210:             }
                    211:             close($fh);
                    212:         }
1.12      harris41  213:     }
                    214: # ------------------------------------------------------------------ copyrights
                    215:     {
1.158     raeburn   216:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    217:                                   '/copyright.tab';
                    218:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  219:             while (my $line = <$fh>) {
                    220:                 next if ($line=~/^\#/);
                    221:                 chomp($line);
                    222:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   223:                 $cprtag{$key}=$val;
                    224:             }
                    225:             close($fh);
                    226:         }
1.12      harris41  227:     }
1.351     www       228: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  229:     {
                    230:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    231:                                   '/source_copyright.tab';
                    232:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  233:             while (my $line = <$fh>) {
                    234:                 next if ($line =~ /^\#/);
                    235:                 chomp($line);
                    236:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  237:                 $scprtag{$key}=$val;
                    238:             }
                    239:             close($fh);
                    240:         }
                    241:     }
1.63      www       242: 
1.517     raeburn   243: # -------------------------------------------------------------- default domain designs
1.63      www       244:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   245:     my $designfile = $designdir.'/default.tab';
                    246:     if ( open (my $fh,"<$designfile") ) {
                    247:         while (my $line = <$fh>) {
                    248:             next if ($line =~ /^\#/);
                    249:             chomp($line);
                    250:             my ($key,$val)=(split(/\=/,$line));
                    251:             if ($val) { $defaultdesign{$key}=$val; }
                    252:         }
                    253:         close($fh);
1.63      www       254:     }
                    255: 
1.15      harris41  256: # ------------------------------------------------------------- file categories
                    257:     {
1.158     raeburn   258:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    259:                                   '/filecategories.tab';
                    260:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  261: 	    while (my $line = <$fh>) {
                    262: 		next if ($line =~ /^\#/);
                    263: 		chomp($line);
                    264:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1075.2.119  raeburn   265:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   266:             }
                    267:             close($fh);
                    268:         }
                    269: 
1.15      harris41  270:     }
1.12      harris41  271: # ------------------------------------------------------------------ file types
                    272:     {
1.158     raeburn   273:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    274:                '/filetypes.tab';
                    275:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  276:             while (my $line = <$fh>) {
                    277: 		next if ($line =~ /^\#/);
                    278: 		chomp($line);
                    279:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   280:                 if ($descr ne '') {
                    281:                     $fe{$ending}=lc($emb);
                    282:                     $fd{$ending}=$descr;
1.351     www       283:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   284:                 }
                    285:             }
                    286:             close($fh);
                    287:         }
1.12      harris41  288:     }
1.22      www       289:     &Apache::lonnet::logthis(
1.705     tempelho  290:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       291:     $readit=1;
1.46      matthew   292:     }  # end of unless($readit) 
1.32      matthew   293:     
                    294: }
1.112     bowersj2  295: 
1.42      matthew   296: ###############################################################
                    297: ##           HTML and Javascript Helper Functions            ##
                    298: ###############################################################
                    299: 
                    300: =pod 
                    301: 
1.112     bowersj2  302: =head1 HTML and Javascript Functions
1.42      matthew   303: 
1.112     bowersj2  304: =over 4
                    305: 
1.648     raeburn   306: =item * &browser_and_searcher_javascript()
1.112     bowersj2  307: 
                    308: X<browsing, javascript>X<searching, javascript>Returns a string
                    309: containing javascript with two functions, C<openbrowser> and
                    310: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    311: tags.
1.42      matthew   312: 
1.648     raeburn   313: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   314: 
                    315: inputs: formname, elementname, only, omit
                    316: 
                    317: formname and elementname indicate the name of the html form and name of
                    318: the element that the results of the browsing selection are to be placed in. 
                    319: 
                    320: Specifying 'only' will restrict the browser to displaying only files
1.185     www       321: with the given extension.  Can be a comma separated list.
1.42      matthew   322: 
                    323: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       324: with the given extension.  Can be a comma separated list.
1.42      matthew   325: 
1.648     raeburn   326: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   327: 
                    328: Inputs: formname, elementname
                    329: 
                    330: formname and elementname specify the name of the html form and the name
                    331: of the element the selection from the search results will be placed in.
1.542     raeburn   332: 
1.42      matthew   333: =cut
                    334: 
                    335: sub browser_and_searcher_javascript {
1.199     albertel  336:     my ($mode)=@_;
                    337:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  338:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   339:     return <<END;
1.219     albertel  340: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   341:     var editbrowser = null;
1.135     albertel  342:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       343:         var url = '$resurl/?';
1.42      matthew   344:         if (editbrowser == null) {
                    345:             url += 'launch=1&';
                    346:         }
                    347:         url += 'catalogmode=interactive&';
1.199     albertel  348:         url += 'mode=$mode&';
1.611     albertel  349:         url += 'inhibitmenu=yes&';
1.42      matthew   350:         url += 'form=' + formname + '&';
                    351:         if (only != null) {
                    352:             url += 'only=' + only + '&';
1.217     albertel  353:         } else {
                    354:             url += 'only=&';
                    355: 	}
1.42      matthew   356:         if (omit != null) {
                    357:             url += 'omit=' + omit + '&';
1.217     albertel  358:         } else {
                    359:             url += 'omit=&';
                    360: 	}
1.135     albertel  361:         if (titleelement != null) {
                    362:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  363:         } else {
                    364: 	    url += 'titleelement=&';
                    365: 	}
1.42      matthew   366:         url += 'element=' + elementname + '';
                    367:         var title = 'Browser';
1.435     albertel  368:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   369:         options += ',width=700,height=600';
                    370:         editbrowser = open(url,title,options,'1');
                    371:         editbrowser.focus();
                    372:     }
                    373:     var editsearcher;
1.135     albertel  374:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   375:         var url = '/adm/searchcat?';
                    376:         if (editsearcher == null) {
                    377:             url += 'launch=1&';
                    378:         }
                    379:         url += 'catalogmode=interactive&';
1.199     albertel  380:         url += 'mode=$mode&';
1.42      matthew   381:         url += 'form=' + formname + '&';
1.135     albertel  382:         if (titleelement != null) {
                    383:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  384:         } else {
                    385: 	    url += 'titleelement=&';
                    386: 	}
1.42      matthew   387:         url += 'element=' + elementname + '';
                    388:         var title = 'Search';
1.435     albertel  389:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   390:         options += ',width=700,height=600';
                    391:         editsearcher = open(url,title,options,'1');
                    392:         editsearcher.focus();
                    393:     }
1.219     albertel  394: // END LON-CAPA Internal -->
1.42      matthew   395: END
1.170     www       396: }
                    397: 
                    398: sub lastresurl {
1.258     albertel  399:     if ($env{'environment.lastresurl'}) {
                    400: 	return $env{'environment.lastresurl'}
1.170     www       401:     } else {
                    402: 	return '/res';
                    403:     }
                    404: }
                    405: 
                    406: sub storeresurl {
                    407:     my $resurl=&Apache::lonnet::clutter(shift);
                    408:     unless ($resurl=~/^\/res/) { return 0; }
                    409:     $resurl=~s/\/$//;
                    410:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   411:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       412:     return 1;
1.42      matthew   413: }
                    414: 
1.74      www       415: sub studentbrowser_javascript {
1.111     www       416:    unless (
1.258     albertel  417:             (($env{'request.course.id'}) && 
1.302     albertel  418:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    419: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    420: 					  '/'.$env{'request.course.sec'})
                    421: 	      ))
1.258     albertel  422:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       423:           ) { return ''; }  
1.74      www       424:    return (<<'ENDSTDBRW');
1.776     bisitz    425: <script type="text/javascript" language="Javascript">
1.824     bisitz    426: // <![CDATA[
1.74      www       427:     var stdeditbrowser;
1.999     www       428:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       429:         var url = '/adm/pickstudent?';
                    430:         var filter;
1.558     albertel  431: 	if (!ignorefilter) {
                    432: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    433: 	}
1.74      www       434:         if (filter != null) {
                    435:            if (filter != '') {
                    436:                url += 'filter='+filter+'&';
                    437: 	   }
                    438:         }
                    439:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       440:                                     '&udomelement='+udom+
                    441:                                     '&clicker='+clicker;
1.111     www       442: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   443:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       444:         var title = 'Student_Browser';
1.74      www       445:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    446:         options += ',width=700,height=600';
                    447:         stdeditbrowser = open(url,title,options,'1');
                    448:         stdeditbrowser.focus();
                    449:     }
1.824     bisitz    450: // ]]>
1.74      www       451: </script>
                    452: ENDSTDBRW
                    453: }
1.42      matthew   454: 
1.1003    www       455: sub resourcebrowser_javascript {
                    456:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       457:    return (<<'ENDRESBRW');
1.1003    www       458: <script type="text/javascript" language="Javascript">
                    459: // <![CDATA[
                    460:     var reseditbrowser;
1.1004    www       461:     function openresbrowser(formname,reslink) {
1.1005    www       462:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       463:         var title = 'Resource_Browser';
                    464:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       465:         options += ',width=700,height=500';
1.1004    www       466:         reseditbrowser = open(url,title,options,'1');
                    467:         reseditbrowser.focus();
1.1003    www       468:     }
                    469: // ]]>
                    470: </script>
1.1004    www       471: ENDRESBRW
1.1003    www       472: }
                    473: 
1.74      www       474: sub selectstudent_link {
1.999     www       475:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    476:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    477:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    478:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  479:    if ($env{'request.course.id'}) {  
1.302     albertel  480:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    481: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    482: 					'/'.$env{'request.course.sec'})) {
1.111     www       483: 	   return '';
                    484:        }
1.999     www       485:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   486:        if ($courseadvonly)  {
                    487:            $callargs .= ",'',1,1";
                    488:        }
                    489:        return '<span class="LC_nobreak">'.
                    490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    491:               &mt('Select User').'</a></span>';
1.74      www       492:    }
1.258     albertel  493:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       494:        $callargs .= ",'',1"; 
1.793     raeburn   495:        return '<span class="LC_nobreak">'.
                    496:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    497:               &mt('Select User').'</a></span>';
1.111     www       498:    }
                    499:    return '';
1.91      www       500: }
                    501: 
1.1004    www       502: sub selectresource_link {
                    503:    my ($form,$reslink,$arg)=@_;
                    504:    
                    505:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    506:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    507:    unless ($env{'request.course.id'}) { return $arg; }
                    508:    return '<span class="LC_nobreak">'.
                    509:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    510:               $arg.'</a></span>';
                    511: }
                    512: 
                    513: 
                    514: 
1.653     raeburn   515: sub authorbrowser_javascript {
                    516:     return <<"ENDAUTHORBRW";
1.776     bisitz    517: <script type="text/javascript" language="JavaScript">
1.824     bisitz    518: // <![CDATA[
1.653     raeburn   519: var stdeditbrowser;
                    520: 
                    521: function openauthorbrowser(formname,udom) {
                    522:     var url = '/adm/pickauthor?';
                    523:     url += 'form='+formname+'&roledom='+udom;
                    524:     var title = 'Author_Browser';
                    525:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    526:     options += ',width=700,height=600';
                    527:     stdeditbrowser = open(url,title,options,'1');
                    528:     stdeditbrowser.focus();
                    529: }
                    530: 
1.824     bisitz    531: // ]]>
1.653     raeburn   532: </script>
                    533: ENDAUTHORBRW
                    534: }
                    535: 
1.91      www       536: sub coursebrowser_javascript {
1.1075.2.31  raeburn   537:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   538:         $credits_element,$instcode) = @_;
1.932     raeburn   539:     my $wintitle = 'Course_Browser';
1.931     raeburn   540:     if ($crstype eq 'Community') {
1.932     raeburn   541:         $wintitle = 'Community_Browser';
1.909     raeburn   542:     }
1.876     raeburn   543:     my $id_functions = &javascript_index_functions();
                    544:     my $output = '
1.776     bisitz    545: <script type="text/javascript" language="JavaScript">
1.824     bisitz    546: // <![CDATA[
1.468     raeburn   547:     var stdeditbrowser;'."\n";
1.876     raeburn   548: 
                    549:     $output .= <<"ENDSTDBRW";
1.909     raeburn   550:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       551:         var url = '/adm/pickcourse?';
1.895     raeburn   552:         var formid = getFormIdByName(formname);
1.876     raeburn   553:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  554:         if (domainfilter != null) {
                    555:            if (domainfilter != '') {
                    556:                url += 'domainfilter='+domainfilter+'&';
                    557: 	   }
                    558:         }
1.91      www       559:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  560: 	                            '&cdomelement='+udom+
                    561:                                     '&cnameelement='+desc;
1.468     raeburn   562:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   563:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   564:                 url += '&roleelement='+extra_element;
                    565:                 if (domainfilter == null || domainfilter == '') {
                    566:                     url += '&domainfilter='+extra_element;
                    567:                 }
1.234     raeburn   568:             }
1.468     raeburn   569:             else {
                    570:                 if (formname == 'portform') {
                    571:                     url += '&setroles='+extra_element;
1.800     raeburn   572:                 } else {
                    573:                     if (formname == 'rules') {
                    574:                         url += '&fixeddom='+extra_element; 
                    575:                     }
1.468     raeburn   576:                 }
                    577:             }     
1.230     raeburn   578:         }
1.909     raeburn   579:         if (type != null && type != '') {
                    580:             url += '&type='+type;
                    581:         }
                    582:         if (type_elem != null && type_elem != '') {
                    583:             url += '&typeelement='+type_elem;
                    584:         }
1.872     raeburn   585:         if (formname == 'ccrs') {
                    586:             var ownername = document.forms[formid].ccuname.value;
                    587:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   588:             url += '&cloner='+ownername+':'+ownerdom;
                    589:             if (type == 'Course') {
                    590:                 url += '&crscode='+document.forms[formid].crscode.value;
                    591:             }
1.1075.2.95  raeburn   592:         }
                    593:         if (formname == 'requestcrs') {
                    594:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   595:         }
1.293     raeburn   596:         if (multflag !=null && multflag != '') {
                    597:             url += '&multiple='+multflag;
                    598:         }
1.909     raeburn   599:         var title = '$wintitle';
1.91      www       600:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    601:         options += ',width=700,height=600';
                    602:         stdeditbrowser = open(url,title,options,'1');
                    603:         stdeditbrowser.focus();
                    604:     }
1.876     raeburn   605: $id_functions
                    606: ENDSTDBRW
1.1075.2.31  raeburn   607:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    608:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    609:                                       $credits_element);
1.876     raeburn   610:     }
                    611:     $output .= '
                    612: // ]]>
                    613: </script>';
                    614:     return $output;
                    615: }
                    616: 
                    617: sub javascript_index_functions {
                    618:     return <<"ENDJS";
                    619: 
                    620: function getFormIdByName(formname) {
                    621:     for (var i=0;i<document.forms.length;i++) {
                    622:         if (document.forms[i].name == formname) {
                    623:             return i;
                    624:         }
                    625:     }
                    626:     return -1;
                    627: }
                    628: 
                    629: function getIndexByName(formid,item) {
                    630:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    631:         if (document.forms[formid].elements[i].name == item) {
                    632:             return i;
                    633:         }
                    634:     }
                    635:     return -1;
                    636: }
1.468     raeburn   637: 
1.876     raeburn   638: function getDomainFromSelectbox(formname,udom) {
                    639:     var userdom;
                    640:     var formid = getFormIdByName(formname);
                    641:     if (formid > -1) {
                    642:         var domid = getIndexByName(formid,udom);
                    643:         if (domid > -1) {
                    644:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    645:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    646:             }
                    647:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    648:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   649:             }
                    650:         }
                    651:     }
1.876     raeburn   652:     return userdom;
                    653: }
                    654: 
                    655: ENDJS
1.468     raeburn   656: 
1.876     raeburn   657: }
                    658: 
1.1017    raeburn   659: sub javascript_array_indexof {
1.1018    raeburn   660:     return <<ENDJS;
1.1017    raeburn   661: <script type="text/javascript" language="JavaScript">
                    662: // <![CDATA[
                    663: 
                    664: if (!Array.prototype.indexOf) {
                    665:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    666:         "use strict";
                    667:         if (this === void 0 || this === null) {
                    668:             throw new TypeError();
                    669:         }
                    670:         var t = Object(this);
                    671:         var len = t.length >>> 0;
                    672:         if (len === 0) {
                    673:             return -1;
                    674:         }
                    675:         var n = 0;
                    676:         if (arguments.length > 0) {
                    677:             n = Number(arguments[1]);
                    678:             if (n !== n) { // shortcut for verifying if it's NaN
                    679:                 n = 0;
                    680:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    681:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    682:             }
                    683:         }
                    684:         if (n >= len) {
                    685:             return -1;
                    686:         }
                    687:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    688:         for (; k < len; k++) {
                    689:             if (k in t && t[k] === searchElement) {
                    690:                 return k;
                    691:             }
                    692:         }
                    693:         return -1;
                    694:     }
                    695: }
                    696: 
                    697: // ]]>
                    698: </script>
                    699: 
                    700: ENDJS
                    701: 
                    702: }
                    703: 
1.876     raeburn   704: sub userbrowser_javascript {
                    705:     my $id_functions = &javascript_index_functions();
                    706:     return <<"ENDUSERBRW";
                    707: 
1.888     raeburn   708: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   709:     var url = '/adm/pickuser?';
                    710:     var userdom = getDomainFromSelectbox(formname,udom);
                    711:     if (userdom != null) {
                    712:        if (userdom != '') {
                    713:            url += 'srchdom='+userdom+'&';
                    714:        }
                    715:     }
                    716:     url += 'form=' + formname + '&unameelement='+uname+
                    717:                                 '&udomelement='+udom+
                    718:                                 '&ulastelement='+ulast+
                    719:                                 '&ufirstelement='+ufirst+
                    720:                                 '&uemailelement='+uemail+
1.881     raeburn   721:                                 '&hideudomelement='+hideudom+
                    722:                                 '&coursedom='+crsdom;
1.888     raeburn   723:     if ((caller != null) && (caller != undefined)) {
                    724:         url += '&caller='+caller;
                    725:     }
1.876     raeburn   726:     var title = 'User_Browser';
                    727:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    728:     options += ',width=700,height=600';
                    729:     var stdeditbrowser = open(url,title,options,'1');
                    730:     stdeditbrowser.focus();
                    731: }
                    732: 
1.888     raeburn   733: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   734:     var formid = getFormIdByName(formname);
                    735:     if (formid > -1) {
1.888     raeburn   736:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   737:         var domid = getIndexByName(formid,udom);
                    738:         var hidedomid = getIndexByName(formid,origdom);
                    739:         if (hidedomid > -1) {
                    740:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   741:             var unameval = document.forms[formid].elements[unameid].value;
                    742:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    743:                 if (domid > -1) {
                    744:                     var slct = document.forms[formid].elements[domid];
                    745:                     if (slct.type == 'select-one') {
                    746:                         var i;
                    747:                         for (i=0;i<slct.length;i++) {
                    748:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    749:                         }
                    750:                     }
                    751:                     if (slct.type == 'hidden') {
                    752:                         slct.value = fixeddom;
1.876     raeburn   753:                     }
                    754:                 }
1.468     raeburn   755:             }
                    756:         }
                    757:     }
1.876     raeburn   758:     return;
                    759: }
                    760: 
                    761: $id_functions
                    762: ENDUSERBRW
1.468     raeburn   763: }
                    764: 
                    765: sub setsec_javascript {
1.1075.2.31  raeburn   766:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   767:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    768:         $communityrolestr);
                    769:     if ($role_element ne '') {
                    770:         my @allroles = ('st','ta','ep','in','ad');
                    771:         foreach my $crstype ('Course','Community') {
                    772:             if ($crstype eq 'Community') {
                    773:                 foreach my $role (@allroles) {
                    774:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    775:                 }
                    776:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    777:             } else {
                    778:                 foreach my $role (@allroles) {
                    779:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    780:                 }
                    781:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    782:             }
                    783:         }
                    784:         $rolestr = '"'.join('","',@allroles).'"';
                    785:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    786:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    787:     }
1.468     raeburn   788:     my $setsections = qq|
                    789: function setSect(sectionlist) {
1.629     raeburn   790:     var sectionsArray = new Array();
                    791:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    792:         sectionsArray = sectionlist.split(",");
                    793:     }
1.468     raeburn   794:     var numSections = sectionsArray.length;
                    795:     document.$formname.$sec_element.length = 0;
                    796:     if (numSections == 0) {
                    797:         document.$formname.$sec_element.multiple=false;
                    798:         document.$formname.$sec_element.size=1;
                    799:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    800:     } else {
                    801:         if (numSections == 1) {
                    802:             document.$formname.$sec_element.multiple=false;
                    803:             document.$formname.$sec_element.size=1;
                    804:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    805:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    806:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    807:         } else {
                    808:             for (var i=0; i<numSections; i++) {
                    809:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    810:             }
                    811:             document.$formname.$sec_element.multiple=true
                    812:             if (numSections < 3) {
                    813:                 document.$formname.$sec_element.size=numSections;
                    814:             } else {
                    815:                 document.$formname.$sec_element.size=3;
                    816:             }
                    817:             document.$formname.$sec_element.options[0].selected = false
                    818:         }
                    819:     }
1.91      www       820: }
1.905     raeburn   821: 
                    822: function setRole(crstype) {
1.468     raeburn   823: |;
1.905     raeburn   824:     if ($role_element eq '') {
                    825:         $setsections .= '    return;
                    826: }
                    827: ';
                    828:     } else {
                    829:         $setsections .= qq|
                    830:     var elementLength = document.$formname.$role_element.length;
                    831:     var allroles = Array($rolestr);
                    832:     var courserolenames = Array($courserolestr);
                    833:     var communityrolenames = Array($communityrolestr);
                    834:     if (elementLength != undefined) {
                    835:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    836:             if (crstype == 'Course') {
                    837:                 return;
                    838:             } else {
                    839:                 allroles[5] = 'co';
                    840:                 for (var i=0; i<6; i++) {
                    841:                     document.$formname.$role_element.options[i].value = allroles[i];
                    842:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    843:                 }
                    844:             }
                    845:         } else {
                    846:             if (crstype == 'Community') {
                    847:                 return;
                    848:             } else {
                    849:                 allroles[5] = 'cc';
                    850:                 for (var i=0; i<6; i++) {
                    851:                     document.$formname.$role_element.options[i].value = allroles[i];
                    852:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    853:                 }
                    854:             }
                    855:         }
                    856:     }
                    857:     return;
                    858: }
                    859: |;
                    860:     }
1.1075.2.31  raeburn   861:     if ($credits_element) {
                    862:         $setsections .= qq|
                    863: function setCredits(defaultcredits) {
                    864:     document.$formname.$credits_element.value = defaultcredits;
                    865:     return;
                    866: }
                    867: |;
                    868:     }
1.468     raeburn   869:     return $setsections;
                    870: }
                    871: 
1.91      www       872: sub selectcourse_link {
1.909     raeburn   873:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    874:        $typeelement) = @_;
                    875:    my $type = $selecttype;
1.871     raeburn   876:    my $linktext = &mt('Select Course');
                    877:    if ($selecttype eq 'Community') {
1.909     raeburn   878:        $linktext = &mt('Select Community');
1.906     raeburn   879:    } elsif ($selecttype eq 'Course/Community') {
                    880:        $linktext = &mt('Select Course/Community');
1.909     raeburn   881:        $type = '';
1.1019    raeburn   882:    } elsif ($selecttype eq 'Select') {
                    883:        $linktext = &mt('Select');
                    884:        $type = '';
1.871     raeburn   885:    }
1.787     bisitz    886:    return '<span class="LC_nobreak">'
                    887:          ."<a href='"
                    888:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    889:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   890:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   891:          ."'>".$linktext.'</a>'
1.787     bisitz    892:          .'</span>';
1.74      www       893: }
1.42      matthew   894: 
1.653     raeburn   895: sub selectauthor_link {
                    896:    my ($form,$udom)=@_;
                    897:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    898:           &mt('Select Author').'</a>';
                    899: }
                    900: 
1.876     raeburn   901: sub selectuser_link {
1.881     raeburn   902:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   903:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   904:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   905:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   906:            ');">'.$linktext.'</a>';
1.876     raeburn   907: }
                    908: 
1.273     raeburn   909: sub check_uncheck_jscript {
                    910:     my $jscript = <<"ENDSCRT";
                    911: function checkAll(field) {
                    912:     if (field.length > 0) {
                    913:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   914:             if (!field[i].disabled) {
                    915:                 field[i].checked = true;
                    916:             }
1.273     raeburn   917:         }
                    918:     } else {
1.1075.2.14  raeburn   919:         if (!field.disabled) {
                    920:             field.checked = true;
                    921:         }
1.273     raeburn   922:     }
                    923: }
                    924:  
                    925: function uncheckAll(field) {
                    926:     if (field.length > 0) {
                    927:         for (i = 0; i < field.length; i++) {
                    928:             field[i].checked = false ;
1.543     albertel  929:         }
                    930:     } else {
1.273     raeburn   931:         field.checked = false ;
                    932:     }
                    933: }
                    934: ENDSCRT
                    935:     return $jscript;
                    936: }
                    937: 
1.656     www       938: sub select_timezone {
1.1075.2.115  raeburn   939:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    940:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   941:    if ($includeempty) {
                    942:        $output .= '<option value=""';
                    943:        if (($selected eq '') || ($selected eq 'local')) {
                    944:            $output .= ' selected="selected" ';
                    945:        }
                    946:        $output .= '> </option>';
                    947:    }
1.657     raeburn   948:    my @timezones = DateTime::TimeZone->all_names;
                    949:    foreach my $tzone (@timezones) {
                    950:        $output.= '<option value="'.$tzone.'"';
                    951:        if ($tzone eq $selected) {
                    952:            $output.=' selected="selected"';
                    953:        }
                    954:        $output.=">$tzone</option>\n";
1.656     www       955:    }
                    956:    $output.="</select>";
                    957:    return $output;
                    958: }
1.273     raeburn   959: 
1.687     raeburn   960: sub select_datelocale {
1.1075.2.115  raeburn   961:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    962:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   963:     if ($includeempty) {
                    964:         $output .= '<option value=""';
                    965:         if ($selected eq '') {
                    966:             $output .= ' selected="selected" ';
                    967:         }
                    968:         $output .= '> </option>';
                    969:     }
1.1075.2.102  raeburn   970:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   971:     my (@possibles,%locale_names);
1.1075.2.102  raeburn   972:     my @locales = DateTime::Locale->ids();
                    973:     foreach my $id (@locales) {
                    974:         if ($id ne '') {
                    975:             my ($en_terr,$native_terr);
                    976:             my $loc = DateTime::Locale->load($id);
                    977:             if (ref($loc)) {
                    978:                 $en_terr = $loc->name();
                    979:                 $native_terr = $loc->native_name();
1.687     raeburn   980:                 if (grep(/^en$/,@languages) || !@languages) {
                    981:                     if ($en_terr ne '') {
                    982:                         $locale_names{$id} = '('.$en_terr.')';
                    983:                     } elsif ($native_terr ne '') {
                    984:                         $locale_names{$id} = $native_terr;
                    985:                     }
                    986:                 } else {
                    987:                     if ($native_terr ne '') {
                    988:                         $locale_names{$id} = $native_terr.' ';
                    989:                     } elsif ($en_terr ne '') {
                    990:                         $locale_names{$id} = '('.$en_terr.')';
                    991:                     }
                    992:                 }
1.1075.2.94  raeburn   993:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1075.2.102  raeburn   994:                 push(@possibles,$id);
1.687     raeburn   995:             }
                    996:         }
                    997:     }
                    998:     foreach my $item (sort(@possibles)) {
                    999:         $output.= '<option value="'.$item.'"';
                   1000:         if ($item eq $selected) {
                   1001:             $output.=' selected="selected"';
                   1002:         }
                   1003:         $output.=">$item";
                   1004:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn  1005:             $output.='  '.$locale_names{$item};
1.687     raeburn  1006:         }
                   1007:         $output.="</option>\n";
                   1008:     }
                   1009:     $output.="</select>";
                   1010:     return $output;
                   1011: }
                   1012: 
1.792     raeburn  1013: sub select_language {
1.1075.2.115  raeburn  1014:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1015:     my %langchoices;
                   1016:     if ($includeempty) {
1.1075.2.32  raeburn  1017:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1018:     }
                   1019:     foreach my $id (&languageids()) {
                   1020:         my $code = &supportedlanguagecode($id);
                   1021:         if ($code) {
                   1022:             $langchoices{$code} = &plainlanguagedescription($id);
                   1023:         }
                   1024:     }
1.1075.2.32  raeburn  1025:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1075.2.115  raeburn  1026:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1027: }
                   1028: 
1.42      matthew  1029: =pod
1.36      matthew  1030: 
1.648     raeburn  1031: =item * &linked_select_forms(...)
1.36      matthew  1032: 
                   1033: linked_select_forms returns a string containing a <script></script> block
                   1034: and html for two <select> menus.  The select menus will be linked in that
                   1035: changing the value of the first menu will result in new values being placed
                   1036: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1037: order unless a defined order is provided.
1.36      matthew  1038: 
                   1039: linked_select_forms takes the following ordered inputs:
                   1040: 
                   1041: =over 4
                   1042: 
1.112     bowersj2 1043: =item * $formname, the name of the <form> tag
1.36      matthew  1044: 
1.112     bowersj2 1045: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1046: 
1.112     bowersj2 1047: =item * $firstdefault, the default value for the first menu
1.36      matthew  1048: 
1.112     bowersj2 1049: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1050: 
1.112     bowersj2 1051: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1052: 
1.112     bowersj2 1053: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1054: 
1.609     raeburn  1055: =item * $menuorder, the order of values in the first menu
                   1056: 
1.1075.2.31  raeburn  1057: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1058:         event for the first <select> tag
                   1059: 
                   1060: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1061:         event for the second <select> tag
                   1062: 
1.41      ng       1063: =back 
                   1064: 
1.36      matthew  1065: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1066: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1067: values for the first select menu.  The text that coincides with the 
1.41      ng       1068: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1069: and text for the second menu are given in the hash pointed to by 
                   1070: $menu{$choice1}->{'select2'}.  
                   1071: 
1.112     bowersj2 1072:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1073:                        default => "B3",
                   1074:                        select2 => { 
                   1075:                            B1 => "Choice B1",
                   1076:                            B2 => "Choice B2",
                   1077:                            B3 => "Choice B3",
                   1078:                            B4 => "Choice B4"
1.609     raeburn  1079:                            },
                   1080:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1081:                    },
                   1082:                A2 => { text =>"Choice A2" ,
                   1083:                        default => "C2",
                   1084:                        select2 => { 
                   1085:                            C1 => "Choice C1",
                   1086:                            C2 => "Choice C2",
                   1087:                            C3 => "Choice C3"
1.609     raeburn  1088:                            },
                   1089:                        order => ['C2','C1','C3'],
1.112     bowersj2 1090:                    },
                   1091:                A3 => { text =>"Choice A3" ,
                   1092:                        default => "D6",
                   1093:                        select2 => { 
                   1094:                            D1 => "Choice D1",
                   1095:                            D2 => "Choice D2",
                   1096:                            D3 => "Choice D3",
                   1097:                            D4 => "Choice D4",
                   1098:                            D5 => "Choice D5",
                   1099:                            D6 => "Choice D6",
                   1100:                            D7 => "Choice D7"
1.609     raeburn  1101:                            },
                   1102:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1103:                    }
                   1104:                );
1.36      matthew  1105: 
                   1106: =cut
                   1107: 
                   1108: sub linked_select_forms {
                   1109:     my ($formname,
                   1110:         $middletext,
                   1111:         $firstdefault,
                   1112:         $firstselectname,
                   1113:         $secondselectname, 
1.609     raeburn  1114:         $hashref,
                   1115:         $menuorder,
1.1075.2.31  raeburn  1116:         $onchangefirst,
                   1117:         $onchangesecond
1.36      matthew  1118:         ) = @_;
                   1119:     my $second = "document.$formname.$secondselectname";
                   1120:     my $first = "document.$formname.$firstselectname";
                   1121:     # output the javascript to do the changing
                   1122:     my $result = '';
1.776     bisitz   1123:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1124:     $result.="// <![CDATA[\n";
1.36      matthew  1125:     $result.="var select2data = new Object();\n";
                   1126:     $" = '","';
                   1127:     my $debug = '';
                   1128:     foreach my $s1 (sort(keys(%$hashref))) {
                   1129:         $result.="select2data.d_$s1 = new Object();\n";        
                   1130:         $result.="select2data.d_$s1.def = new String('".
                   1131:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1132:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1133:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1134:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1135:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1136:         }
1.36      matthew  1137:         $result.="\"@s2values\");\n";
                   1138:         $result.="select2data.d_$s1.texts = new Array(";        
                   1139:         my @s2texts;
                   1140:         foreach my $value (@s2values) {
1.1075.2.119  raeburn  1141:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1142:         }
                   1143:         $result.="\"@s2texts\");\n";
                   1144:     }
                   1145:     $"=' ';
                   1146:     $result.= <<"END";
                   1147: 
                   1148: function select1_changed() {
                   1149:     // Determine new choice
                   1150:     var newvalue = "d_" + $first.value;
                   1151:     // update select2
                   1152:     var values     = select2data[newvalue].values;
                   1153:     var texts      = select2data[newvalue].texts;
                   1154:     var select2def = select2data[newvalue].def;
                   1155:     var i;
                   1156:     // out with the old
                   1157:     for (i = 0; i < $second.options.length; i++) {
                   1158:         $second.options[i] = null;
                   1159:     }
                   1160:     // in with the nuclear
                   1161:     for (i=0;i<values.length; i++) {
                   1162:         $second.options[i] = new Option(values[i]);
1.143     matthew  1163:         $second.options[i].value = values[i];
1.36      matthew  1164:         $second.options[i].text = texts[i];
                   1165:         if (values[i] == select2def) {
                   1166:             $second.options[i].selected = true;
                   1167:         }
                   1168:     }
                   1169: }
1.824     bisitz   1170: // ]]>
1.36      matthew  1171: </script>
                   1172: END
                   1173:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1174:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1175:     my @order = sort(keys(%{$hashref}));
                   1176:     if (ref($menuorder) eq 'ARRAY') {
                   1177:         @order = @{$menuorder};
                   1178:     }
                   1179:     foreach my $value (@order) {
1.36      matthew  1180:         $result.="    <option value=\"$value\" ";
1.253     albertel 1181:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1182:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1183:     }
                   1184:     $result .= "</select>\n";
                   1185:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1186:     $result .= $middletext;
1.1075.2.31  raeburn  1187:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1188:     if ($onchangesecond) {
                   1189:         $result .= ' onchange="'.$onchangesecond.'"';
                   1190:     }
                   1191:     $result .= ">\n";
1.36      matthew  1192:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1193:     
                   1194:     my @secondorder = sort(keys(%select2));
                   1195:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1196:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1197:     }
                   1198:     foreach my $value (@secondorder) {
1.36      matthew  1199:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1200:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1201:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1202:     }
                   1203:     $result .= "</select>\n";
                   1204:     #    return $debug;
                   1205:     return $result;
                   1206: }   #  end of sub linked_select_forms {
                   1207: 
1.45      matthew  1208: =pod
1.44      bowersj2 1209: 
1.973     raeburn  1210: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1211: 
1.112     bowersj2 1212: Returns a string corresponding to an HTML link to the given help
                   1213: $topic, where $topic corresponds to the name of a .tex file in
                   1214: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1215: spaces. 
                   1216: 
                   1217: $text will optionally be linked to the same topic, allowing you to
                   1218: link text in addition to the graphic. If you do not want to link
                   1219: text, but wish to specify one of the later parameters, pass an
                   1220: empty string. 
                   1221: 
                   1222: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1223: the link will not open a new window. If false, the link will open
                   1224: a new window using Javascript. (Default is false.) 
                   1225: 
                   1226: $width and $height are optional numerical parameters that will
                   1227: override the width and height of the popped up window, which may
1.973     raeburn  1228: be useful for certain help topics with big pictures included.
                   1229: 
                   1230: $imgid is the id of the img tag used for the help icon. This may be
                   1231: used in a javascript call to switch the image src.  See 
                   1232: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1233: 
                   1234: =cut
                   1235: 
                   1236: sub help_open_topic {
1.973     raeburn  1237:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1238:     $text = "" if (not defined $text);
1.44      bowersj2 1239:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1240:     $width = 500 if (not defined $width);
1.44      bowersj2 1241:     $height = 400 if (not defined $height);
                   1242:     my $filename = $topic;
                   1243:     $filename =~ s/ /_/g;
                   1244: 
1.48      bowersj2 1245:     my $template = "";
                   1246:     my $link;
1.572     banghart 1247:     
1.159     www      1248:     $topic=~s/\W/\_/g;
1.44      bowersj2 1249: 
1.572     banghart 1250:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1251:         if ($env{'browser.mobile'}) {
                   1252: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1253:         } else {
                   1254:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1255:         }
1.1037    www      1256:     } elsif ($stayOnPage eq 'popup') {
                   1257:         $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 1258:     } else {
1.48      bowersj2 1259: 	$link = "/adm/help/${filename}.hlp";
                   1260:     }
                   1261: 
                   1262:     # Add the text
1.755     neumanie 1263:     if ($text ne "") {	
1.763     bisitz   1264: 	$template.='<span class="LC_help_open_topic">'
                   1265:                   .'<a target="_top" href="'.$link.'">'
                   1266:                   .$text.'</a>';
1.48      bowersj2 1267:     }
                   1268: 
1.763     bisitz   1269:     # (Always) Add the graphic
1.179     matthew  1270:     my $title = &mt('Online Help');
1.667     raeburn  1271:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1272:     if ($imgid ne '') {
                   1273:         $imgid = ' id="'.$imgid.'"';
                   1274:     }
1.763     bisitz   1275:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1276:               .'<img src="'.$helpicon.'" border="0"'
                   1277:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1278:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1279:               .' /></a>';
                   1280:     if ($text ne "") {	
                   1281:         $template.='</span>';
                   1282:     }
1.44      bowersj2 1283:     return $template;
                   1284: 
1.106     bowersj2 1285: }
                   1286: 
                   1287: # This is a quicky function for Latex cheatsheet editing, since it 
                   1288: # appears in at least four places
                   1289: sub helpLatexCheatsheet {
1.1037    www      1290:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1291:     my $out;
1.106     bowersj2 1292:     my $addOther = '';
1.732     raeburn  1293:     if ($topic) {
1.1037    www      1294: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1295:     }
                   1296:     $out = '<span>' # Start cheatsheet
                   1297: 	  .$addOther
                   1298:           .'<span>'
1.1037    www      1299: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1300: 	  .'</span> <span>'
1.1037    www      1301: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1302: 	  .'</span>';
1.732     raeburn  1303:     unless ($not_author) {
1.763     bisitz   1304:         $out .= ' <span>'
1.1037    www      1305: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1306: 	       .'</span> <span>'
1.1075.2.78  raeburn  1307:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1308:                .'</span>';
1.732     raeburn  1309:     }
1.763     bisitz   1310:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1311:     return $out;
1.172     www      1312: }
                   1313: 
1.430     albertel 1314: sub general_help {
                   1315:     my $helptopic='Student_Intro';
                   1316:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1317: 	$helptopic='Authoring_Intro';
1.907     raeburn  1318:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1319: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1320:     } elsif ($env{'request.role'}=~/^dc/) {
                   1321:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1322:     }
                   1323:     return $helptopic;
                   1324: }
                   1325: 
                   1326: sub update_help_link {
                   1327:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1328:     my $origurl = $ENV{'REQUEST_URI'};
                   1329:     $origurl=~s|^/~|/priv/|;
                   1330:     my $timestamp = time;
                   1331:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1332:         $$datum = &escape($$datum);
                   1333:     }
                   1334: 
                   1335:     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";
                   1336:     my $output .= <<"ENDOUTPUT";
                   1337: <script type="text/javascript">
1.824     bisitz   1338: // <![CDATA[
1.430     albertel 1339: banner_link = '$banner_link';
1.824     bisitz   1340: // ]]>
1.430     albertel 1341: </script>
                   1342: ENDOUTPUT
                   1343:     return $output;
                   1344: }
                   1345: 
                   1346: # now just updates the help link and generates a blue icon
1.193     raeburn  1347: sub help_open_menu {
1.430     albertel 1348:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1349: 	= @_;    
1.949     droeschl 1350:     $stayOnPage = 1;
1.430     albertel 1351:     my $output;
                   1352:     if ($component_help) {
                   1353: 	if (!$text) {
                   1354: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1355: 				       $width,$height);
                   1356: 	} else {
                   1357: 	    my $help_text;
                   1358: 	    $help_text=&unescape($topic);
                   1359: 	    $output='<table><tr><td>'.
                   1360: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1361: 				 $width,$height).'</td></tr></table>';
                   1362: 	}
                   1363:     }
                   1364:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1365:     return $output.$banner_link;
                   1366: }
                   1367: 
                   1368: sub top_nav_help {
                   1369:     my ($text) = @_;
1.436     albertel 1370:     $text = &mt($text);
1.1075.2.60  raeburn  1371:     my $stay_on_page;
                   1372:     unless ($env{'environment.remote'} eq 'on') {
                   1373:         $stay_on_page = 1;
                   1374:     }
1.1075.2.61  raeburn  1375:     my ($link,$banner_link);
                   1376:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1377:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1378: 	                         : "javascript:helpMenu('open')";
                   1379:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1380:     }
1.201     raeburn  1381:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1382:     if ($link) {
                   1383:         return <<"END";
1.436     albertel 1384: $banner_link
1.1075.2.56  raeburn  1385: <a href="$link" title="$title">$text</a>
1.436     albertel 1386: END
1.1075.2.61  raeburn  1387:     } else {
                   1388:         return '&nbsp;'.$text.'&nbsp;';
                   1389:     }
1.436     albertel 1390: }
                   1391: 
                   1392: sub help_menu_js {
1.1075.2.52  raeburn  1393:     my ($httphost) = @_;
1.949     droeschl 1394:     my $stayOnPage = 1;
1.436     albertel 1395:     my $width = 620;
                   1396:     my $height = 600;
1.430     albertel 1397:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1398:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1399:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1400:     my $start_page =
                   1401:         &Apache::loncommon::start_page('Help Menu', undef,
                   1402: 				       {'frameset'    => 1,
                   1403: 					'js_ready'    => 1,
1.1075.2.52  raeburn  1404:                                         'use_absolute' => $httphost, 
1.331     albertel 1405: 					'add_entries' => {
                   1406: 					    'border' => '0',
1.579     raeburn  1407: 					    'rows'   => "110,*",},});
1.331     albertel 1408:     my $end_page =
                   1409:         &Apache::loncommon::end_page({'frameset' => 1,
                   1410: 				      'js_ready' => 1,});
                   1411: 
1.436     albertel 1412:     my $template .= <<"ENDTEMPLATE";
                   1413: <script type="text/javascript">
1.877     bisitz   1414: // <![CDATA[
1.253     albertel 1415: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1416: var banner_link = '';
1.243     raeburn  1417: function helpMenu(target) {
                   1418:     var caller = this;
                   1419:     if (target == 'open') {
                   1420:         var newWindow = null;
                   1421:         try {
1.262     albertel 1422:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1423:         }
                   1424:         catch(error) {
                   1425:             writeHelp(caller);
                   1426:             return;
                   1427:         }
                   1428:         if (newWindow) {
                   1429:             caller = newWindow;
                   1430:         }
1.193     raeburn  1431:     }
1.243     raeburn  1432:     writeHelp(caller);
                   1433:     return;
                   1434: }
                   1435: function writeHelp(caller) {
1.1075.2.61  raeburn  1436:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1437:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1438:     caller.document.close();
                   1439:     caller.focus();
1.193     raeburn  1440: }
1.877     bisitz   1441: // END LON-CAPA Internal -->
1.253     albertel 1442: // ]]>
1.436     albertel 1443: </script>
1.193     raeburn  1444: ENDTEMPLATE
                   1445:     return $template;
                   1446: }
                   1447: 
1.172     www      1448: sub help_open_bug {
                   1449:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1450:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1451:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1452:     $text = "" if (not defined $text);
                   1453: 	$stayOnPage=1;
1.184     albertel 1454:     $width = 600 if (not defined $width);
                   1455:     $height = 600 if (not defined $height);
1.172     www      1456: 
                   1457:     $topic=~s/\W+/\+/g;
                   1458:     my $link='';
                   1459:     my $template='';
1.379     albertel 1460:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1461: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1462:     if (!$stayOnPage)
                   1463:     {
                   1464: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1465:     }
                   1466:     else
                   1467:     {
                   1468: 	$link = $url;
                   1469:     }
                   1470:     # Add the text
                   1471:     if ($text ne "")
                   1472:     {
                   1473: 	$template .= 
                   1474:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1475:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1476:     }
                   1477: 
                   1478:     # Add the graphic
1.179     matthew  1479:     my $title = &mt('Report a Bug');
1.215     albertel 1480:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1481:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1482:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1483: ENDTEMPLATE
                   1484:     if ($text ne '') { $template.='</td></tr></table>' };
                   1485:     return $template;
                   1486: 
                   1487: }
                   1488: 
                   1489: sub help_open_faq {
                   1490:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1491:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1492:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1493:     $text = "" if (not defined $text);
                   1494: 	$stayOnPage=1;
                   1495:     $width = 350 if (not defined $width);
                   1496:     $height = 400 if (not defined $height);
                   1497: 
                   1498:     $topic=~s/\W+/\+/g;
                   1499:     my $link='';
                   1500:     my $template='';
                   1501:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1502:     if (!$stayOnPage)
                   1503:     {
                   1504: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1505:     }
                   1506:     else
                   1507:     {
                   1508: 	$link = $url;
                   1509:     }
                   1510: 
                   1511:     # Add the text
                   1512:     if ($text ne "")
                   1513:     {
                   1514: 	$template .= 
1.173     www      1515:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1516:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1517:     }
                   1518: 
                   1519:     # Add the graphic
1.179     matthew  1520:     my $title = &mt('View the FAQ');
1.215     albertel 1521:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1522:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1523:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1524: ENDTEMPLATE
                   1525:     if ($text ne '') { $template.='</td></tr></table>' };
                   1526:     return $template;
                   1527: 
1.44      bowersj2 1528: }
1.37      matthew  1529: 
1.180     matthew  1530: ###############################################################
                   1531: ###############################################################
                   1532: 
1.45      matthew  1533: =pod
                   1534: 
1.648     raeburn  1535: =item * &change_content_javascript():
1.256     matthew  1536: 
                   1537: This and the next function allow you to create small sections of an
                   1538: otherwise static HTML page that you can update on the fly with
                   1539: Javascript, even in Netscape 4.
                   1540: 
                   1541: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1542: must be written to the HTML page once. It will prove the Javascript
                   1543: function "change(name, content)". Calling the change function with the
                   1544: name of the section 
                   1545: you want to update, matching the name passed to C<changable_area>, and
                   1546: the new content you want to put in there, will put the content into
                   1547: that area.
                   1548: 
                   1549: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1550: to contain room for the original contents. You need to "make space"
                   1551: for whatever changes you wish to make, and be B<sure> to check your
                   1552: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1553: it's adequate for updating a one-line status display, but little more.
                   1554: This script will set the space to 100% width, so you only need to
                   1555: worry about height in Netscape 4.
                   1556: 
                   1557: Modern browsers are much less limiting, and if you can commit to the
                   1558: user not using Netscape 4, this feature may be used freely with
                   1559: pretty much any HTML.
                   1560: 
                   1561: =cut
                   1562: 
                   1563: sub change_content_javascript {
                   1564:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1565:     if ($env{'browser.type'} eq 'netscape' &&
                   1566: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1567: 	return (<<NETSCAPE4);
                   1568: 	function change(name, content) {
                   1569: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1570: 	    doc.open();
                   1571: 	    doc.write(content);
                   1572: 	    doc.close();
                   1573: 	}
                   1574: NETSCAPE4
                   1575:     } else {
                   1576: 	# Otherwise, we need to use semi-standards-compliant code
                   1577: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1578: 	# is really scary, and every useful browser supports it
                   1579: 	return (<<DOMBASED);
                   1580: 	function change(name, content) {
                   1581: 	    element = document.getElementById(name);
                   1582: 	    element.innerHTML = content;
                   1583: 	}
                   1584: DOMBASED
                   1585:     }
                   1586: }
                   1587: 
                   1588: =pod
                   1589: 
1.648     raeburn  1590: =item * &changable_area($name,$origContent):
1.256     matthew  1591: 
                   1592: This provides a "changable area" that can be modified on the fly via
                   1593: the Javascript code provided in C<change_content_javascript>. $name is
                   1594: the name you will use to reference the area later; do not repeat the
                   1595: same name on a given HTML page more then once. $origContent is what
                   1596: the area will originally contain, which can be left blank.
                   1597: 
                   1598: =cut
                   1599: 
                   1600: sub changable_area {
                   1601:     my ($name, $origContent) = @_;
                   1602: 
1.258     albertel 1603:     if ($env{'browser.type'} eq 'netscape' &&
                   1604: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1605: 	# If this is netscape 4, we need to use the Layer tag
                   1606: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1607:     } else {
                   1608: 	return "<span id='$name'>$origContent</span>";
                   1609:     }
                   1610: }
                   1611: 
                   1612: =pod
                   1613: 
1.648     raeburn  1614: =item * &viewport_geometry_js 
1.590     raeburn  1615: 
                   1616: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1617: 
                   1618: =cut
                   1619: 
                   1620: 
                   1621: sub viewport_geometry_js { 
                   1622:     return <<"GEOMETRY";
                   1623: var Geometry = {};
                   1624: function init_geometry() {
                   1625:     if (Geometry.init) { return };
                   1626:     Geometry.init=1;
                   1627:     if (window.innerHeight) {
                   1628:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1629:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1630:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1631:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1632:     }
                   1633:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1634:         Geometry.getViewportHeight =
                   1635:             function() { return document.documentElement.clientHeight; };
                   1636:         Geometry.getViewportWidth =
                   1637:             function() { return document.documentElement.clientWidth; };
                   1638: 
                   1639:         Geometry.getHorizontalScroll =
                   1640:             function() { return document.documentElement.scrollLeft; };
                   1641:         Geometry.getVerticalScroll =
                   1642:             function() { return document.documentElement.scrollTop; };
                   1643:     }
                   1644:     else if (document.body.clientHeight) {
                   1645:         Geometry.getViewportHeight =
                   1646:             function() { return document.body.clientHeight; };
                   1647:         Geometry.getViewportWidth =
                   1648:             function() { return document.body.clientWidth; };
                   1649:         Geometry.getHorizontalScroll =
                   1650:             function() { return document.body.scrollLeft; };
                   1651:         Geometry.getVerticalScroll =
                   1652:             function() { return document.body.scrollTop; };
                   1653:     }
                   1654: }
                   1655: 
                   1656: GEOMETRY
                   1657: }
                   1658: 
                   1659: =pod
                   1660: 
1.648     raeburn  1661: =item * &viewport_size_js()
1.590     raeburn  1662: 
                   1663: 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. 
                   1664: 
                   1665: =cut
                   1666: 
                   1667: sub viewport_size_js {
                   1668:     my $geometry = &viewport_geometry_js();
                   1669:     return <<"DIMS";
                   1670: 
                   1671: $geometry
                   1672: 
                   1673: function getViewportDims(width,height) {
                   1674:     init_geometry();
                   1675:     width.value = Geometry.getViewportWidth();
                   1676:     height.value = Geometry.getViewportHeight();
                   1677:     return;
                   1678: }
                   1679: 
                   1680: DIMS
                   1681: }
                   1682: 
                   1683: =pod
                   1684: 
1.648     raeburn  1685: =item * &resize_textarea_js()
1.565     albertel 1686: 
                   1687: emits the needed javascript to resize a textarea to be as big as possible
                   1688: 
                   1689: creates a function resize_textrea that takes two IDs first should be
                   1690: the id of the element to resize, second should be the id of a div that
                   1691: surrounds everything that comes after the textarea, this routine needs
                   1692: to be attached to the <body> for the onload and onresize events.
                   1693: 
1.648     raeburn  1694: =back
1.565     albertel 1695: 
                   1696: =cut
                   1697: 
                   1698: sub resize_textarea_js {
1.590     raeburn  1699:     my $geometry = &viewport_geometry_js();
1.565     albertel 1700:     return <<"RESIZE";
                   1701:     <script type="text/javascript">
1.824     bisitz   1702: // <![CDATA[
1.590     raeburn  1703: $geometry
1.565     albertel 1704: 
1.588     albertel 1705: function getX(element) {
                   1706:     var x = 0;
                   1707:     while (element) {
                   1708: 	x += element.offsetLeft;
                   1709: 	element = element.offsetParent;
                   1710:     }
                   1711:     return x;
                   1712: }
                   1713: function getY(element) {
                   1714:     var y = 0;
                   1715:     while (element) {
                   1716: 	y += element.offsetTop;
                   1717: 	element = element.offsetParent;
                   1718:     }
                   1719:     return y;
                   1720: }
                   1721: 
                   1722: 
1.565     albertel 1723: function resize_textarea(textarea_id,bottom_id) {
                   1724:     init_geometry();
                   1725:     var textarea        = document.getElementById(textarea_id);
                   1726:     //alert(textarea);
                   1727: 
1.588     albertel 1728:     var textarea_top    = getY(textarea);
1.565     albertel 1729:     var textarea_height = textarea.offsetHeight;
                   1730:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1731:     var bottom_top      = getY(bottom);
1.565     albertel 1732:     var bottom_height   = bottom.offsetHeight;
                   1733:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1734:     var fudge           = 23;
1.565     albertel 1735:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1736:     if (new_height < 300) {
                   1737: 	new_height = 300;
                   1738:     }
                   1739:     textarea.style.height=new_height+'px';
                   1740: }
1.824     bisitz   1741: // ]]>
1.565     albertel 1742: </script>
                   1743: RESIZE
                   1744: 
                   1745: }
                   1746: 
1.1075.2.112  raeburn  1747: sub colorfuleditor_js {
                   1748:     return <<"COLORFULEDIT"
                   1749: <script type="text/javascript">
                   1750: // <![CDATA[>
                   1751:     function fold_box(curDepth, lastresource){
                   1752: 
                   1753:     // we need a list because there can be several blocks you need to fold in one tag
                   1754:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1755:     // but there is only one folding button per tag
                   1756:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1757: 
                   1758:         if(block.item(0).style.display == 'none'){
                   1759: 
                   1760:             foldbutton.value = '@{[&mt("Hide")]}';
                   1761:             for (i = 0; i < block.length; i++){
                   1762:                 block.item(i).style.display = '';
                   1763:             }
                   1764:         }else{
                   1765: 
                   1766:             foldbutton.value = '@{[&mt("Show")]}';
                   1767:             for (i = 0; i < block.length; i++){
                   1768:                 // block.item(i).style.visibility = 'collapse';
                   1769:                 block.item(i).style.display = 'none';
                   1770:             }
                   1771:         };
                   1772:         saveState(lastresource);
                   1773:     }
                   1774: 
                   1775:     function saveState (lastresource) {
                   1776: 
                   1777:         var tag_list = getTagList();
                   1778:         if(tag_list != null){
                   1779:             var timestamp = new Date().getTime();
                   1780:             var key = lastresource;
                   1781: 
                   1782:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1783:             // starting with timestamp
                   1784:             var value = timestamp+';';
                   1785: 
                   1786:             // building the list of key-value pairs
                   1787:             for(var i = 0; i < tag_list.length; i++){
                   1788:                 value += tag_list[i]+',';
                   1789:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1790:             }
                   1791: 
                   1792:             // only iterate whole storage if nothing to override
                   1793:             if(localStorage.getItem(key) == null){
                   1794: 
                   1795:                 // prevent storage from growing large
                   1796:                 if(localStorage.length > 50){
                   1797:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1798:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1799:                     var oldest_key;
                   1800: 
                   1801:                     for(var i = 1; i < localStorage.length; i++){
                   1802:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1803:                             oldest_key = localStorage.key(i);
                   1804:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1805:                         }
                   1806:                     }
                   1807:                     localStorage.removeItem(oldest_key);
                   1808:                 }
                   1809:             }
                   1810:             localStorage.setItem(key,value);
                   1811:         }
                   1812:     }
                   1813: 
                   1814:     // restore folding status of blocks (on page load)
                   1815:     function restoreState (lastresource) {
                   1816:         if(localStorage.getItem(lastresource) != null){
                   1817:             var key = lastresource;
                   1818:             var value = localStorage.getItem(key);
                   1819:             var regex_delTimestamp = /^\d+;/;
                   1820: 
                   1821:             value.replace(regex_delTimestamp, '');
                   1822: 
                   1823:             var valueArr = value.split(';');
                   1824:             var pairs;
                   1825:             var elements;
                   1826:             for (var i = 0; i < valueArr.length; i++){
                   1827:                 pairs = valueArr[i].split(',');
                   1828:                 elements = document.getElementsByName(pairs[0]);
                   1829: 
                   1830:                 for (var j = 0; j < elements.length; j++){
                   1831:                     elements[j].style.display = pairs[1];
                   1832:                     if (pairs[1] == "none"){
                   1833:                         var regex_id = /([_\\d]+)\$/;
                   1834:                         regex_id.exec(pairs[0]);
                   1835:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1836:                     }
                   1837:                 }
                   1838:             }
                   1839:         }
                   1840:     }
                   1841: 
                   1842:     function getTagList () {
                   1843: 
                   1844:         var stringToSearch = document.lonhomework.innerHTML;
                   1845: 
                   1846:         var ret = new Array();
                   1847:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1848:         var tag_list = stringToSearch.match(regex_findBlock);
                   1849: 
                   1850:         if(tag_list != null){
                   1851:             for(var i = 0; i < tag_list.length; i++){
                   1852:                 ret.push(tag_list[i].replace(/"/, ''));
                   1853:             }
                   1854:         }
                   1855:         return ret;
                   1856:     }
                   1857: 
                   1858:     function saveScrollPosition (resource) {
                   1859:         var tag_list = getTagList();
                   1860: 
                   1861:         // we dont always want to jump to the first block
                   1862:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1863:         if(\$(window).scrollTop() > 170){
                   1864:             if(tag_list != null){
                   1865:                 var result;
                   1866:                 for(var i = 0; i < tag_list.length; i++){
                   1867:                     if(isElementInViewport(tag_list[i])){
                   1868:                         result += tag_list[i]+';';
                   1869:                     }
                   1870:                 }
                   1871:                 sessionStorage.setItem('anchor_'+resource, result);
                   1872:             }
                   1873:         } else {
                   1874:             // we dont need to save zero, just delete the item to leave everything tidy
                   1875:             sessionStorage.removeItem('anchor_'+resource);
                   1876:         }
                   1877:     }
                   1878: 
                   1879:     function restoreScrollPosition(resource){
                   1880: 
                   1881:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1882:         if(elem != null){
                   1883:             var tag_list = elem.split(';');
                   1884:             var elem_list;
                   1885: 
                   1886:             for(var i = 0; i < tag_list.length; i++){
                   1887:                 elem_list = document.getElementsByName(tag_list[i]);
                   1888: 
                   1889:                 if(elem_list.length > 0){
                   1890:                     elem = elem_list[0];
                   1891:                     break;
                   1892:                 }
                   1893:             }
                   1894:             elem.scrollIntoView();
                   1895:         }
                   1896:     }
                   1897: 
                   1898:     function isElementInViewport(el) {
                   1899: 
                   1900:         // change to last element instead of first
                   1901:         var elem = document.getElementsByName(el);
                   1902:         var rect = elem[0].getBoundingClientRect();
                   1903: 
                   1904:         return (
                   1905:             rect.top >= 0 &&
                   1906:             rect.left >= 0 &&
                   1907:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1908:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1909:         );
                   1910:     }
                   1911: 
                   1912:     function autosize(depth){
                   1913:         var cmInst = window['cm'+depth];
                   1914:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1915: 
                   1916:         // is fixed size, switching to dynamic
                   1917:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1918:             cmInst.setSize("","auto");
                   1919:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1920:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1921: 
                   1922:         // is dynamic size, switching to fixed
                   1923:         } else {
                   1924:             cmInst.setSize("","300px");
                   1925:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1926:             sessionStorage.removeItem("autosized_"+depth);
                   1927:         }
                   1928:     }
                   1929: 
                   1930: 
                   1931: 
                   1932: // ]]>
                   1933: </script>
                   1934: COLORFULEDIT
                   1935: }
                   1936: 
                   1937: sub xmleditor_js {
                   1938:     return <<XMLEDIT
                   1939: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1940: <script type="text/javascript">
                   1941: // <![CDATA[>
                   1942: 
                   1943:     function saveScrollPosition (resource) {
                   1944: 
                   1945:         var scrollPos = \$(window).scrollTop();
                   1946:         sessionStorage.setItem(resource,scrollPos);
                   1947:     }
                   1948: 
                   1949:     function restoreScrollPosition(resource){
                   1950: 
                   1951:         var scrollPos = sessionStorage.getItem(resource);
                   1952:         \$(window).scrollTop(scrollPos);
                   1953:     }
                   1954: 
                   1955:     // unless internet explorer
                   1956:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1957: 
                   1958:         \$(document).ready(function() {
                   1959:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1960:         });
                   1961:     }
                   1962: 
                   1963:     // inserts text at cursor position into codemirror (xml editor only)
                   1964:     function insertText(text){
                   1965:         cm.focus();
                   1966:         var curPos = cm.getCursor();
                   1967:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1968:     }
                   1969: // ]]>
                   1970: </script>
                   1971: XMLEDIT
                   1972: }
                   1973: 
                   1974: sub insert_folding_button {
                   1975:     my $curDepth = $Apache::lonxml::curdepth;
                   1976:     my $lastresource = $env{'request.ambiguous'};
                   1977: 
                   1978:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   1979:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   1980: }
                   1981: 
                   1982: 
1.565     albertel 1983: =pod
                   1984: 
1.256     matthew  1985: =head1 Excel and CSV file utility routines
                   1986: 
                   1987: =cut
                   1988: 
                   1989: ###############################################################
                   1990: ###############################################################
                   1991: 
                   1992: =pod
                   1993: 
1.1075.2.56  raeburn  1994: =over 4
                   1995: 
1.648     raeburn  1996: =item * &csv_translate($text) 
1.37      matthew  1997: 
1.185     www      1998: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1999: format.
                   2000: 
                   2001: =cut
                   2002: 
1.180     matthew  2003: ###############################################################
                   2004: ###############################################################
1.37      matthew  2005: sub csv_translate {
                   2006:     my $text = shift;
                   2007:     $text =~ s/\"/\"\"/g;
1.209     albertel 2008:     $text =~ s/\n/ /g;
1.37      matthew  2009:     return $text;
                   2010: }
1.180     matthew  2011: 
                   2012: ###############################################################
                   2013: ###############################################################
                   2014: 
                   2015: =pod
                   2016: 
1.648     raeburn  2017: =item * &define_excel_formats()
1.180     matthew  2018: 
                   2019: Define some commonly used Excel cell formats.
                   2020: 
                   2021: Currently supported formats:
                   2022: 
                   2023: =over 4
                   2024: 
                   2025: =item header
                   2026: 
                   2027: =item bold
                   2028: 
                   2029: =item h1
                   2030: 
                   2031: =item h2
                   2032: 
                   2033: =item h3
                   2034: 
1.256     matthew  2035: =item h4
                   2036: 
                   2037: =item i
                   2038: 
1.180     matthew  2039: =item date
                   2040: 
                   2041: =back
                   2042: 
                   2043: Inputs: $workbook
                   2044: 
                   2045: Returns: $format, a hash reference.
                   2046: 
1.1057    foxr     2047: 
1.180     matthew  2048: =cut
                   2049: 
                   2050: ###############################################################
                   2051: ###############################################################
                   2052: sub define_excel_formats {
                   2053:     my ($workbook) = @_;
                   2054:     my $format;
                   2055:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2056:                                                 bottom    => 1,
                   2057:                                                 align     => 'center');
                   2058:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2059:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2060:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2061:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2062:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2063:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2064:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2065:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2066:     return $format;
                   2067: }
                   2068: 
                   2069: ###############################################################
                   2070: ###############################################################
1.113     bowersj2 2071: 
                   2072: =pod
                   2073: 
1.648     raeburn  2074: =item * &create_workbook()
1.255     matthew  2075: 
                   2076: Create an Excel worksheet.  If it fails, output message on the
                   2077: request object and return undefs.
                   2078: 
                   2079: Inputs: Apache request object
                   2080: 
                   2081: Returns (undef) on failure, 
                   2082:     Excel worksheet object, scalar with filename, and formats 
                   2083:     from &Apache::loncommon::define_excel_formats on success
                   2084: 
                   2085: =cut
                   2086: 
                   2087: ###############################################################
                   2088: ###############################################################
                   2089: sub create_workbook {
                   2090:     my ($r) = @_;
                   2091:         #
                   2092:     # Create the excel spreadsheet
                   2093:     my $filename = '/prtspool/'.
1.258     albertel 2094:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2095:         time.'_'.rand(1000000000).'.xls';
                   2096:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2097:     if (! defined($workbook)) {
                   2098:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2099:         $r->print(
                   2100:             '<p class="LC_error">'
                   2101:            .&mt('Problems occurred in creating the new Excel file.')
                   2102:            .' '.&mt('This error has been logged.')
                   2103:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2104:            .'</p>'
                   2105:         );
1.255     matthew  2106:         return (undef);
                   2107:     }
                   2108:     #
1.1014    foxr     2109:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2110:     #
                   2111:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2112:     return ($workbook,$filename,$format);
                   2113: }
                   2114: 
                   2115: ###############################################################
                   2116: ###############################################################
                   2117: 
                   2118: =pod
                   2119: 
1.648     raeburn  2120: =item * &create_text_file()
1.113     bowersj2 2121: 
1.542     raeburn  2122: Create a file to write to and eventually make available to the user.
1.256     matthew  2123: If file creation fails, outputs an error message on the request object and 
                   2124: return undefs.
1.113     bowersj2 2125: 
1.256     matthew  2126: Inputs: Apache request object, and file suffix
1.113     bowersj2 2127: 
1.256     matthew  2128: Returns (undef) on failure, 
                   2129:     Filehandle and filename on success.
1.113     bowersj2 2130: 
                   2131: =cut
                   2132: 
1.256     matthew  2133: ###############################################################
                   2134: ###############################################################
                   2135: sub create_text_file {
                   2136:     my ($r,$suffix) = @_;
                   2137:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2138:     my $fh;
                   2139:     my $filename = '/prtspool/'.
1.258     albertel 2140:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2141:         time.'_'.rand(1000000000).'.'.$suffix;
                   2142:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2143:     if (! defined($fh)) {
                   2144:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2145:         $r->print(
                   2146:             '<p class="LC_error">'
                   2147:            .&mt('Problems occurred in creating the output file.')
                   2148:            .' '.&mt('This error has been logged.')
                   2149:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2150:            .'</p>'
                   2151:         );
1.113     bowersj2 2152:     }
1.256     matthew  2153:     return ($fh,$filename)
1.113     bowersj2 2154: }
                   2155: 
                   2156: 
1.256     matthew  2157: =pod 
1.113     bowersj2 2158: 
                   2159: =back
                   2160: 
                   2161: =cut
1.37      matthew  2162: 
                   2163: ###############################################################
1.33      matthew  2164: ##        Home server <option> list generating code          ##
                   2165: ###############################################################
1.35      matthew  2166: 
1.169     www      2167: # ------------------------------------------
                   2168: 
                   2169: sub domain_select {
                   2170:     my ($name,$value,$multiple)=@_;
                   2171:     my %domains=map { 
1.514     albertel 2172: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2173:     } &Apache::lonnet::all_domains();
1.169     www      2174:     if ($multiple) {
                   2175: 	$domains{''}=&mt('Any domain');
1.550     albertel 2176: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2177: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2178:     } else {
1.550     albertel 2179: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2180: 	return &select_form($name,$value,\%domains);
1.169     www      2181:     }
                   2182: }
                   2183: 
1.282     albertel 2184: #-------------------------------------------
                   2185: 
                   2186: =pod
                   2187: 
1.519     raeburn  2188: =head1 Routines for form select boxes
                   2189: 
                   2190: =over 4
                   2191: 
1.648     raeburn  2192: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2193: 
                   2194: Returns a string containing a <select> element int multiple mode
                   2195: 
                   2196: 
                   2197: Args:
                   2198:   $name - name of the <select> element
1.506     raeburn  2199:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2200:   $size - number of rows long the select element is
1.283     albertel 2201:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2202:           (shown text should already have been &mt())
1.506     raeburn  2203:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2204: 
1.282     albertel 2205: =cut
                   2206: 
                   2207: #-------------------------------------------
1.169     www      2208: sub multiple_select_form {
1.284     albertel 2209:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2210:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2211:     my $output='';
1.191     matthew  2212:     if (! defined($size)) {
                   2213:         $size = 4;
1.283     albertel 2214:         if (scalar(keys(%$hash))<4) {
                   2215:             $size = scalar(keys(%$hash));
1.191     matthew  2216:         }
                   2217:     }
1.734     bisitz   2218:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2219:     my @order;
1.506     raeburn  2220:     if (ref($order) eq 'ARRAY')  {
                   2221:         @order = @{$order};
                   2222:     } else {
                   2223:         @order = sort(keys(%$hash));
1.501     banghart 2224:     }
                   2225:     if (exists($$hash{'select_form_order'})) {
                   2226:         @order = @{$$hash{'select_form_order'}};
                   2227:     }
                   2228:         
1.284     albertel 2229:     foreach my $key (@order) {
1.356     albertel 2230:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2231:         $output.='selected="selected" ' if ($selected{$key});
                   2232:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2233:     }
                   2234:     $output.="</select>\n";
                   2235:     return $output;
                   2236: }
                   2237: 
1.88      www      2238: #-------------------------------------------
                   2239: 
                   2240: =pod
                   2241: 
1.1075.2.115  raeburn  2242: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2243: 
                   2244: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2245: allow a user to select options from a ref to a hash containing:
                   2246: option_name => displayed text. An optional $onchange can include
1.1075.2.115  raeburn  2247: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2248: An optional arg -- $readonly -- if true will cause the select form
                   2249: to be disabled, e.g., for the case where an instructor has a section-
                   2250: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2251: 
1.88      www      2252: See lonrights.pm for an example invocation and use.
                   2253: 
                   2254: =cut
                   2255: 
                   2256: #-------------------------------------------
                   2257: sub select_form {
1.1075.2.115  raeburn  2258:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2259:     return unless (ref($hashref) eq 'HASH');
                   2260:     if ($onchange) {
                   2261:         $onchange = ' onchange="'.$onchange.'"';
                   2262:     }
                   2263:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 2264:     my @keys;
1.970     raeburn  2265:     if (exists($hashref->{'select_form_order'})) {
                   2266: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2267:     } else {
1.970     raeburn  2268: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2269:     }
1.356     albertel 2270:     foreach my $key (@keys) {
                   2271:         $selectform.=
                   2272: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2273:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2274:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2275:     }
                   2276:     $selectform.="</select>";
                   2277:     return $selectform;
                   2278: }
                   2279: 
1.475     www      2280: # For display filters
                   2281: 
                   2282: sub display_filter {
1.1074    raeburn  2283:     my ($context) = @_;
1.475     www      2284:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2285:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2286:     my $phraseinput = 'hidden';
                   2287:     my $includeinput = 'hidden';
                   2288:     my ($checked,$includetypestext);
                   2289:     if ($env{'form.displayfilter'} eq 'containing') {
                   2290:         $phraseinput = 'text'; 
                   2291:         if ($context eq 'parmslog') {
                   2292:             $includeinput = 'checkbox';
                   2293:             if ($env{'form.includetypes'}) {
                   2294:                 $checked = ' checked="checked"';
                   2295:             }
                   2296:             $includetypestext = &mt('Include parameter types');
                   2297:         }
                   2298:     } else {
                   2299:         $includetypestext = '&nbsp;';
                   2300:     }
                   2301:     my ($additional,$secondid,$thirdid);
                   2302:     if ($context eq 'parmslog') {
                   2303:         $additional = 
                   2304:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2305:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2306:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2307:             '</label>';
                   2308:         $secondid = 'includetypes';
                   2309:         $thirdid = 'includetypestext';
                   2310:     }
                   2311:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2312:                                                     '$secondid','$thirdid')";
                   2313:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2314: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2315: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2316: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2317:            &mt('Filter: [_1]',
1.477     www      2318: 	   &select_form($env{'form.displayfilter'},
                   2319: 			'displayfilter',
1.970     raeburn  2320: 			{'currentfolder' => 'Current folder/page',
1.477     www      2321: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2322: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2323: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2324:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2325:                          '" />'.$additional;
                   2326: }
                   2327: 
                   2328: sub display_filter_js {
                   2329:     my $includetext = &mt('Include parameter types');
                   2330:     return <<"ENDJS";
                   2331:   
                   2332: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2333:     var firstType = 'hidden';
                   2334:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2335:         firstType = 'text';
                   2336:     }
                   2337:     firstObject = document.getElementById(firstid);
                   2338:     if (typeof(firstObject) == 'object') {
                   2339:         if (firstObject.type != firstType) {
                   2340:             changeInputType(firstObject,firstType);
                   2341:         }
                   2342:     }
                   2343:     if (context == 'parmslog') {
                   2344:         var secondType = 'hidden';
                   2345:         if (firstType == 'text') {
                   2346:             secondType = 'checkbox';
                   2347:         }
                   2348:         secondObject = document.getElementById(secondid);  
                   2349:         if (typeof(secondObject) == 'object') {
                   2350:             if (secondObject.type != secondType) {
                   2351:                 changeInputType(secondObject,secondType);
                   2352:             }
                   2353:         }
                   2354:         var textItem = document.getElementById(thirdid);
                   2355:         var currtext = textItem.innerHTML;
                   2356:         var newtext;
                   2357:         if (firstType == 'text') {
                   2358:             newtext = '$includetext';
                   2359:         } else {
                   2360:             newtext = '&nbsp;';
                   2361:         }
                   2362:         if (currtext != newtext) {
                   2363:             textItem.innerHTML = newtext;
                   2364:         }
                   2365:     }
                   2366:     return;
                   2367: }
                   2368: 
                   2369: function changeInputType(oldObject,newType) {
                   2370:     var newObject = document.createElement('input');
                   2371:     newObject.type = newType;
                   2372:     if (oldObject.size) {
                   2373:         newObject.size = oldObject.size;
                   2374:     }
                   2375:     if (oldObject.value) {
                   2376:         newObject.value = oldObject.value;
                   2377:     }
                   2378:     if (oldObject.name) {
                   2379:         newObject.name = oldObject.name;
                   2380:     }
                   2381:     if (oldObject.id) {
                   2382:         newObject.id = oldObject.id;
                   2383:     }
                   2384:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2385:     return;
                   2386: }
                   2387: 
                   2388: ENDJS
1.475     www      2389: }
                   2390: 
1.167     www      2391: sub gradeleveldescription {
                   2392:     my $gradelevel=shift;
                   2393:     my %gradelevels=(0 => 'Not specified',
                   2394: 		     1 => 'Grade 1',
                   2395: 		     2 => 'Grade 2',
                   2396: 		     3 => 'Grade 3',
                   2397: 		     4 => 'Grade 4',
                   2398: 		     5 => 'Grade 5',
                   2399: 		     6 => 'Grade 6',
                   2400: 		     7 => 'Grade 7',
                   2401: 		     8 => 'Grade 8',
                   2402: 		     9 => 'Grade 9',
                   2403: 		     10 => 'Grade 10',
                   2404: 		     11 => 'Grade 11',
                   2405: 		     12 => 'Grade 12',
                   2406: 		     13 => 'Grade 13',
                   2407: 		     14 => '100 Level',
                   2408: 		     15 => '200 Level',
                   2409: 		     16 => '300 Level',
                   2410: 		     17 => '400 Level',
                   2411: 		     18 => 'Graduate Level');
                   2412:     return &mt($gradelevels{$gradelevel});
                   2413: }
                   2414: 
1.163     www      2415: sub select_level_form {
                   2416:     my ($deflevel,$name)=@_;
                   2417:     unless ($deflevel) { $deflevel=0; }
1.167     www      2418:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2419:     for (my $i=0; $i<=18; $i++) {
                   2420:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2421:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2422:                 ">".&gradeleveldescription($i)."</option>\n";
                   2423:     }
                   2424:     $selectform.="</select>";
                   2425:     return $selectform;
1.163     www      2426: }
1.167     www      2427: 
1.35      matthew  2428: #-------------------------------------------
                   2429: 
1.45      matthew  2430: =pod
                   2431: 
1.1075.2.115  raeburn  2432: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2433: 
                   2434: Returns a string containing a <select name='$name' size='1'> form to 
                   2435: allow a user to select the domain to preform an operation in.  
                   2436: See loncreateuser.pm for an example invocation and use.
                   2437: 
1.90      www      2438: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2439: selected");
                   2440: 
1.743     raeburn  2441: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2442: 
1.910     raeburn  2443: 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.
                   2444: 
1.1075.2.36  raeburn  2445: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2446: 
1.1075.2.115  raeburn  2447: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2448: 
                   2449: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2450: 
1.35      matthew  2451: =cut
                   2452: 
                   2453: #-------------------------------------------
1.34      matthew  2454: sub select_dom_form {
1.1075.2.115  raeburn  2455:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2456:     if ($onchange) {
1.874     raeburn  2457:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2458:     }
1.1075.2.115  raeburn  2459:     if ($disabled) {
                   2460:         $disabled = ' disabled="disabled"';
                   2461:     }
1.1075.2.36  raeburn  2462:     my (@domains,%exclude);
1.910     raeburn  2463:     if (ref($incdoms) eq 'ARRAY') {
                   2464:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2465:     } else {
                   2466:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2467:     }
1.90      www      2468:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2469:     if (ref($excdoms) eq 'ARRAY') {
                   2470:         map { $exclude{$_} = 1; } @{$excdoms};
                   2471:     }
1.1075.2.115  raeburn  2472:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2473:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2474:         next if ($exclude{$dom});
1.356     albertel 2475:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2476:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2477:         if ($showdomdesc) {
                   2478:             if ($dom ne '') {
                   2479:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2480:                 if ($domdesc ne '') {
                   2481:                     $selectdomain .= ' ('.$domdesc.')';
                   2482:                 }
                   2483:             } 
                   2484:         }
                   2485:         $selectdomain .= "</option>\n";
1.34      matthew  2486:     }
                   2487:     $selectdomain.="</select>";
                   2488:     return $selectdomain;
                   2489: }
                   2490: 
1.35      matthew  2491: #-------------------------------------------
                   2492: 
1.45      matthew  2493: =pod
                   2494: 
1.648     raeburn  2495: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2496: 
1.586     raeburn  2497: input: 4 arguments (two required, two optional) - 
                   2498:     $domain - domain of new user
                   2499:     $name - name of form element
                   2500:     $default - Value of 'default' causes a default item to be first 
                   2501:                             option, and selected by default. 
                   2502:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2503:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2504: output: returns 2 items: 
1.586     raeburn  2505: (a) form element which contains either:
                   2506:    (i) <select name="$name">
                   2507:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2508:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2509:        </select>
                   2510:        form item if there are multiple library servers in $domain, or
                   2511:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2512:        if there is only one library server in $domain.
                   2513: 
                   2514: (b) number of library servers found.
                   2515: 
                   2516: See loncreateuser.pm for example of use.
1.35      matthew  2517: 
                   2518: =cut
                   2519: 
                   2520: #-------------------------------------------
1.586     raeburn  2521: sub home_server_form_item {
                   2522:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2523:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2524:     my $result;
                   2525:     my $numlib = keys(%servers);
                   2526:     if ($numlib > 1) {
                   2527:         $result .= '<select name="'.$name.'" />'."\n";
                   2528:         if ($default) {
1.804     bisitz   2529:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2530:                        '</option>'."\n";
                   2531:         }
                   2532:         foreach my $hostid (sort(keys(%servers))) {
                   2533:             $result.= '<option value="'.$hostid.'">'.
                   2534: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2535:         }
                   2536:         $result .= '</select>'."\n";
                   2537:     } elsif ($numlib == 1) {
                   2538:         my $hostid;
                   2539:         foreach my $item (keys(%servers)) {
                   2540:             $hostid = $item;
                   2541:         }
                   2542:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2543:                    $hostid.'" />';
                   2544:                    if (!$hide) {
                   2545:                        $result .= $hostid.' '.$servers{$hostid};
                   2546:                    }
                   2547:                    $result .= "\n";
                   2548:     } elsif ($default) {
                   2549:         $result .= '<input type="hidden" name="'.$name.
                   2550:                    '" value="default" />';
                   2551:                    if (!$hide) {
                   2552:                        $result .= &mt('default');
                   2553:                    }
                   2554:                    $result .= "\n";
1.33      matthew  2555:     }
1.586     raeburn  2556:     return ($result,$numlib);
1.33      matthew  2557: }
1.112     bowersj2 2558: 
                   2559: =pod
                   2560: 
1.534     albertel 2561: =back 
                   2562: 
1.112     bowersj2 2563: =cut
1.87      matthew  2564: 
                   2565: ###############################################################
1.112     bowersj2 2566: ##                  Decoding User Agent                      ##
1.87      matthew  2567: ###############################################################
                   2568: 
                   2569: =pod
                   2570: 
1.112     bowersj2 2571: =head1 Decoding the User Agent
                   2572: 
                   2573: =over 4
                   2574: 
                   2575: =item * &decode_user_agent()
1.87      matthew  2576: 
                   2577: Inputs: $r
                   2578: 
                   2579: Outputs:
                   2580: 
                   2581: =over 4
                   2582: 
1.112     bowersj2 2583: =item * $httpbrowser
1.87      matthew  2584: 
1.112     bowersj2 2585: =item * $clientbrowser
1.87      matthew  2586: 
1.112     bowersj2 2587: =item * $clientversion
1.87      matthew  2588: 
1.112     bowersj2 2589: =item * $clientmathml
1.87      matthew  2590: 
1.112     bowersj2 2591: =item * $clientunicode
1.87      matthew  2592: 
1.112     bowersj2 2593: =item * $clientos
1.87      matthew  2594: 
1.1075.2.42  raeburn  2595: =item * $clientmobile
                   2596: 
                   2597: =item * $clientinfo
                   2598: 
1.1075.2.77  raeburn  2599: =item * $clientosversion
                   2600: 
1.87      matthew  2601: =back
                   2602: 
1.157     matthew  2603: =back 
                   2604: 
1.87      matthew  2605: =cut
                   2606: 
                   2607: ###############################################################
                   2608: ###############################################################
                   2609: sub decode_user_agent {
1.247     albertel 2610:     my ($r)=@_;
1.87      matthew  2611:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2612:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2613:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2614:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2615:     my $clientbrowser='unknown';
                   2616:     my $clientversion='0';
                   2617:     my $clientmathml='';
                   2618:     my $clientunicode='0';
1.1075.2.42  raeburn  2619:     my $clientmobile=0;
1.1075.2.77  raeburn  2620:     my $clientosversion='';
1.87      matthew  2621:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2622:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2623: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2624: 	    $clientbrowser=$bname;
                   2625:             $httpbrowser=~/$vreg/i;
                   2626: 	    $clientversion=$1;
                   2627:             $clientmathml=($clientversion>=$minv);
                   2628:             $clientunicode=($clientversion>=$univ);
                   2629: 	}
                   2630:     }
                   2631:     my $clientos='unknown';
1.1075.2.42  raeburn  2632:     my $clientinfo;
1.87      matthew  2633:     if (($httpbrowser=~/linux/i) ||
                   2634:         ($httpbrowser=~/unix/i) ||
                   2635:         ($httpbrowser=~/ux/i) ||
                   2636:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2637:     if (($httpbrowser=~/vax/i) ||
                   2638:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2639:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2640:     if (($httpbrowser=~/mac/i) ||
                   2641:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2642:     if ($httpbrowser=~/win/i) {
                   2643:         $clientos='win';
                   2644:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2645:             $clientosversion = $1;
                   2646:         }
                   2647:     }
1.87      matthew  2648:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2649:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2650:         $clientmobile=lc($1);
                   2651:     }
                   2652:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2653:         $clientinfo = 'firefox-'.$1;
                   2654:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2655:         $clientinfo = 'chromeframe-'.$1;
                   2656:     }
1.87      matthew  2657:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2658:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2659:             $clientosversion);
1.87      matthew  2660: }
                   2661: 
1.32      matthew  2662: ###############################################################
                   2663: ##    Authentication changing form generation subroutines    ##
                   2664: ###############################################################
                   2665: ##
                   2666: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2667: ## hash, and have reasonable default values.
                   2668: ##
                   2669: ##    formname = the name given in the <form> tag.
1.35      matthew  2670: #-------------------------------------------
                   2671: 
1.45      matthew  2672: =pod
                   2673: 
1.112     bowersj2 2674: =head1 Authentication Routines
                   2675: 
                   2676: =over 4
                   2677: 
1.648     raeburn  2678: =item * &authform_xxxxxx()
1.35      matthew  2679: 
                   2680: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2681: handle some of the conveniences required for authentication forms.  
                   2682: This is not an optimal method, but it works.  
                   2683: 
                   2684: =over 4
                   2685: 
1.112     bowersj2 2686: =item * authform_header
1.35      matthew  2687: 
1.112     bowersj2 2688: =item * authform_authorwarning
1.35      matthew  2689: 
1.112     bowersj2 2690: =item * authform_nochange
1.35      matthew  2691: 
1.112     bowersj2 2692: =item * authform_kerberos
1.35      matthew  2693: 
1.112     bowersj2 2694: =item * authform_internal
1.35      matthew  2695: 
1.112     bowersj2 2696: =item * authform_filesystem
1.35      matthew  2697: 
                   2698: =back
                   2699: 
1.648     raeburn  2700: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2701: 
1.35      matthew  2702: =cut
                   2703: 
                   2704: #-------------------------------------------
1.32      matthew  2705: sub authform_header{  
                   2706:     my %in = (
                   2707:         formname => 'cu',
1.80      albertel 2708:         kerb_def_dom => '',
1.32      matthew  2709:         @_,
                   2710:     );
                   2711:     $in{'formname'} = 'document.' . $in{'formname'};
                   2712:     my $result='';
1.80      albertel 2713: 
                   2714: #---------------------------------------------- Code for upper case translation
                   2715:     my $Javascript_toUpperCase;
                   2716:     unless ($in{kerb_def_dom}) {
                   2717:         $Javascript_toUpperCase =<<"END";
                   2718:         switch (choice) {
                   2719:            case 'krb': currentform.elements[choicearg].value =
                   2720:                currentform.elements[choicearg].value.toUpperCase();
                   2721:                break;
                   2722:            default:
                   2723:         }
                   2724: END
                   2725:     } else {
                   2726:         $Javascript_toUpperCase = "";
                   2727:     }
                   2728: 
1.165     raeburn  2729:     my $radioval = "'nochange'";
1.591     raeburn  2730:     if (defined($in{'curr_authtype'})) {
                   2731:         if ($in{'curr_authtype'} ne '') {
                   2732:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2733:         }
1.174     matthew  2734:     }
1.165     raeburn  2735:     my $argfield = 'null';
1.591     raeburn  2736:     if (defined($in{'mode'})) {
1.165     raeburn  2737:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2738:             if (defined($in{'curr_autharg'})) {
                   2739:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2740:                     $argfield = "'$in{'curr_autharg'}'";
                   2741:                 }
                   2742:             }
                   2743:         }
                   2744:     }
                   2745: 
1.32      matthew  2746:     $result.=<<"END";
                   2747: var current = new Object();
1.165     raeburn  2748: current.radiovalue = $radioval;
                   2749: current.argfield = $argfield;
1.32      matthew  2750: 
                   2751: function changed_radio(choice,currentform) {
                   2752:     var choicearg = choice + 'arg';
                   2753:     // If a radio button in changed, we need to change the argfield
                   2754:     if (current.radiovalue != choice) {
                   2755:         current.radiovalue = choice;
                   2756:         if (current.argfield != null) {
                   2757:             currentform.elements[current.argfield].value = '';
                   2758:         }
                   2759:         if (choice == 'nochange') {
                   2760:             current.argfield = null;
                   2761:         } else {
                   2762:             current.argfield = choicearg;
                   2763:             switch(choice) {
                   2764:                 case 'krb': 
                   2765:                     currentform.elements[current.argfield].value = 
                   2766:                         "$in{'kerb_def_dom'}";
                   2767:                 break;
                   2768:               default:
                   2769:                 break;
                   2770:             }
                   2771:         }
                   2772:     }
                   2773:     return;
                   2774: }
1.22      www      2775: 
1.32      matthew  2776: function changed_text(choice,currentform) {
                   2777:     var choicearg = choice + 'arg';
                   2778:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2779:         $Javascript_toUpperCase
1.32      matthew  2780:         // clear old field
                   2781:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2782:             currentform.elements[current.argfield].value = '';
                   2783:         }
                   2784:         current.argfield = choicearg;
                   2785:     }
                   2786:     set_auth_radio_buttons(choice,currentform);
                   2787:     return;
1.20      www      2788: }
1.32      matthew  2789: 
                   2790: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2791:     var numauthchoices = currentform.login.length;
                   2792:     if (typeof numauthchoices  == "undefined") {
                   2793:         return;
                   2794:     } 
1.32      matthew  2795:     var i=0;
1.986     raeburn  2796:     while (i < numauthchoices) {
1.32      matthew  2797:         if (currentform.login[i].value == newvalue) { break; }
                   2798:         i++;
                   2799:     }
1.986     raeburn  2800:     if (i == numauthchoices) {
1.32      matthew  2801:         return;
                   2802:     }
                   2803:     current.radiovalue = newvalue;
                   2804:     currentform.login[i].checked = true;
                   2805:     return;
                   2806: }
                   2807: END
                   2808:     return $result;
                   2809: }
                   2810: 
1.1075.2.20  raeburn  2811: sub authform_authorwarning {
1.32      matthew  2812:     my $result='';
1.144     matthew  2813:     $result='<i>'.
                   2814:         &mt('As a general rule, only authors or co-authors should be '.
                   2815:             'filesystem authenticated '.
                   2816:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2817:     return $result;
                   2818: }
                   2819: 
1.1075.2.20  raeburn  2820: sub authform_nochange {
1.32      matthew  2821:     my %in = (
                   2822:               formname => 'document.cu',
                   2823:               kerb_def_dom => 'MSU.EDU',
                   2824:               @_,
                   2825:           );
1.1075.2.20  raeburn  2826:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2827:     my $result;
1.1075.2.20  raeburn  2828:     if (!$authnum) {
                   2829:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2830:     } else {
                   2831:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2832:                   '<input type="radio" name="login" value="nochange" '.
                   2833:                   'checked="checked" onclick="'.
1.281     albertel 2834:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2835: 	    '</label>';
1.586     raeburn  2836:     }
1.32      matthew  2837:     return $result;
                   2838: }
                   2839: 
1.591     raeburn  2840: sub authform_kerberos {
1.32      matthew  2841:     my %in = (
                   2842:               formname => 'document.cu',
                   2843:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2844:               kerb_def_auth => 'krb4',
1.32      matthew  2845:               @_,
                   2846:               );
1.586     raeburn  2847:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2848:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2849:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2850:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2851:        $check5 = ' checked="checked"';
1.80      albertel 2852:     } else {
1.772     bisitz   2853:        $check4 = ' checked="checked"';
1.80      albertel 2854:     }
1.1075.2.117  raeburn  2855:     if ($in{'readonly'}) {
                   2856:         $disabled = ' disabled="disabled"';
                   2857:     }
1.165     raeburn  2858:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2859:     if (defined($in{'curr_authtype'})) {
                   2860:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2861:             $krbcheck = ' checked="checked"';
1.623     raeburn  2862:             if (defined($in{'mode'})) {
                   2863:                 if ($in{'mode'} eq 'modifyuser') {
                   2864:                     $krbcheck = '';
                   2865:                 }
                   2866:             }
1.591     raeburn  2867:             if (defined($in{'curr_kerb_ver'})) {
                   2868:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2869:                     $check5 = ' checked="checked"';
1.591     raeburn  2870:                     $check4 = '';
                   2871:                 } else {
1.772     bisitz   2872:                     $check4 = ' checked="checked"';
1.591     raeburn  2873:                     $check5 = '';
                   2874:                 }
1.586     raeburn  2875:             }
1.591     raeburn  2876:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2877:                 $krbarg = $in{'curr_autharg'};
                   2878:             }
1.586     raeburn  2879:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2880:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2881:                     $result = 
                   2882:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2883:         $in{'curr_autharg'},$krbver);
                   2884:                 } else {
                   2885:                     $result =
                   2886:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2887:                 }
                   2888:                 return $result; 
                   2889:             }
                   2890:         }
                   2891:     } else {
                   2892:         if ($authnum == 1) {
1.784     bisitz   2893:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2894:         }
                   2895:     }
1.586     raeburn  2896:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2897:         return;
1.587     raeburn  2898:     } elsif ($authtype eq '') {
1.591     raeburn  2899:         if (defined($in{'mode'})) {
1.587     raeburn  2900:             if ($in{'mode'} eq 'modifycourse') {
                   2901:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2902:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  2903:                 }
                   2904:             }
                   2905:         }
1.586     raeburn  2906:     }
                   2907:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2908:     if ($authtype eq '') {
                   2909:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2910:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  2911:                     $krbcheck.$disabled.' />';
1.586     raeburn  2912:     }
                   2913:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2914:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2915:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2916:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2917:          $in{'curr_authtype'} eq 'krb4')) {
                   2918:         $result .= &mt
1.144     matthew  2919:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2920:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2921:          '<label>'.$authtype,
1.281     albertel 2922:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2923:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2924:              'onchange="'.$jscall.'"'.$disabled.' />',
                   2925:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   2926:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 2927: 	 '</label>');
1.586     raeburn  2928:     } elsif ($can_assign{'krb4'}) {
                   2929:         $result .= &mt
                   2930:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2931:          '[_3] Version 4 [_4]',
                   2932:          '<label>'.$authtype,
                   2933:          '</label><input type="text" size="10" name="krbarg" '.
                   2934:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2935:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2936:          '<label><input type="hidden" name="krbver" value="4" />',
                   2937:          '</label>');
                   2938:     } elsif ($can_assign{'krb5'}) {
                   2939:         $result .= &mt
                   2940:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2941:          '[_3] Version 5 [_4]',
                   2942:          '<label>'.$authtype,
                   2943:          '</label><input type="text" size="10" name="krbarg" '.
                   2944:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2945:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2946:          '<label><input type="hidden" name="krbver" value="5" />',
                   2947:          '</label>');
                   2948:     }
1.32      matthew  2949:     return $result;
                   2950: }
                   2951: 
1.1075.2.20  raeburn  2952: sub authform_internal {
1.586     raeburn  2953:     my %in = (
1.32      matthew  2954:                 formname => 'document.cu',
                   2955:                 kerb_def_dom => 'MSU.EDU',
                   2956:                 @_,
                   2957:                 );
1.1075.2.117  raeburn  2958:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2959:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  2960:     if ($in{'readonly'}) {
                   2961:         $disabled = ' disabled="disabled"';
                   2962:     }
1.591     raeburn  2963:     if (defined($in{'curr_authtype'})) {
                   2964:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2965:             if ($can_assign{'int'}) {
1.772     bisitz   2966:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2967:                 if (defined($in{'mode'})) {
                   2968:                     if ($in{'mode'} eq 'modifyuser') {
                   2969:                         $intcheck = '';
                   2970:                     }
                   2971:                 }
1.591     raeburn  2972:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2973:                     $intarg = $in{'curr_autharg'};
                   2974:                 }
                   2975:             } else {
                   2976:                 $result = &mt('Currently internally authenticated.');
                   2977:                 return $result;
1.165     raeburn  2978:             }
                   2979:         }
1.586     raeburn  2980:     } else {
                   2981:         if ($authnum == 1) {
1.784     bisitz   2982:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2983:         }
                   2984:     }
                   2985:     if (!$can_assign{'int'}) {
                   2986:         return;
1.587     raeburn  2987:     } elsif ($authtype eq '') {
1.591     raeburn  2988:         if (defined($in{'mode'})) {
1.587     raeburn  2989:             if ($in{'mode'} eq 'modifycourse') {
                   2990:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2991:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  2992:                 }
                   2993:             }
                   2994:         }
1.165     raeburn  2995:     }
1.586     raeburn  2996:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2997:     if ($authtype eq '') {
                   2998:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  2999:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3000:     }
1.605     bisitz   3001:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3002:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3003:     $result = &mt
1.144     matthew  3004:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3005:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3006:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
1.32      matthew  3007:     return $result;
                   3008: }
                   3009: 
1.1075.2.20  raeburn  3010: sub authform_local {
1.32      matthew  3011:     my %in = (
                   3012:               formname => 'document.cu',
                   3013:               kerb_def_dom => 'MSU.EDU',
                   3014:               @_,
                   3015:               );
1.1075.2.117  raeburn  3016:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3017:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3018:     if ($in{'readonly'}) {
                   3019:         $disabled = ' disabled="disabled"';
                   3020:     }
1.591     raeburn  3021:     if (defined($in{'curr_authtype'})) {
                   3022:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3023:             if ($can_assign{'loc'}) {
1.772     bisitz   3024:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3025:                 if (defined($in{'mode'})) {
                   3026:                     if ($in{'mode'} eq 'modifyuser') {
                   3027:                         $loccheck = '';
                   3028:                     }
                   3029:                 }
1.591     raeburn  3030:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3031:                     $locarg = $in{'curr_autharg'};
                   3032:                 }
                   3033:             } else {
                   3034:                 $result = &mt('Currently using local (institutional) authentication.');
                   3035:                 return $result;
1.165     raeburn  3036:             }
                   3037:         }
1.586     raeburn  3038:     } else {
                   3039:         if ($authnum == 1) {
1.784     bisitz   3040:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3041:         }
                   3042:     }
                   3043:     if (!$can_assign{'loc'}) {
                   3044:         return;
1.587     raeburn  3045:     } elsif ($authtype eq '') {
1.591     raeburn  3046:         if (defined($in{'mode'})) {
1.587     raeburn  3047:             if ($in{'mode'} eq 'modifycourse') {
                   3048:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3049:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3050:                 }
                   3051:             }
                   3052:         }
1.165     raeburn  3053:     }
1.586     raeburn  3054:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3055:     if ($authtype eq '') {
                   3056:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3057:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3058:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3059:     }
                   3060:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3061:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3062:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3063:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3064:     return $result;
                   3065: }
                   3066: 
1.1075.2.20  raeburn  3067: sub authform_filesystem {
1.32      matthew  3068:     my %in = (
                   3069:               formname => 'document.cu',
                   3070:               kerb_def_dom => 'MSU.EDU',
                   3071:               @_,
                   3072:               );
1.1075.2.117  raeburn  3073:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3074:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3075:     if ($in{'readonly'}) {
                   3076:         $disabled = ' disabled="disabled"';
                   3077:     }
1.591     raeburn  3078:     if (defined($in{'curr_authtype'})) {
                   3079:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3080:             if ($can_assign{'fsys'}) {
1.772     bisitz   3081:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3082:                 if (defined($in{'mode'})) {
                   3083:                     if ($in{'mode'} eq 'modifyuser') {
                   3084:                         $fsyscheck = '';
                   3085:                     }
                   3086:                 }
1.586     raeburn  3087:             } else {
                   3088:                 $result = &mt('Currently Filesystem Authenticated.');
                   3089:                 return $result;
                   3090:             }           
                   3091:         }
                   3092:     } else {
                   3093:         if ($authnum == 1) {
1.784     bisitz   3094:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3095:         }
                   3096:     }
                   3097:     if (!$can_assign{'fsys'}) {
                   3098:         return;
1.587     raeburn  3099:     } elsif ($authtype eq '') {
1.591     raeburn  3100:         if (defined($in{'mode'})) {
1.587     raeburn  3101:             if ($in{'mode'} eq 'modifycourse') {
                   3102:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3103:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3104:                 }
                   3105:             }
                   3106:         }
1.586     raeburn  3107:     }
                   3108:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3109:     if ($authtype eq '') {
                   3110:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3111:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3112:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3113:     }
                   3114:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3115:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3116:     $result = &mt
1.144     matthew  3117:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3118:          '<label><input type="radio" name="login" value="fsys" '.
1.1075.2.117  raeburn  3119:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
1.605     bisitz   3120:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.1075.2.117  raeburn  3121:                   'onchange="'.$jscall.'"'.$disabled.' />');
1.32      matthew  3122:     return $result;
                   3123: }
                   3124: 
1.586     raeburn  3125: sub get_assignable_auth {
                   3126:     my ($dom) = @_;
                   3127:     if ($dom eq '') {
                   3128:         $dom = $env{'request.role.domain'};
                   3129:     }
                   3130:     my %can_assign = (
                   3131:                           krb4 => 1,
                   3132:                           krb5 => 1,
                   3133:                           int  => 1,
                   3134:                           loc  => 1,
                   3135:                      );
                   3136:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3137:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3138:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3139:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3140:             my $context;
                   3141:             if ($env{'request.role'} =~ /^au/) {
                   3142:                 $context = 'author';
1.1075.2.117  raeburn  3143:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3144:                 $context = 'domain';
                   3145:             } elsif ($env{'request.course.id'}) {
                   3146:                 $context = 'course';
                   3147:             }
                   3148:             if ($context) {
                   3149:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3150:                    %can_assign = %{$authhash->{$context}}; 
                   3151:                 }
                   3152:             }
                   3153:         }
                   3154:     }
                   3155:     my $authnum = 0;
                   3156:     foreach my $key (keys(%can_assign)) {
                   3157:         if ($can_assign{$key}) {
                   3158:             $authnum ++;
                   3159:         }
                   3160:     }
                   3161:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3162:         $authnum --;
                   3163:     }
                   3164:     return ($authnum,%can_assign);
                   3165: }
                   3166: 
1.80      albertel 3167: ###############################################################
                   3168: ##    Get Kerberos Defaults for Domain                 ##
                   3169: ###############################################################
                   3170: ##
                   3171: ## Returns default kerberos version and an associated argument
                   3172: ## as listed in file domain.tab. If not listed, provides
                   3173: ## appropriate default domain and kerberos version.
                   3174: ##
                   3175: #-------------------------------------------
                   3176: 
                   3177: =pod
                   3178: 
1.648     raeburn  3179: =item * &get_kerberos_defaults()
1.80      albertel 3180: 
                   3181: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3182: version and domain. If not found, it defaults to version 4 and the 
                   3183: domain of the server.
1.80      albertel 3184: 
1.648     raeburn  3185: =over 4
                   3186: 
1.80      albertel 3187: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3188: 
1.648     raeburn  3189: =back
                   3190: 
                   3191: =back
                   3192: 
1.80      albertel 3193: =cut
                   3194: 
                   3195: #-------------------------------------------
                   3196: sub get_kerberos_defaults {
                   3197:     my $domain=shift;
1.641     raeburn  3198:     my ($krbdef,$krbdefdom);
                   3199:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3200:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3201:         $krbdef = $domdefaults{'auth_def'};
                   3202:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3203:     } else {
1.80      albertel 3204:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3205:         my $krbdefdom=$1;
                   3206:         $krbdefdom=~tr/a-z/A-Z/;
                   3207:         $krbdef = "krb4";
                   3208:     }
                   3209:     return ($krbdef,$krbdefdom);
                   3210: }
1.112     bowersj2 3211: 
1.32      matthew  3212: 
1.46      matthew  3213: ###############################################################
                   3214: ##                Thesaurus Functions                        ##
                   3215: ###############################################################
1.20      www      3216: 
1.46      matthew  3217: =pod
1.20      www      3218: 
1.112     bowersj2 3219: =head1 Thesaurus Functions
                   3220: 
                   3221: =over 4
                   3222: 
1.648     raeburn  3223: =item * &initialize_keywords()
1.46      matthew  3224: 
                   3225: Initializes the package variable %Keywords if it is empty.  Uses the
                   3226: package variable $thesaurus_db_file.
                   3227: 
                   3228: =cut
                   3229: 
                   3230: ###################################################
                   3231: 
                   3232: sub initialize_keywords {
                   3233:     return 1 if (scalar keys(%Keywords));
                   3234:     # If we are here, %Keywords is empty, so fill it up
                   3235:     #   Make sure the file we need exists...
                   3236:     if (! -e $thesaurus_db_file) {
                   3237:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3238:                                  " failed because it does not exist");
                   3239:         return 0;
                   3240:     }
                   3241:     #   Set up the hash as a database
                   3242:     my %thesaurus_db;
                   3243:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3244:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3245:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3246:                                  $thesaurus_db_file);
                   3247:         return 0;
                   3248:     } 
                   3249:     #  Get the average number of appearances of a word.
                   3250:     my $avecount = $thesaurus_db{'average.count'};
                   3251:     #  Put keywords (those that appear > average) into %Keywords
                   3252:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3253:         my ($count,undef) = split /:/,$data;
                   3254:         $Keywords{$word}++ if ($count > $avecount);
                   3255:     }
                   3256:     untie %thesaurus_db;
                   3257:     # Remove special values from %Keywords.
1.356     albertel 3258:     foreach my $value ('total.count','average.count') {
                   3259:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3260:   }
1.46      matthew  3261:     return 1;
                   3262: }
                   3263: 
                   3264: ###################################################
                   3265: 
                   3266: =pod
                   3267: 
1.648     raeburn  3268: =item * &keyword($word)
1.46      matthew  3269: 
                   3270: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3271: than the average number of times in the thesaurus database.  Calls 
                   3272: &initialize_keywords
                   3273: 
                   3274: =cut
                   3275: 
                   3276: ###################################################
1.20      www      3277: 
                   3278: sub keyword {
1.46      matthew  3279:     return if (!&initialize_keywords());
                   3280:     my $word=lc(shift());
                   3281:     $word=~s/\W//g;
                   3282:     return exists($Keywords{$word});
1.20      www      3283: }
1.46      matthew  3284: 
                   3285: ###############################################################
                   3286: 
                   3287: =pod 
1.20      www      3288: 
1.648     raeburn  3289: =item * &get_related_words()
1.46      matthew  3290: 
1.160     matthew  3291: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3292: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3293: will be returned.  The order of the words returned is determined by the
                   3294: database which holds them.
                   3295: 
                   3296: Uses global $thesaurus_db_file.
                   3297: 
1.1057    foxr     3298: 
1.46      matthew  3299: =cut
                   3300: 
                   3301: ###############################################################
                   3302: sub get_related_words {
                   3303:     my $keyword = shift;
                   3304:     my %thesaurus_db;
                   3305:     if (! -e $thesaurus_db_file) {
                   3306:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3307:                                  "failed because the file does not exist");
                   3308:         return ();
                   3309:     }
                   3310:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3311:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3312:         return ();
                   3313:     } 
                   3314:     my @Words=();
1.429     www      3315:     my $count=0;
1.46      matthew  3316:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3317: 	# The first element is the number of times
                   3318: 	# the word appears.  We do not need it now.
1.429     www      3319: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3320: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3321: 	my $threshold=$mostfrequentcount/10;
                   3322:         foreach my $possibleword (@RelatedWords) {
                   3323:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3324:             if ($wordcount>$threshold) {
                   3325: 		push(@Words,$word);
                   3326:                 $count++;
                   3327:                 if ($count>10) { last; }
                   3328: 	    }
1.20      www      3329:         }
                   3330:     }
1.46      matthew  3331:     untie %thesaurus_db;
                   3332:     return @Words;
1.14      harris41 3333: }
1.46      matthew  3334: 
1.112     bowersj2 3335: =pod
                   3336: 
                   3337: =back
                   3338: 
                   3339: =cut
1.61      www      3340: 
                   3341: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3342: =pod
                   3343: 
1.112     bowersj2 3344: =head1 User Name Functions
                   3345: 
                   3346: =over 4
                   3347: 
1.648     raeburn  3348: =item * &plainname($uname,$udom,$first)
1.81      albertel 3349: 
1.112     bowersj2 3350: Takes a users logon name and returns it as a string in
1.226     albertel 3351: "first middle last generation" form 
                   3352: if $first is set to 'lastname' then it returns it as
                   3353: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3354: 
                   3355: =cut
1.61      www      3356: 
1.295     www      3357: 
1.81      albertel 3358: ###############################################################
1.61      www      3359: sub plainname {
1.226     albertel 3360:     my ($uname,$udom,$first)=@_;
1.537     albertel 3361:     return if (!defined($uname) || !defined($udom));
1.295     www      3362:     my %names=&getnames($uname,$udom);
1.226     albertel 3363:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3364: 					  $names{'middlename'},
                   3365: 					  $names{'lastname'},
                   3366: 					  $names{'generation'},$first);
                   3367:     $name=~s/^\s+//;
1.62      www      3368:     $name=~s/\s+$//;
                   3369:     $name=~s/\s+/ /g;
1.353     albertel 3370:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3371:     return $name;
1.61      www      3372: }
1.66      www      3373: 
                   3374: # -------------------------------------------------------------------- Nickname
1.81      albertel 3375: =pod
                   3376: 
1.648     raeburn  3377: =item * &nickname($uname,$udom)
1.81      albertel 3378: 
                   3379: Gets a users name and returns it as a string as
                   3380: 
                   3381: "&quot;nickname&quot;"
1.66      www      3382: 
1.81      albertel 3383: if the user has a nickname or
                   3384: 
                   3385: "first middle last generation"
                   3386: 
                   3387: if the user does not
                   3388: 
                   3389: =cut
1.66      www      3390: 
                   3391: sub nickname {
                   3392:     my ($uname,$udom)=@_;
1.537     albertel 3393:     return if (!defined($uname) || !defined($udom));
1.295     www      3394:     my %names=&getnames($uname,$udom);
1.68      albertel 3395:     my $name=$names{'nickname'};
1.66      www      3396:     if ($name) {
                   3397:        $name='&quot;'.$name.'&quot;'; 
                   3398:     } else {
                   3399:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3400: 	     $names{'lastname'}.' '.$names{'generation'};
                   3401:        $name=~s/\s+$//;
                   3402:        $name=~s/\s+/ /g;
                   3403:     }
                   3404:     return $name;
                   3405: }
                   3406: 
1.295     www      3407: sub getnames {
                   3408:     my ($uname,$udom)=@_;
1.537     albertel 3409:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3410:     if ($udom eq 'public' && $uname eq 'public') {
                   3411: 	return ('lastname' => &mt('Public'));
                   3412:     }
1.295     www      3413:     my $id=$uname.':'.$udom;
                   3414:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3415:     if ($cached) {
                   3416: 	return %{$names};
                   3417:     } else {
                   3418: 	my %loadnames=&Apache::lonnet::get('environment',
                   3419:                     ['firstname','middlename','lastname','generation','nickname'],
                   3420: 					 $udom,$uname);
                   3421: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3422: 	return %loadnames;
                   3423:     }
                   3424: }
1.61      www      3425: 
1.542     raeburn  3426: # -------------------------------------------------------------------- getemails
1.648     raeburn  3427: 
1.542     raeburn  3428: =pod
                   3429: 
1.648     raeburn  3430: =item * &getemails($uname,$udom)
1.542     raeburn  3431: 
                   3432: Gets a user's email information and returns it as a hash with keys:
                   3433: notification, critnotification, permanentemail
                   3434: 
                   3435: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3436: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3437:  
1.648     raeburn  3438: 
1.542     raeburn  3439: =cut
                   3440: 
1.648     raeburn  3441: 
1.466     albertel 3442: sub getemails {
                   3443:     my ($uname,$udom)=@_;
                   3444:     if ($udom eq 'public' && $uname eq 'public') {
                   3445: 	return;
                   3446:     }
1.467     www      3447:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3448:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3449:     my $id=$uname.':'.$udom;
                   3450:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3451:     if ($cached) {
                   3452: 	return %{$names};
                   3453:     } else {
                   3454: 	my %loadnames=&Apache::lonnet::get('environment',
                   3455:                     			   ['notification','critnotification',
                   3456: 					    'permanentemail'],
                   3457: 					   $udom,$uname);
                   3458: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3459: 	return %loadnames;
                   3460:     }
                   3461: }
                   3462: 
1.551     albertel 3463: sub flush_email_cache {
                   3464:     my ($uname,$udom)=@_;
                   3465:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3466:     if (!$uname) { $uname=$env{'user.name'};   }
                   3467:     return if ($udom eq 'public' && $uname eq 'public');
                   3468:     my $id=$uname.':'.$udom;
                   3469:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3470: }
                   3471: 
1.728     raeburn  3472: # -------------------------------------------------------------------- getlangs
                   3473: 
                   3474: =pod
                   3475: 
                   3476: =item * &getlangs($uname,$udom)
                   3477: 
                   3478: Gets a user's language preference and returns it as a hash with key:
                   3479: language.
                   3480: 
                   3481: =cut
                   3482: 
                   3483: 
                   3484: sub getlangs {
                   3485:     my ($uname,$udom) = @_;
                   3486:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3487:     if (!$uname) { $uname=$env{'user.name'};   }
                   3488:     my $id=$uname.':'.$udom;
                   3489:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3490:     if ($cached) {
                   3491:         return %{$langs};
                   3492:     } else {
                   3493:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3494:                                            $udom,$uname);
                   3495:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3496:         return %loadlangs;
                   3497:     }
                   3498: }
                   3499: 
                   3500: sub flush_langs_cache {
                   3501:     my ($uname,$udom)=@_;
                   3502:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3503:     if (!$uname) { $uname=$env{'user.name'};   }
                   3504:     return if ($udom eq 'public' && $uname eq 'public');
                   3505:     my $id=$uname.':'.$udom;
                   3506:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3507: }
                   3508: 
1.61      www      3509: # ------------------------------------------------------------------ Screenname
1.81      albertel 3510: 
                   3511: =pod
                   3512: 
1.648     raeburn  3513: =item * &screenname($uname,$udom)
1.81      albertel 3514: 
                   3515: Gets a users screenname and returns it as a string
                   3516: 
                   3517: =cut
1.61      www      3518: 
                   3519: sub screenname {
                   3520:     my ($uname,$udom)=@_;
1.258     albertel 3521:     if ($uname eq $env{'user.name'} &&
                   3522: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3523:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3524:     return $names{'screenname'};
1.62      www      3525: }
                   3526: 
1.212     albertel 3527: 
1.802     bisitz   3528: # ------------------------------------------------------------- Confirm Wrapper
                   3529: =pod
                   3530: 
1.1075.2.42  raeburn  3531: =item * &confirmwrapper($message)
1.802     bisitz   3532: 
                   3533: Wrap messages about completion of operation in box
                   3534: 
                   3535: =cut
                   3536: 
                   3537: sub confirmwrapper {
                   3538:     my ($message)=@_;
                   3539:     if ($message) {
                   3540:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3541:                .$message."\n"
                   3542:                .'</div>'."\n";
                   3543:     } else {
                   3544:         return $message;
                   3545:     }
                   3546: }
                   3547: 
1.62      www      3548: # ------------------------------------------------------------- Message Wrapper
                   3549: 
                   3550: sub messagewrapper {
1.369     www      3551:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3552:     return 
1.441     albertel 3553:         '<a href="/adm/email?compose=individual&amp;'.
                   3554:         'recname='.$username.'&amp;recdom='.$domain.
                   3555: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3556:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3557: }
1.802     bisitz   3558: 
1.74      www      3559: # --------------------------------------------------------------- Notes Wrapper
                   3560: 
                   3561: sub noteswrapper {
                   3562:     my ($link,$un,$do)=@_;
                   3563:     return 
1.896     amueller 3564: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3565: }
1.802     bisitz   3566: 
1.62      www      3567: # ------------------------------------------------------------- Aboutme Wrapper
                   3568: 
                   3569: sub aboutmewrapper {
1.1070    raeburn  3570:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3571:     if (!defined($username)  && !defined($domain)) {
                   3572:         return;
                   3573:     }
1.1075.2.15  raeburn  3574:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3575: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3576: }
                   3577: 
                   3578: # ------------------------------------------------------------ Syllabus Wrapper
                   3579: 
                   3580: sub syllabuswrapper {
1.707     bisitz   3581:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3582:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3583: }
1.14      harris41 3584: 
1.802     bisitz   3585: # -----------------------------------------------------------------------------
                   3586: 
1.208     matthew  3587: sub track_student_link {
1.887     raeburn  3588:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3589:     my $link ="/adm/trackstudent?";
1.208     matthew  3590:     my $title = 'View recent activity';
                   3591:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3592:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3593:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3594:         $title .= ' of this student';
1.268     albertel 3595:     } 
1.208     matthew  3596:     if (defined($target) && $target !~ /^\s*$/) {
                   3597:         $target = qq{target="$target"};
                   3598:     } else {
                   3599:         $target = '';
                   3600:     }
1.268     albertel 3601:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3602:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3603:     $title = &mt($title);
                   3604:     $linktext = &mt($linktext);
1.448     albertel 3605:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3606: 	&help_open_topic('View_recent_activity');
1.208     matthew  3607: }
                   3608: 
1.781     raeburn  3609: sub slot_reservations_link {
                   3610:     my ($linktext,$sname,$sdom,$target) = @_;
                   3611:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3612:     my $title = 'View slot reservation history';
                   3613:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3614:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3615:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3616:         $title .= ' of this student';
                   3617:     }
                   3618:     if (defined($target) && $target !~ /^\s*$/) {
                   3619:         $target = qq{target="$target"};
                   3620:     } else {
                   3621:         $target = '';
                   3622:     }
                   3623:     $title = &mt($title);
                   3624:     $linktext = &mt($linktext);
                   3625:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3626: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3627: 
                   3628: }
                   3629: 
1.508     www      3630: # ===================================================== Display a student photo
                   3631: 
                   3632: 
1.509     albertel 3633: sub student_image_tag {
1.508     www      3634:     my ($domain,$user)=@_;
                   3635:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3636:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3637: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3638:     } else {
                   3639: 	return '';
                   3640:     }
                   3641: }
                   3642: 
1.112     bowersj2 3643: =pod
                   3644: 
                   3645: =back
                   3646: 
                   3647: =head1 Access .tab File Data
                   3648: 
                   3649: =over 4
                   3650: 
1.648     raeburn  3651: =item * &languageids() 
1.112     bowersj2 3652: 
                   3653: returns list of all language ids
                   3654: 
                   3655: =cut
                   3656: 
1.14      harris41 3657: sub languageids {
1.16      harris41 3658:     return sort(keys(%language));
1.14      harris41 3659: }
                   3660: 
1.112     bowersj2 3661: =pod
                   3662: 
1.648     raeburn  3663: =item * &languagedescription() 
1.112     bowersj2 3664: 
                   3665: returns description of a specified language id
                   3666: 
                   3667: =cut
                   3668: 
1.14      harris41 3669: sub languagedescription {
1.125     www      3670:     my $code=shift;
                   3671:     return  ($supported_language{$code}?'* ':'').
                   3672:             $language{$code}.
1.126     www      3673: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3674: }
                   3675: 
1.1048    foxr     3676: =pod
                   3677: 
                   3678: =item * &plainlanguagedescription
                   3679: 
                   3680: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3681: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3682: 
                   3683: =cut
                   3684: 
1.145     www      3685: sub plainlanguagedescription {
                   3686:     my $code=shift;
                   3687:     return $language{$code};
                   3688: }
                   3689: 
1.1048    foxr     3690: =pod
                   3691: 
                   3692: =item * &supportedlanguagecode
                   3693: 
                   3694: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3695: code.
                   3696: 
                   3697: =cut
                   3698: 
1.145     www      3699: sub supportedlanguagecode {
                   3700:     my $code=shift;
                   3701:     return $supported_language{$code};
1.97      www      3702: }
                   3703: 
1.112     bowersj2 3704: =pod
                   3705: 
1.1048    foxr     3706: =item * &latexlanguage()
                   3707: 
                   3708: Given a language key code returns the correspondnig language to use
                   3709: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3710: is no supported hyphenation for the language code.
                   3711: 
                   3712: =cut
                   3713: 
                   3714: sub latexlanguage {
                   3715:     my $code = shift;
                   3716:     return $latex_language{$code};
                   3717: }
                   3718: 
                   3719: =pod
                   3720: 
                   3721: =item * &latexhyphenation()
                   3722: 
                   3723: Same as above but what's supplied is the language as it might be stored
                   3724: in the metadata.
                   3725: 
                   3726: =cut
                   3727: 
                   3728: sub latexhyphenation {
                   3729:     my $key = shift;
                   3730:     return $latex_language_bykey{$key};
                   3731: }
                   3732: 
                   3733: =pod
                   3734: 
1.648     raeburn  3735: =item * &copyrightids() 
1.112     bowersj2 3736: 
                   3737: returns list of all copyrights
                   3738: 
                   3739: =cut
                   3740: 
                   3741: sub copyrightids {
                   3742:     return sort(keys(%cprtag));
                   3743: }
                   3744: 
                   3745: =pod
                   3746: 
1.648     raeburn  3747: =item * &copyrightdescription() 
1.112     bowersj2 3748: 
                   3749: returns description of a specified copyright id
                   3750: 
                   3751: =cut
                   3752: 
                   3753: sub copyrightdescription {
1.166     www      3754:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3755: }
1.197     matthew  3756: 
                   3757: =pod
                   3758: 
1.648     raeburn  3759: =item * &source_copyrightids() 
1.192     taceyjo1 3760: 
                   3761: returns list of all source copyrights
                   3762: 
                   3763: =cut
                   3764: 
                   3765: sub source_copyrightids {
                   3766:     return sort(keys(%scprtag));
                   3767: }
                   3768: 
                   3769: =pod
                   3770: 
1.648     raeburn  3771: =item * &source_copyrightdescription() 
1.192     taceyjo1 3772: 
                   3773: returns description of a specified source copyright id
                   3774: 
                   3775: =cut
                   3776: 
                   3777: sub source_copyrightdescription {
                   3778:     return &mt($scprtag{shift(@_)});
                   3779: }
1.112     bowersj2 3780: 
                   3781: =pod
                   3782: 
1.648     raeburn  3783: =item * &filecategories() 
1.112     bowersj2 3784: 
                   3785: returns list of all file categories
                   3786: 
                   3787: =cut
                   3788: 
                   3789: sub filecategories {
                   3790:     return sort(keys(%category_extensions));
                   3791: }
                   3792: 
                   3793: =pod
                   3794: 
1.648     raeburn  3795: =item * &filecategorytypes() 
1.112     bowersj2 3796: 
                   3797: returns list of file types belonging to a given file
                   3798: category
                   3799: 
                   3800: =cut
                   3801: 
                   3802: sub filecategorytypes {
1.356     albertel 3803:     my ($cat) = @_;
                   3804:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3805: }
                   3806: 
                   3807: =pod
                   3808: 
1.648     raeburn  3809: =item * &fileembstyle() 
1.112     bowersj2 3810: 
                   3811: returns embedding style for a specified file type
                   3812: 
                   3813: =cut
                   3814: 
                   3815: sub fileembstyle {
                   3816:     return $fe{lc(shift(@_))};
1.169     www      3817: }
                   3818: 
1.351     www      3819: sub filemimetype {
                   3820:     return $fm{lc(shift(@_))};
                   3821: }
                   3822: 
1.169     www      3823: 
                   3824: sub filecategoryselect {
                   3825:     my ($name,$value)=@_;
1.189     matthew  3826:     return &select_form($value,$name,
1.970     raeburn  3827:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3828: }
                   3829: 
                   3830: =pod
                   3831: 
1.648     raeburn  3832: =item * &filedescription() 
1.112     bowersj2 3833: 
                   3834: returns description for a specified file type
                   3835: 
                   3836: =cut
                   3837: 
                   3838: sub filedescription {
1.188     matthew  3839:     my $file_description = $fd{lc(shift())};
                   3840:     $file_description =~ s:([\[\]]):~$1:g;
                   3841:     return &mt($file_description);
1.112     bowersj2 3842: }
                   3843: 
                   3844: =pod
                   3845: 
1.648     raeburn  3846: =item * &filedescriptionex() 
1.112     bowersj2 3847: 
                   3848: returns description for a specified file type with
                   3849: extra formatting
                   3850: 
                   3851: =cut
                   3852: 
                   3853: sub filedescriptionex {
                   3854:     my $ex=shift;
1.188     matthew  3855:     my $file_description = $fd{lc($ex)};
                   3856:     $file_description =~ s:([\[\]]):~$1:g;
                   3857:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3858: }
                   3859: 
                   3860: # End of .tab access
                   3861: =pod
                   3862: 
                   3863: =back
                   3864: 
                   3865: =cut
                   3866: 
                   3867: # ------------------------------------------------------------------ File Types
                   3868: sub fileextensions {
                   3869:     return sort(keys(%fe));
                   3870: }
                   3871: 
1.97      www      3872: # ----------------------------------------------------------- Display Languages
                   3873: # returns a hash with all desired display languages
                   3874: #
                   3875: 
                   3876: sub display_languages {
                   3877:     my %languages=();
1.695     raeburn  3878:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3879: 	$languages{$lang}=1;
1.97      www      3880:     }
                   3881:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3882:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3883: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3884: 	    $languages{$lang}=1;
1.97      www      3885:         }
                   3886:     }
                   3887:     return %languages;
1.14      harris41 3888: }
                   3889: 
1.582     albertel 3890: sub languages {
                   3891:     my ($possible_langs) = @_;
1.695     raeburn  3892:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3893:     if (!ref($possible_langs)) {
                   3894: 	if( wantarray ) {
                   3895: 	    return @preferred_langs;
                   3896: 	} else {
                   3897: 	    return $preferred_langs[0];
                   3898: 	}
                   3899:     }
                   3900:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3901:     my @preferred_possibilities;
                   3902:     foreach my $preferred_lang (@preferred_langs) {
                   3903: 	if (exists($possibilities{$preferred_lang})) {
                   3904: 	    push(@preferred_possibilities, $preferred_lang);
                   3905: 	}
                   3906:     }
                   3907:     if( wantarray ) {
                   3908: 	return @preferred_possibilities;
                   3909:     }
                   3910:     return $preferred_possibilities[0];
                   3911: }
                   3912: 
1.742     raeburn  3913: sub user_lang {
                   3914:     my ($touname,$toudom,$fromcid) = @_;
                   3915:     my @userlangs;
                   3916:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3917:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3918:                     $env{'course.'.$fromcid.'.languages'}));
                   3919:     } else {
                   3920:         my %langhash = &getlangs($touname,$toudom);
                   3921:         if ($langhash{'languages'} ne '') {
                   3922:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3923:         } else {
                   3924:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3925:             if ($domdefs{'lang_def'} ne '') {
                   3926:                 @userlangs = ($domdefs{'lang_def'});
                   3927:             }
                   3928:         }
                   3929:     }
                   3930:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3931:     my $user_lh = Apache::localize->get_handle(@languages);
                   3932:     return $user_lh;
                   3933: }
                   3934: 
                   3935: 
1.112     bowersj2 3936: ###############################################################
                   3937: ##               Student Answer Attempts                     ##
                   3938: ###############################################################
                   3939: 
                   3940: =pod
                   3941: 
                   3942: =head1 Alternate Problem Views
                   3943: 
                   3944: =over 4
                   3945: 
1.648     raeburn  3946: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  3947:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 3948: 
                   3949: Return string with previous attempt on problem. Arguments:
                   3950: 
                   3951: =over 4
                   3952: 
                   3953: =item * $symb: Problem, including path
                   3954: 
                   3955: =item * $username: username of the desired student
                   3956: 
                   3957: =item * $domain: domain of the desired student
1.14      harris41 3958: 
1.112     bowersj2 3959: =item * $course: Course ID
1.14      harris41 3960: 
1.112     bowersj2 3961: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3962:     something
1.14      harris41 3963: 
1.112     bowersj2 3964: =item * $regexp: if string matches this regexp, the string will be
                   3965:     sent to $gradesub
1.14      harris41 3966: 
1.112     bowersj2 3967: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3968: 
1.1075.2.86  raeburn  3969: =item * $usec: section of the desired student
                   3970: 
                   3971: =item * $identifier: counter for student (multiple students one problem) or
                   3972:     problem (one student; whole sequence).
                   3973: 
1.112     bowersj2 3974: =back
1.14      harris41 3975: 
1.112     bowersj2 3976: The output string is a table containing all desired attempts, if any.
1.16      harris41 3977: 
1.112     bowersj2 3978: =cut
1.1       albertel 3979: 
                   3980: sub get_previous_attempt {
1.1075.2.86  raeburn  3981:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 3982:   my $prevattempts='';
1.43      ng       3983:   no strict 'refs';
1.1       albertel 3984:   if ($symb) {
1.3       albertel 3985:     my (%returnhash)=
                   3986:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3987:     if ($returnhash{'version'}) {
                   3988:       my %lasthash=();
                   3989:       my $version;
                   3990:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  3991:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   3992:             if ($key =~ /\.rawrndseed$/) {
                   3993:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   3994:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   3995:             } else {
                   3996:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   3997:             }
1.19      harris41 3998:         }
1.1       albertel 3999:       }
1.596     albertel 4000:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4001:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4002:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4003:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4004:       foreach my $key (sort(keys(%lasthash))) {
                   4005: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4006: 	if ($#parts > 0) {
1.31      albertel 4007: 	  my $data=$parts[-1];
1.989     raeburn  4008:           next if ($data eq 'foilorder');
1.31      albertel 4009: 	  pop(@parts);
1.1010    www      4010:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4011:           if ($data eq 'type') {
                   4012:               unless ($showsurv) {
                   4013:                   my $id = join(',',@parts);
                   4014:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4015:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4016:                       $lasthidden{$ign.'.'.$id} = 1;
                   4017:                   }
1.945     raeburn  4018:               }
1.1075.2.86  raeburn  4019:               if ($identifier ne '') {
                   4020:                   my $id = join(',',@parts);
                   4021:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4022:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4023:                       $hidestatus{$ign.'.'.$id} = 1;
                   4024:                   }
                   4025:               }
                   4026:           } elsif ($data eq 'regrader') {
                   4027:               if (($identifier ne '') && (@parts)) {
                   4028:                   my $id = join(',',@parts);
                   4029:                   $regraded{$ign.'.'.$id} = 1;
                   4030:               }
1.1010    www      4031:           } 
1.31      albertel 4032: 	} else {
1.41      ng       4033: 	  if ($#parts == 0) {
                   4034: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4035: 	  } else {
                   4036: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4037: 	  }
1.31      albertel 4038: 	}
1.16      harris41 4039:       }
1.596     albertel 4040:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4041:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4042:         my (%solved,%resets,%probstatus);
                   4043:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4044:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4045:                 foreach my $id (keys(%regraded)) {
                   4046:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4047:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4048:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4049:                         push(@{$resets{$id}},$version);
                   4050:                     }
                   4051:                 }
                   4052:             }
                   4053:         }
1.40      ng       4054: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4055:             my (@hidden,@unsolved);
1.945     raeburn  4056:             if (%typeparts) {
                   4057:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4058:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4059:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4060:                         push(@hidden,$id);
1.1075.2.86  raeburn  4061:                     } elsif ($identifier ne '') {
                   4062:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4063:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4064:                                 ($hidestatus{$id})) {
                   4065:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4066:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4067:                                 push(@{$solved{$id}},$version);
                   4068:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4069:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4070:                                 my $skip;
                   4071:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4072:                                     foreach my $reset (@{$resets{$id}}) {
                   4073:                                         if ($reset > $solved{$id}[-1]) {
                   4074:                                             $skip=1;
                   4075:                                             last;
                   4076:                                         }
                   4077:                                     }
                   4078:                                 }
                   4079:                                 unless ($skip) {
                   4080:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4081:                                     push(@unsolved,$partslist);
                   4082:                                 }
                   4083:                             }
                   4084:                         }
1.945     raeburn  4085:                     }
                   4086:                 }
                   4087:             }
                   4088:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4089:                            '<td>'.&mt('Transaction [_1]',$version);
                   4090:             if (@unsolved) {
                   4091:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4092:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4093:                                  &mt('Hide').'</label></span>';
                   4094:             }
                   4095:             $prevattempts .= '</td>';
1.945     raeburn  4096:             if (@hidden) {
                   4097:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4098:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4099:                     my $hide;
                   4100:                     foreach my $id (@hidden) {
                   4101:                         if ($key =~ /^\Q$id\E/) {
                   4102:                             $hide = 1;
                   4103:                             last;
                   4104:                         }
                   4105:                     }
                   4106:                     if ($hide) {
                   4107:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4108:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4109:                             my $value = &format_previous_attempt_value($key,
                   4110:                                              $returnhash{$version.':'.$key});
                   4111:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4112:                         } else {
                   4113:                             $prevattempts.='<td>&nbsp;</td>';
                   4114:                         }
                   4115:                     } else {
                   4116:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4117:                             my $value = $returnhash{$version.':'.$key};
                   4118:                             if ($key =~ /\.rndseed$/) {
                   4119:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4120:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4121:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4122:                                 }
                   4123:                             }
                   4124:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4125:                                            '&nbsp;</td>';
1.945     raeburn  4126:                         } else {
                   4127:                             $prevattempts.='<td>&nbsp;</td>';
                   4128:                         }
                   4129:                     }
                   4130:                 }
                   4131:             } else {
                   4132: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4133:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4134:                     my $value = $returnhash{$version.':'.$key};
                   4135:                     if ($key =~ /\.rndseed$/) {
                   4136:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4137:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4138:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4139:                         }
                   4140:                     }
                   4141:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4142:                                    '&nbsp;</td>';
1.945     raeburn  4143: 	        }
                   4144:             }
                   4145: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4146: 	 }
1.1       albertel 4147:       }
1.945     raeburn  4148:       my @currhidden = keys(%lasthidden);
1.596     albertel 4149:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4150:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4151:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4152:           if (%typeparts) {
                   4153:               my $hidden;
                   4154:               foreach my $id (@currhidden) {
                   4155:                   if ($key =~ /^\Q$id\E/) {
                   4156:                       $hidden = 1;
                   4157:                       last;
                   4158:                   }
                   4159:               }
                   4160:               if ($hidden) {
                   4161:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4162:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4163:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4164:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4165:                           $value = &$gradesub($value);
                   4166:                       }
                   4167:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4168:                   } else {
                   4169:                       $prevattempts.='<td>&nbsp;</td>';
                   4170:                   }
                   4171:               } else {
                   4172:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4173:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4174:                       $value = &$gradesub($value);
                   4175:                   }
                   4176:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4177:               }
                   4178:           } else {
                   4179: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4180: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4181:                   $value = &$gradesub($value);
                   4182:               }
                   4183: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4184:           }
1.16      harris41 4185:       }
1.596     albertel 4186:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4187:     } else {
1.596     albertel 4188:       $prevattempts=
                   4189: 	  &start_data_table().&start_data_table_row().
                   4190: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4191: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4192:     }
                   4193:   } else {
1.596     albertel 4194:     $prevattempts=
                   4195: 	  &start_data_table().&start_data_table_row().
                   4196: 	  '<td>'.&mt('No data.').'</td>'.
                   4197: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4198:   }
1.10      albertel 4199: }
                   4200: 
1.581     albertel 4201: sub format_previous_attempt_value {
                   4202:     my ($key,$value) = @_;
1.1011    www      4203:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4204: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4205:     } elsif (ref($value) eq 'ARRAY') {
                   4206: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4207:     } elsif ($key =~ /answerstring$/) {
                   4208:         my %answers = &Apache::lonnet::str2hash($value);
                   4209:         my @anskeys = sort(keys(%answers));
                   4210:         if (@anskeys == 1) {
                   4211:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4212:             if ($answer =~ m{\0}) {
                   4213:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4214:             }
                   4215:             my $tag_internal_answer_name = 'INTERNAL';
                   4216:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4217:                 $value = $answer; 
                   4218:             } else {
                   4219:                 $value = $anskeys[0].'='.$answer;
                   4220:             }
                   4221:         } else {
                   4222:             foreach my $ans (@anskeys) {
                   4223:                 my $answer = $answers{$ans};
1.1001    raeburn  4224:                 if ($answer =~ m{\0}) {
                   4225:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4226:                 }
                   4227:                 $value .=  $ans.'='.$answer.'<br />';;
                   4228:             } 
                   4229:         }
1.581     albertel 4230:     } else {
                   4231: 	$value = &unescape($value);
                   4232:     }
                   4233:     return $value;
                   4234: }
                   4235: 
                   4236: 
1.107     albertel 4237: sub relative_to_absolute {
                   4238:     my ($url,$output)=@_;
                   4239:     my $parser=HTML::TokeParser->new(\$output);
                   4240:     my $token;
                   4241:     my $thisdir=$url;
                   4242:     my @rlinks=();
                   4243:     while ($token=$parser->get_token) {
                   4244: 	if ($token->[0] eq 'S') {
                   4245: 	    if ($token->[1] eq 'a') {
                   4246: 		if ($token->[2]->{'href'}) {
                   4247: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4248: 		}
                   4249: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4250: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4251: 	    } elsif ($token->[1] eq 'base') {
                   4252: 		$thisdir=$token->[2]->{'href'};
                   4253: 	    }
                   4254: 	}
                   4255:     }
                   4256:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4257:     foreach my $link (@rlinks) {
1.726     raeburn  4258: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4259: 		($link=~/^\//) ||
                   4260: 		($link=~/^javascript:/i) ||
                   4261: 		($link=~/^mailto:/i) ||
                   4262: 		($link=~/^\#/)) {
                   4263: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4264: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4265: 	}
                   4266:     }
                   4267: # -------------------------------------------------- Deal with Applet codebases
                   4268:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4269:     return $output;
                   4270: }
                   4271: 
1.112     bowersj2 4272: =pod
                   4273: 
1.648     raeburn  4274: =item * &get_student_view()
1.112     bowersj2 4275: 
                   4276: show a snapshot of what student was looking at
                   4277: 
                   4278: =cut
                   4279: 
1.10      albertel 4280: sub get_student_view {
1.186     albertel 4281:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4282:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4283:   my (%form);
1.10      albertel 4284:   my @elements=('symb','courseid','domain','username');
                   4285:   foreach my $element (@elements) {
1.186     albertel 4286:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4287:   }
1.186     albertel 4288:   if (defined($moreenv)) {
                   4289:       %form=(%form,%{$moreenv});
                   4290:   }
1.236     albertel 4291:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4292:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4293:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4294:   $userview=~s/\<body[^\>]*\>//gi;
                   4295:   $userview=~s/\<\/body\>//gi;
                   4296:   $userview=~s/\<html\>//gi;
                   4297:   $userview=~s/\<\/html\>//gi;
                   4298:   $userview=~s/\<head\>//gi;
                   4299:   $userview=~s/\<\/head\>//gi;
                   4300:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4301:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4302:   if (wantarray) {
                   4303:      return ($userview,$response);
                   4304:   } else {
                   4305:      return $userview;
                   4306:   }
                   4307: }
                   4308: 
                   4309: sub get_student_view_with_retries {
                   4310:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4311: 
                   4312:     my $ok = 0;                 # True if we got a good response.
                   4313:     my $content;
                   4314:     my $response;
                   4315: 
                   4316:     # Try to get the student_view done. within the retries count:
                   4317:     
                   4318:     do {
                   4319:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4320:          $ok      = $response->is_success;
                   4321:          if (!$ok) {
                   4322:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4323:          }
                   4324:          $retries--;
                   4325:     } while (!$ok && ($retries > 0));
                   4326:     
                   4327:     if (!$ok) {
                   4328:        $content = '';          # On error return an empty content.
                   4329:     }
1.651     www      4330:     if (wantarray) {
                   4331:        return ($content, $response);
                   4332:     } else {
                   4333:        return $content;
                   4334:     }
1.11      albertel 4335: }
                   4336: 
1.112     bowersj2 4337: =pod
                   4338: 
1.648     raeburn  4339: =item * &get_student_answers() 
1.112     bowersj2 4340: 
                   4341: show a snapshot of how student was answering problem
                   4342: 
                   4343: =cut
                   4344: 
1.11      albertel 4345: sub get_student_answers {
1.100     sakharuk 4346:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4347:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4348:   my (%moreenv);
1.11      albertel 4349:   my @elements=('symb','courseid','domain','username');
                   4350:   foreach my $element (@elements) {
1.186     albertel 4351:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4352:   }
1.186     albertel 4353:   $moreenv{'grade_target'}='answer';
                   4354:   %moreenv=(%form,%moreenv);
1.497     raeburn  4355:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4356:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4357:   return $userview;
1.1       albertel 4358: }
1.116     albertel 4359: 
                   4360: =pod
                   4361: 
                   4362: =item * &submlink()
                   4363: 
1.242     albertel 4364: Inputs: $text $uname $udom $symb $target
1.116     albertel 4365: 
                   4366: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4367: 
                   4368: =cut
                   4369: 
                   4370: ###############################################
                   4371: sub submlink {
1.242     albertel 4372:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4373:     if (!($uname && $udom)) {
                   4374: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4375: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4376: 	if (!$symb) { $symb=$cursymb; }
                   4377:     }
1.254     matthew  4378:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4379:     $symb=&escape($symb);
1.960     bisitz   4380:     if ($target) { $target=" target=\"$target\""; }
                   4381:     return
                   4382:         '<a href="/adm/grades?command=submission'.
                   4383:         '&amp;symb='.$symb.
                   4384:         '&amp;student='.$uname.
                   4385:         '&amp;userdom='.$udom.'"'.
                   4386:         $target.'>'.$text.'</a>';
1.242     albertel 4387: }
                   4388: ##############################################
                   4389: 
                   4390: =pod
                   4391: 
                   4392: =item * &pgrdlink()
                   4393: 
                   4394: Inputs: $text $uname $udom $symb $target
                   4395: 
                   4396: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4397: 
                   4398: =cut
                   4399: 
                   4400: ###############################################
                   4401: sub pgrdlink {
                   4402:     my $link=&submlink(@_);
                   4403:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4404:     return $link;
                   4405: }
                   4406: ##############################################
                   4407: 
                   4408: =pod
                   4409: 
                   4410: =item * &pprmlink()
                   4411: 
                   4412: Inputs: $text $uname $udom $symb $target
                   4413: 
                   4414: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4415: student and a specific resource
1.242     albertel 4416: 
                   4417: =cut
                   4418: 
                   4419: ###############################################
                   4420: sub pprmlink {
                   4421:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4422:     if (!($uname && $udom)) {
                   4423: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4424: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4425: 	if (!$symb) { $symb=$cursymb; }
                   4426:     }
1.254     matthew  4427:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4428:     $symb=&escape($symb);
1.242     albertel 4429:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4430:     return '<a href="/adm/parmset?command=set&amp;'.
                   4431: 	'symb='.$symb.'&amp;uname='.$uname.
                   4432: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4433: }
                   4434: ##############################################
1.37      matthew  4435: 
1.112     bowersj2 4436: =pod
                   4437: 
                   4438: =back
                   4439: 
                   4440: =cut
                   4441: 
1.37      matthew  4442: ###############################################
1.51      www      4443: 
                   4444: 
                   4445: sub timehash {
1.687     raeburn  4446:     my ($thistime) = @_;
                   4447:     my $timezone = &Apache::lonlocal::gettimezone();
                   4448:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4449:                      ->set_time_zone($timezone);
                   4450:     my $wday = $dt->day_of_week();
                   4451:     if ($wday == 7) { $wday = 0; }
                   4452:     return ( 'second' => $dt->second(),
                   4453:              'minute' => $dt->minute(),
                   4454:              'hour'   => $dt->hour(),
                   4455:              'day'     => $dt->day_of_month(),
                   4456:              'month'   => $dt->month(),
                   4457:              'year'    => $dt->year(),
                   4458:              'weekday' => $wday,
                   4459:              'dayyear' => $dt->day_of_year(),
                   4460:              'dlsav'   => $dt->is_dst() );
1.51      www      4461: }
                   4462: 
1.370     www      4463: sub utc_string {
                   4464:     my ($date)=@_;
1.371     www      4465:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4466: }
                   4467: 
1.51      www      4468: sub maketime {
                   4469:     my %th=@_;
1.687     raeburn  4470:     my ($epoch_time,$timezone,$dt);
                   4471:     $timezone = &Apache::lonlocal::gettimezone();
                   4472:     eval {
                   4473:         $dt = DateTime->new( year   => $th{'year'},
                   4474:                              month  => $th{'month'},
                   4475:                              day    => $th{'day'},
                   4476:                              hour   => $th{'hour'},
                   4477:                              minute => $th{'minute'},
                   4478:                              second => $th{'second'},
                   4479:                              time_zone => $timezone,
                   4480:                          );
                   4481:     };
                   4482:     if (!$@) {
                   4483:         $epoch_time = $dt->epoch;
                   4484:         if ($epoch_time) {
                   4485:             return $epoch_time;
                   4486:         }
                   4487:     }
1.51      www      4488:     return POSIX::mktime(
                   4489:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4490:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4491: }
                   4492: 
                   4493: #########################################
1.51      www      4494: 
                   4495: sub findallcourses {
1.482     raeburn  4496:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4497:     my %roles;
                   4498:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4499:     my %courses;
1.51      www      4500:     my $now=time;
1.482     raeburn  4501:     if (!defined($uname)) {
                   4502:         $uname = $env{'user.name'};
                   4503:     }
                   4504:     if (!defined($udom)) {
                   4505:         $udom = $env{'user.domain'};
                   4506:     }
                   4507:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4508:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4509:         if (!%roles) {
                   4510:             %roles = (
                   4511:                        cc => 1,
1.907     raeburn  4512:                        co => 1,
1.482     raeburn  4513:                        in => 1,
                   4514:                        ep => 1,
                   4515:                        ta => 1,
                   4516:                        cr => 1,
                   4517:                        st => 1,
                   4518:              );
                   4519:         }
                   4520:         foreach my $entry (keys(%roleshash)) {
                   4521:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4522:             if ($trole =~ /^cr/) { 
                   4523:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4524:             } else {
                   4525:                 next if (!exists($roles{$trole}));
                   4526:             }
                   4527:             if ($tend) {
                   4528:                 next if ($tend < $now);
                   4529:             }
                   4530:             if ($tstart) {
                   4531:                 next if ($tstart > $now);
                   4532:             }
1.1058    raeburn  4533:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4534:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4535:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4536:             if ($secpart eq '') {
                   4537:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4538:                 $sec = 'none';
1.1058    raeburn  4539:                 $value .= $cnum.'/';
1.482     raeburn  4540:             } else {
                   4541:                 $cnum = $cnumpart;
                   4542:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4543:                 $value .= $cnum.'/'.$sec;
                   4544:             }
                   4545:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4546:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4547:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4548:                 }
                   4549:             } else {
                   4550:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4551:             }
1.482     raeburn  4552:         }
                   4553:     } else {
                   4554:         foreach my $key (keys(%env)) {
1.483     albertel 4555: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4556:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4557: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4558: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4559: 	        next if (%roles && !exists($roles{$role}));
                   4560: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4561:                 my $active=1;
                   4562:                 if ($starttime) {
                   4563: 		    if ($now<$starttime) { $active=0; }
                   4564:                 }
                   4565:                 if ($endtime) {
                   4566:                     if ($now>$endtime) { $active=0; }
                   4567:                 }
                   4568:                 if ($active) {
1.1058    raeburn  4569:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4570:                     if ($sec eq '') {
                   4571:                         $sec = 'none';
1.1058    raeburn  4572:                     } else {
                   4573:                         $value .= $sec;
                   4574:                     }
                   4575:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4576:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4577:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4578:                         }
                   4579:                     } else {
                   4580:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4581:                     }
1.474     raeburn  4582:                 }
                   4583:             }
1.51      www      4584:         }
                   4585:     }
1.474     raeburn  4586:     return %courses;
1.51      www      4587: }
1.37      matthew  4588: 
1.54      www      4589: ###############################################
1.474     raeburn  4590: 
                   4591: sub blockcheck {
1.1075.2.73  raeburn  4592:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4593: 
1.1075.2.73  raeburn  4594:     if (defined($udom) && defined($uname)) {
                   4595:         # If uname and udom are for a course, check for blocks in the course.
                   4596:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4597:             my ($startblock,$endblock,$triggerblock) =
                   4598:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4599:             return ($startblock,$endblock,$triggerblock);
                   4600:         }
                   4601:     } else {
1.490     raeburn  4602:         $udom = $env{'user.domain'};
                   4603:         $uname = $env{'user.name'};
                   4604:     }
                   4605: 
1.502     raeburn  4606:     my $startblock = 0;
                   4607:     my $endblock = 0;
1.1062    raeburn  4608:     my $triggerblock = '';
1.482     raeburn  4609:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4610: 
1.490     raeburn  4611:     # If uname is for a user, and activity is course-specific, i.e.,
                   4612:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4613: 
1.490     raeburn  4614:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.73  raeburn  4615:          $activity eq 'groups' || $activity eq 'printout') &&
                   4616:         ($env{'request.course.id'})) {
1.490     raeburn  4617:         foreach my $key (keys(%live_courses)) {
                   4618:             if ($key ne $env{'request.course.id'}) {
                   4619:                 delete($live_courses{$key});
                   4620:             }
                   4621:         }
                   4622:     }
                   4623: 
                   4624:     my $otheruser = 0;
                   4625:     my %own_courses;
                   4626:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4627:         # Resource belongs to user other than current user.
                   4628:         $otheruser = 1;
                   4629:         # Gather courses for current user
                   4630:         %own_courses = 
                   4631:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4632:     }
                   4633: 
                   4634:     # Gather active course roles - course coordinator, instructor, 
                   4635:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4636: 
                   4637:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4638:         my ($cdom,$cnum);
                   4639:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4640:             $cdom = $env{'course.'.$course.'.domain'};
                   4641:             $cnum = $env{'course.'.$course.'.num'};
                   4642:         } else {
1.490     raeburn  4643:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4644:         }
                   4645:         my $no_ownblock = 0;
                   4646:         my $no_userblock = 0;
1.533     raeburn  4647:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4648:             # Check if current user has 'evb' priv for this
                   4649:             if (defined($own_courses{$course})) {
                   4650:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4651:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4652:                     if ($sec ne 'none') {
                   4653:                         $checkrole .= '/'.$sec;
                   4654:                     }
                   4655:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4656:                         $no_ownblock = 1;
                   4657:                         last;
                   4658:                     }
                   4659:                 }
                   4660:             }
                   4661:             # if they have 'evb' priv and are currently not playing student
                   4662:             next if (($no_ownblock) &&
                   4663:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4664:         }
1.474     raeburn  4665:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4666:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4667:             if ($sec ne 'none') {
1.482     raeburn  4668:                 $checkrole .= '/'.$sec;
1.474     raeburn  4669:             }
1.490     raeburn  4670:             if ($otheruser) {
                   4671:                 # Resource belongs to user other than current user.
                   4672:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4673:                 my (%allroles,%userroles);
                   4674:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4675:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4676:                         my ($trole,$tdom,$tnum,$tsec);
                   4677:                         if ($entry =~ /^cr/) {
                   4678:                             ($trole,$tdom,$tnum,$tsec) = 
                   4679:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4680:                         } else {
                   4681:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4682:                         }
                   4683:                         my ($spec,$area,$trest);
                   4684:                         $area = '/'.$tdom.'/'.$tnum;
                   4685:                         $trest = $tnum;
                   4686:                         if ($tsec ne '') {
                   4687:                             $area .= '/'.$tsec;
                   4688:                             $trest .= '/'.$tsec;
                   4689:                         }
                   4690:                         $spec = $trole.'.'.$area;
                   4691:                         if ($trole =~ /^cr/) {
                   4692:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4693:                                                               $tdom,$spec,$trest,$area);
                   4694:                         } else {
                   4695:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4696:                                                                 $tdom,$spec,$trest,$area);
                   4697:                         }
                   4698:                     }
1.1075.2.124  raeburn  4699:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  4700:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4701:                         if ($1) {
                   4702:                             $no_userblock = 1;
                   4703:                             last;
                   4704:                         }
1.486     raeburn  4705:                     }
                   4706:                 }
1.490     raeburn  4707:             } else {
                   4708:                 # Resource belongs to current user
                   4709:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4710:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4711:                     $no_ownblock = 1;
                   4712:                     last;
                   4713:                 }
1.474     raeburn  4714:             }
                   4715:         }
                   4716:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4717:         next if (($no_ownblock) &&
1.491     albertel 4718:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4719:         next if ($no_userblock);
1.474     raeburn  4720: 
1.866     kalberla 4721:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4722:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4723:         
1.1062    raeburn  4724:         my ($start,$end,$trigger) = 
                   4725:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4726:         if (($start != 0) && 
                   4727:             (($startblock == 0) || ($startblock > $start))) {
                   4728:             $startblock = $start;
1.1062    raeburn  4729:             if ($trigger ne '') {
                   4730:                 $triggerblock = $trigger;
                   4731:             }
1.502     raeburn  4732:         }
                   4733:         if (($end != 0)  &&
                   4734:             (($endblock == 0) || ($endblock < $end))) {
                   4735:             $endblock = $end;
1.1062    raeburn  4736:             if ($trigger ne '') {
                   4737:                 $triggerblock = $trigger;
                   4738:             }
1.502     raeburn  4739:         }
1.490     raeburn  4740:     }
1.1062    raeburn  4741:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4742: }
                   4743: 
                   4744: sub get_blocks {
1.1062    raeburn  4745:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4746:     my $startblock = 0;
                   4747:     my $endblock = 0;
1.1062    raeburn  4748:     my $triggerblock = '';
1.490     raeburn  4749:     my $course = $cdom.'_'.$cnum;
                   4750:     $setters->{$course} = {};
                   4751:     $setters->{$course}{'staff'} = [];
                   4752:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4753:     $setters->{$course}{'triggers'} = [];
                   4754:     my (@blockers,%triggered);
                   4755:     my $now = time;
                   4756:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4757:     if ($activity eq 'docs') {
                   4758:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4759:         foreach my $block (@blockers) {
                   4760:             if ($block =~ /^firstaccess____(.+)$/) {
                   4761:                 my $item = $1;
                   4762:                 my $type = 'map';
                   4763:                 my $timersymb = $item;
                   4764:                 if ($item eq 'course') {
                   4765:                     $type = 'course';
                   4766:                 } elsif ($item =~ /___\d+___/) {
                   4767:                     $type = 'resource';
                   4768:                 } else {
                   4769:                     $timersymb = &Apache::lonnet::symbread($item);
                   4770:                 }
                   4771:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4772:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4773:                 $triggered{$block} = {
                   4774:                                        start => $start,
                   4775:                                        end   => $end,
                   4776:                                        type  => $type,
                   4777:                                      };
                   4778:             }
                   4779:         }
                   4780:     } else {
                   4781:         foreach my $block (keys(%commblocks)) {
                   4782:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4783:                 my ($start,$end) = ($1,$2);
                   4784:                 if ($start <= time && $end >= time) {
                   4785:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4786:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4787:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4788:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4789:                                     push(@blockers,$block);
                   4790:                                 }
                   4791:                             }
                   4792:                         }
                   4793:                     }
                   4794:                 }
                   4795:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4796:                 my $item = $1;
                   4797:                 my $timersymb = $item; 
                   4798:                 my $type = 'map';
                   4799:                 if ($item eq 'course') {
                   4800:                     $type = 'course';
                   4801:                 } elsif ($item =~ /___\d+___/) {
                   4802:                     $type = 'resource';
                   4803:                 } else {
                   4804:                     $timersymb = &Apache::lonnet::symbread($item);
                   4805:                 }
                   4806:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4807:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4808:                 if ($start && $end) {
                   4809:                     if (($start <= time) && ($end >= time)) {
                   4810:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4811:                             push(@blockers,$block);
                   4812:                             $triggered{$block} = {
                   4813:                                                    start => $start,
                   4814:                                                    end   => $end,
                   4815:                                                    type  => $type,
                   4816:                                                  };
                   4817:                         }
                   4818:                     }
1.490     raeburn  4819:                 }
1.1062    raeburn  4820:             }
                   4821:         }
                   4822:     }
                   4823:     foreach my $blocker (@blockers) {
                   4824:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4825:             &parse_block_record($commblocks{$blocker});
                   4826:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4827:         my ($start,$end,$triggertype);
                   4828:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4829:             ($start,$end) = ($1,$2);
                   4830:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4831:             $start = $triggered{$blocker}{'start'};
                   4832:             $end = $triggered{$blocker}{'end'};
                   4833:             $triggertype = $triggered{$blocker}{'type'};
                   4834:         }
                   4835:         if ($start) {
                   4836:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4837:             if ($triggertype) {
                   4838:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4839:             } else {
                   4840:                 push(@{$$setters{$course}{'triggers'}},0);
                   4841:             }
                   4842:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4843:                 $startblock = $start;
                   4844:                 if ($triggertype) {
                   4845:                     $triggerblock = $blocker;
1.474     raeburn  4846:                 }
                   4847:             }
1.1062    raeburn  4848:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4849:                $endblock = $end;
                   4850:                if ($triggertype) {
                   4851:                    $triggerblock = $blocker;
                   4852:                }
                   4853:             }
1.474     raeburn  4854:         }
                   4855:     }
1.1062    raeburn  4856:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4857: }
                   4858: 
                   4859: sub parse_block_record {
                   4860:     my ($record) = @_;
                   4861:     my ($setuname,$setudom,$title,$blocks);
                   4862:     if (ref($record) eq 'HASH') {
                   4863:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4864:         $title = &unescape($record->{'event'});
                   4865:         $blocks = $record->{'blocks'};
                   4866:     } else {
                   4867:         my @data = split(/:/,$record,3);
                   4868:         if (scalar(@data) eq 2) {
                   4869:             $title = $data[1];
                   4870:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4871:         } else {
                   4872:             ($setuname,$setudom,$title) = @data;
                   4873:         }
                   4874:         $blocks = { 'com' => 'on' };
                   4875:     }
                   4876:     return ($setuname,$setudom,$title,$blocks);
                   4877: }
                   4878: 
1.854     kalberla 4879: sub blocking_status {
1.1075.2.73  raeburn  4880:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  4881:     my %setters;
1.890     droeschl 4882: 
1.1061    raeburn  4883: # check for active blocking
1.1062    raeburn  4884:     my ($startblock,$endblock,$triggerblock) = 
1.1075.2.73  raeburn  4885:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  4886:     my $blocked = 0;
                   4887:     if ($startblock && $endblock) {
                   4888:         $blocked = 1;
                   4889:     }
1.890     droeschl 4890: 
1.1061    raeburn  4891: # caller just wants to know whether a block is active
                   4892:     if (!wantarray) { return $blocked; }
                   4893: 
                   4894: # build a link to a popup window containing the details
                   4895:     my $querystring  = "?activity=$activity";
                   4896: # $uname and $udom decide whose portfolio the user is trying to look at
1.1075.2.97  raeburn  4897:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   4898:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   4899:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  4900:     } elsif ($activity eq 'docs') {
                   4901:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4902:     }
1.1061    raeburn  4903: 
                   4904:     my $output .= <<'END_MYBLOCK';
                   4905: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4906:     var options = "width=" + w + ",height=" + h + ",";
                   4907:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4908:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4909:     var newWin = window.open(url, wdwName, options);
                   4910:     newWin.focus();
                   4911: }
1.890     droeschl 4912: END_MYBLOCK
1.854     kalberla 4913: 
1.1061    raeburn  4914:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4915:   
1.1061    raeburn  4916:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4917:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  4918:     my $class = 'LC_comblock';
1.1062    raeburn  4919:     if ($activity eq 'docs') {
                   4920:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  4921:         $class = '';
1.1063    raeburn  4922:     } elsif ($activity eq 'printout') {
                   4923:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  4924:     } elsif ($activity eq 'passwd') {
                   4925:         $text = &mt('Password Changing Blocked');
1.1062    raeburn  4926:     }
1.1061    raeburn  4927:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  4928: <div class='$class'>
1.869     kalberla 4929:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4930:   title='$text'>
                   4931:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4932:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4933:   title='$text'>$text</a>
1.867     kalberla 4934: </div>
                   4935: 
                   4936: END_BLOCK
1.474     raeburn  4937: 
1.1061    raeburn  4938:     return ($blocked, $output);
1.854     kalberla 4939: }
1.490     raeburn  4940: 
1.60      matthew  4941: ###############################################
                   4942: 
1.682     raeburn  4943: sub check_ip_acc {
1.1075.2.105  raeburn  4944:     my ($acc,$clientip)=@_;
1.682     raeburn  4945:     &Apache::lonxml::debug("acc is $acc");
                   4946:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4947:         return 1;
                   4948:     }
                   4949:     my $allowed=0;
1.1075.2.111  raeburn  4950:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
1.682     raeburn  4951: 
                   4952:     my $name;
                   4953:     foreach my $pattern (split(',',$acc)) {
                   4954:         $pattern =~ s/^\s*//;
                   4955:         $pattern =~ s/\s*$//;
                   4956:         if ($pattern =~ /\*$/) {
                   4957:             #35.8.*
                   4958:             $pattern=~s/\*//;
                   4959:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4960:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4961:             #35.8.3.[34-56]
                   4962:             my $low=$2;
                   4963:             my $high=$3;
                   4964:             $pattern=$1;
                   4965:             if ($ip =~ /^\Q$pattern\E/) {
                   4966:                 my $last=(split(/\./,$ip))[3];
                   4967:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4968:             }
                   4969:         } elsif ($pattern =~ /^\*/) {
                   4970:             #*.msu.edu
                   4971:             $pattern=~s/\*//;
                   4972:             if (!defined($name)) {
                   4973:                 use Socket;
                   4974:                 my $netaddr=inet_aton($ip);
                   4975:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4976:             }
                   4977:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4978:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4979:             #127.0.0.1
                   4980:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4981:         } else {
                   4982:             #some.name.com
                   4983:             if (!defined($name)) {
                   4984:                 use Socket;
                   4985:                 my $netaddr=inet_aton($ip);
                   4986:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4987:             }
                   4988:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4989:         }
                   4990:         if ($allowed) { last; }
                   4991:     }
                   4992:     return $allowed;
                   4993: }
                   4994: 
1.1075.2.127.  .1(raebu 4995:17): sub check_slotip_acc {
                   4996:17):     my ($acc,$clientip)=@_;
                   4997:17):     &Apache::lonxml::debug("acc is $acc");
                   4998:17):     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4999:17):         return 1;
                   5000:17):     }
                   5001:17):     my $allowed;
                   5002:17):     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
                   5003:17): 
                   5004:17):     my $name;
                   5005:17):     my %access = (
                   5006:17):                      allowfrom => 1,
                   5007:17):                      denyfrom  => 0,
                   5008:17):                  );
                   5009:17):     my @allows;
                   5010:17):     my @denies;
                   5011:17):     foreach my $item (split(',',$acc)) {
                   5012:17):         $item =~ s/^\s*//;
                   5013:17):         $item =~ s/\s*$//;
                   5014:17):         my $pattern;
                   5015:17):         if ($item =~ /^\!(.+)$/) {
                   5016:17):             push(@denies,$1);
                   5017:17):         } else {
                   5018:17):             push(@allows,$item);
                   5019:17):         }
                   5020:17):    }
                   5021:17):    my $numdenies = scalar(@denies);
                   5022:17):    my $numallows = scalar(@allows);
                   5023:17):    my $count = 0;
                   5024:17):    foreach my $pattern (@denies,@allows) {
                   5025:17):         $count ++;
                   5026:17):         my $acctype = 'allowfrom';
                   5027:17):         if ($count <= $numdenies) {
                   5028:17):             $acctype = 'denyfrom';
                   5029:17):         }
                   5030:17):         if ($pattern =~ /\*$/) {
                   5031:17):             #35.8.*
                   5032:17):             $pattern=~s/\*//;
                   5033:17):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
                   5034:17):         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5035:17):             #35.8.3.[34-56]
                   5036:17):             my $low=$2;
                   5037:17):             my $high=$3;
                   5038:17):             $pattern=$1;
                   5039:17):             if ($ip =~ /^\Q$pattern\E/) {
                   5040:17):                 my $last=(split(/\./,$ip))[3];
                   5041:17):                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
                   5042:17):             }
                   5043:17):         } elsif ($pattern =~ /^\*/) {
                   5044:17):             #*.msu.edu
                   5045:17):             $pattern=~s/\*//;
                   5046:17):             if (!defined($name)) {
                   5047:17):                 use Socket;
                   5048:17):                 my $netaddr=inet_aton($ip);
                   5049:17):                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5050:17):             }
                   5051:17):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5052:17):         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5053:17):             #127.0.0.1
                   5054:17):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
                   5055:17):         } else {
                   5056:17):             #some.name.com
                   5057:17):             if (!defined($name)) {
                   5058:17):                 use Socket;
                   5059:17):                 my $netaddr=inet_aton($ip);
                   5060:17):                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5061:17):             }
                   5062:17):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5063:17):         }
                   5064:17):         if ($allowed =~ /^(0|1)$/) { last; }
                   5065:17):     }
                   5066:17):     if ($allowed eq '') {
                   5067:17):         if ($numdenies && !$numallows) {
                   5068:17):             $allowed = 1;
                   5069:17):         } else {
                   5070:17):             $allowed = 0;
                   5071:17):         }
                   5072:17):     }
                   5073:17):     return $allowed;
                   5074:17): }
                   5075:17): 
1.682     raeburn  5076: ###############################################
                   5077: 
1.60      matthew  5078: =pod
                   5079: 
1.112     bowersj2 5080: =head1 Domain Template Functions
                   5081: 
                   5082: =over 4
                   5083: 
                   5084: =item * &determinedomain()
1.60      matthew  5085: 
                   5086: Inputs: $domain (usually will be undef)
                   5087: 
1.63      www      5088: Returns: Determines which domain should be used for designs
1.60      matthew  5089: 
                   5090: =cut
1.54      www      5091: 
1.60      matthew  5092: ###############################################
1.63      www      5093: sub determinedomain {
                   5094:     my $domain=shift;
1.531     albertel 5095:     if (! $domain) {
1.60      matthew  5096:         # Determine domain if we have not been given one
1.893     raeburn  5097:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5098:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5099:         if ($env{'request.role.domain'}) { 
                   5100:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5101:         }
                   5102:     }
1.63      www      5103:     return $domain;
                   5104: }
                   5105: ###############################################
1.517     raeburn  5106: 
1.518     albertel 5107: sub devalidate_domconfig_cache {
                   5108:     my ($udom)=@_;
                   5109:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5110: }
                   5111: 
                   5112: # ---------------------- Get domain configuration for a domain
                   5113: sub get_domainconf {
                   5114:     my ($udom) = @_;
                   5115:     my $cachetime=1800;
                   5116:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5117:     if (defined($cached)) { return %{$result}; }
                   5118: 
                   5119:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5120: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5121:     my (%designhash,%legacy);
1.518     albertel 5122:     if (keys(%domconfig) > 0) {
                   5123:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5124:             if (keys(%{$domconfig{'login'}})) {
                   5125:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5126:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5127:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5128:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5129:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5130:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5131:                                         if ($key eq 'loginvia') {
                   5132:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5133:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5134:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5135:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5136:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5137:                                                 } else {
                   5138:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5139:                                                 }
1.948     raeburn  5140:                                             }
1.1075.2.87  raeburn  5141:                                         } elsif ($key eq 'headtag') {
                   5142:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5143:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5144:                                             }
1.946     raeburn  5145:                                         }
1.1075.2.87  raeburn  5146:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5147:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5148:                                         }
1.946     raeburn  5149:                                     }
                   5150:                                 }
                   5151:                             }
                   5152:                         } else {
                   5153:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5154:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5155:                                     $domconfig{'login'}{$key}{$img};
                   5156:                             }
1.699     raeburn  5157:                         }
                   5158:                     } else {
                   5159:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5160:                     }
1.632     raeburn  5161:                 }
                   5162:             } else {
                   5163:                 $legacy{'login'} = 1;
1.518     albertel 5164:             }
1.632     raeburn  5165:         } else {
                   5166:             $legacy{'login'} = 1;
1.518     albertel 5167:         }
                   5168:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5169:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5170:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5171:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5172:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5173:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5174:                         }
1.518     albertel 5175:                     }
                   5176:                 }
1.632     raeburn  5177:             } else {
                   5178:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5179:             }
1.632     raeburn  5180:         } else {
                   5181:             $legacy{'rolecolors'} = 1;
1.518     albertel 5182:         }
1.948     raeburn  5183:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5184:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5185:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5186:             }
                   5187:         }
1.632     raeburn  5188:         if (keys(%legacy) > 0) {
                   5189:             my %legacyhash = &get_legacy_domconf($udom);
                   5190:             foreach my $item (keys(%legacyhash)) {
                   5191:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5192:                     if ($legacy{'login'}) { 
                   5193:                         $designhash{$item} = $legacyhash{$item};
                   5194:                     }
                   5195:                 } else {
                   5196:                     if ($legacy{'rolecolors'}) {
                   5197:                         $designhash{$item} = $legacyhash{$item};
                   5198:                     }
1.518     albertel 5199:                 }
                   5200:             }
                   5201:         }
1.632     raeburn  5202:     } else {
                   5203:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5204:     }
                   5205:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5206: 				  $cachetime);
                   5207:     return %designhash;
                   5208: }
                   5209: 
1.632     raeburn  5210: sub get_legacy_domconf {
                   5211:     my ($udom) = @_;
                   5212:     my %legacyhash;
                   5213:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5214:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5215:     if (-e $designfile) {
                   5216:         if ( open (my $fh,"<$designfile") ) {
                   5217:             while (my $line = <$fh>) {
                   5218:                 next if ($line =~ /^\#/);
                   5219:                 chomp($line);
                   5220:                 my ($key,$val)=(split(/\=/,$line));
                   5221:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5222:             }
                   5223:             close($fh);
                   5224:         }
                   5225:     }
1.1026    raeburn  5226:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5227:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5228:     }
                   5229:     return %legacyhash;
                   5230: }
                   5231: 
1.63      www      5232: =pod
                   5233: 
1.112     bowersj2 5234: =item * &domainlogo()
1.63      www      5235: 
                   5236: Inputs: $domain (usually will be undef)
                   5237: 
                   5238: Returns: A link to a domain logo, if the domain logo exists.
                   5239: If the domain logo does not exist, a description of the domain.
                   5240: 
                   5241: =cut
1.112     bowersj2 5242: 
1.63      www      5243: ###############################################
                   5244: sub domainlogo {
1.517     raeburn  5245:     my $domain = &determinedomain(shift);
1.518     albertel 5246:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5247:     # See if there is a logo
                   5248:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5249:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5250:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5251: 	    if ($imgsrc =~ m{^/res/}) {
                   5252: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5253: 		&Apache::lonnet::repcopy($local_name);
                   5254: 	    }
                   5255: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5256:         } 
                   5257:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5258:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5259:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5260:     } else {
1.60      matthew  5261:         return '';
1.59      www      5262:     }
                   5263: }
1.63      www      5264: ##############################################
                   5265: 
                   5266: =pod
                   5267: 
1.112     bowersj2 5268: =item * &designparm()
1.63      www      5269: 
                   5270: Inputs: $which parameter; $domain (usually will be undef)
                   5271: 
                   5272: Returns: value of designparamter $which
                   5273: 
                   5274: =cut
1.112     bowersj2 5275: 
1.397     albertel 5276: 
1.400     albertel 5277: ##############################################
1.397     albertel 5278: sub designparm {
                   5279:     my ($which,$domain)=@_;
                   5280:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5281:         return $env{'environment.color.'.$which};
1.96      www      5282:     }
1.63      www      5283:     $domain=&determinedomain($domain);
1.1016    raeburn  5284:     my %domdesign;
                   5285:     unless ($domain eq 'public') {
                   5286:         %domdesign = &get_domainconf($domain);
                   5287:     }
1.520     raeburn  5288:     my $output;
1.517     raeburn  5289:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5290:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5291:     } else {
1.520     raeburn  5292:         $output = $defaultdesign{$which};
                   5293:     }
                   5294:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5295:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5296:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5297:             if ($output =~ m{^/res/}) {
                   5298:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5299:                 &Apache::lonnet::repcopy($local_name);
                   5300:             }
1.520     raeburn  5301:             $output = &lonhttpdurl($output);
                   5302:         }
1.63      www      5303:     }
1.520     raeburn  5304:     return $output;
1.63      www      5305: }
1.59      www      5306: 
1.822     bisitz   5307: ##############################################
                   5308: =pod
                   5309: 
1.832     bisitz   5310: =item * &authorspace()
                   5311: 
1.1028    raeburn  5312: Inputs: $url (usually will be undef).
1.832     bisitz   5313: 
1.1075.2.40  raeburn  5314: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5315:          directory being viewed (or for which action is being taken). 
                   5316:          If $url is provided, and begins /priv/<domain>/<uname>
                   5317:          the path will be that portion of the $context argument.
                   5318:          Otherwise the path will be for the author space of the current
                   5319:          user when the current role is author, or for that of the 
                   5320:          co-author/assistant co-author space when the current role 
                   5321:          is co-author or assistant co-author.
1.832     bisitz   5322: 
                   5323: =cut
                   5324: 
                   5325: sub authorspace {
1.1028    raeburn  5326:     my ($url) = @_;
                   5327:     if ($url ne '') {
                   5328:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5329:            return $1;
                   5330:         }
                   5331:     }
1.832     bisitz   5332:     my $caname = '';
1.1024    www      5333:     my $cadom = '';
1.1028    raeburn  5334:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5335:         ($cadom,$caname) =
1.832     bisitz   5336:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5337:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5338:         $caname = $env{'user.name'};
1.1024    www      5339:         $cadom = $env{'user.domain'};
1.832     bisitz   5340:     }
1.1028    raeburn  5341:     if (($caname ne '') && ($cadom ne '')) {
                   5342:         return "/priv/$cadom/$caname/";
                   5343:     }
                   5344:     return;
1.832     bisitz   5345: }
                   5346: 
                   5347: ##############################################
                   5348: =pod
                   5349: 
1.822     bisitz   5350: =item * &head_subbox()
                   5351: 
                   5352: Inputs: $content (contains HTML code with page functions, etc.)
                   5353: 
                   5354: Returns: HTML div with $content
                   5355:          To be included in page header
                   5356: 
                   5357: =cut
                   5358: 
                   5359: sub head_subbox {
                   5360:     my ($content)=@_;
                   5361:     my $output =
1.993     raeburn  5362:         '<div class="LC_head_subbox">'
1.822     bisitz   5363:        .$content
                   5364:        .'</div>'
                   5365: }
                   5366: 
                   5367: ##############################################
                   5368: =pod
                   5369: 
                   5370: =item * &CSTR_pageheader()
                   5371: 
1.1026    raeburn  5372: Input: (optional) filename from which breadcrumb trail is built.
                   5373:        In most cases no input as needed, as $env{'request.filename'}
                   5374:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5375: 
                   5376: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5377:          To be included on Authoring Space pages
1.822     bisitz   5378: 
                   5379: =cut
                   5380: 
                   5381: sub CSTR_pageheader {
1.1026    raeburn  5382:     my ($trailfile) = @_;
                   5383:     if ($trailfile eq '') {
                   5384:         $trailfile = $env{'request.filename'};
                   5385:     }
                   5386: 
                   5387: # this is for resources; directories have customtitle, and crumbs
                   5388: # and select recent are created in lonpubdir.pm
                   5389: 
                   5390:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5391:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5392:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5393:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5394:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5395: 
                   5396:     my $parentpath = '';
                   5397:     my $lastitem = '';
                   5398:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5399:         $parentpath = $1;
                   5400:         $lastitem = $2;
                   5401:     } else {
                   5402:         $lastitem = $thisdisfn;
                   5403:     }
1.921     bisitz   5404: 
                   5405:     my $output =
1.822     bisitz   5406:          '<div>'
                   5407:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5408:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5409:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5410:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5411:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5412: 
                   5413:     if ($lastitem) {
                   5414:         $output .=
                   5415:              '<span class="LC_filename">'
                   5416:             .$lastitem
                   5417:             .'</span>';
                   5418:     }
                   5419:     $output .=
                   5420:          '<br />'
1.822     bisitz   5421:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5422:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5423:         .'</form>'
                   5424:         .&Apache::lonmenu::constspaceform()
                   5425:         .'</div>';
1.921     bisitz   5426: 
                   5427:     return $output;
1.822     bisitz   5428: }
                   5429: 
1.60      matthew  5430: ###############################################
                   5431: ###############################################
                   5432: 
                   5433: =pod
                   5434: 
1.112     bowersj2 5435: =back
                   5436: 
1.549     albertel 5437: =head1 HTML Helpers
1.112     bowersj2 5438: 
                   5439: =over 4
                   5440: 
                   5441: =item * &bodytag()
1.60      matthew  5442: 
                   5443: Returns a uniform header for LON-CAPA web pages.
                   5444: 
                   5445: Inputs: 
                   5446: 
1.112     bowersj2 5447: =over 4
                   5448: 
                   5449: =item * $title, A title to be displayed on the page.
                   5450: 
                   5451: =item * $function, the current role (can be undef).
                   5452: 
                   5453: =item * $addentries, extra parameters for the <body> tag.
                   5454: 
                   5455: =item * $bodyonly, if defined, only return the <body> tag.
                   5456: 
                   5457: =item * $domain, if defined, force a given domain.
                   5458: 
                   5459: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5460:             text interface only)
1.60      matthew  5461: 
1.814     bisitz   5462: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5463:                      navigational links
1.317     albertel 5464: 
1.338     albertel 5465: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5466: 
1.1075.2.12  raeburn  5467: =item * $no_inline_link, if true and in remote mode, don't show the
                   5468:          'Switch To Inline Menu' link
                   5469: 
1.460     albertel 5470: =item * $args, optional argument valid values are
                   5471:             no_auto_mt_title -> prevents &mt()ing the title arg
                   5472: 
1.1075.2.15  raeburn  5473: =item * $advtoolsref, optional argument, ref to an array containing
                   5474:             inlineremote items to be added in "Functions" menu below
                   5475:             breadcrumbs.
                   5476: 
1.112     bowersj2 5477: =back
                   5478: 
1.60      matthew  5479: Returns: A uniform header for LON-CAPA web pages.  
                   5480: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5481: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5482: other decorations will be returned.
                   5483: 
                   5484: =cut
                   5485: 
1.54      www      5486: sub bodytag {
1.831     bisitz   5487:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5488:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5489: 
1.954     raeburn  5490:     my $public;
                   5491:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5492:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5493:         $public = 1;
                   5494:     }
1.460     albertel 5495:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5496:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5497: 
1.183     matthew  5498:     $function = &get_users_function() if (!$function);
1.339     albertel 5499:     my $img =    &designparm($function.'.img',$domain);
                   5500:     my $font =   &designparm($function.'.font',$domain);
                   5501:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5502: 
1.803     bisitz   5503:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5504: 		   'bgcolor' => $pgbg,
1.339     albertel 5505: 		   'text'    => $font,
                   5506:                    'alink'   => &designparm($function.'.alink',$domain),
                   5507: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5508: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5509:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5510: 
1.63      www      5511:  # role and realm
1.1075.2.68  raeburn  5512:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5513:     if ($realm) {
                   5514:         $realm = '/'.$realm;
                   5515:     }
1.378     raeburn  5516:     if ($role  eq 'ca') {
1.479     albertel 5517:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5518:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5519:     } 
1.55      www      5520: # realm
1.258     albertel 5521:     if ($env{'request.course.id'}) {
1.378     raeburn  5522:         if ($env{'request.role'} !~ /^cr/) {
                   5523:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  5524:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  5525:             if ($env{'request.role.desc'}) {
                   5526:                 $role = $env{'request.role.desc'};
                   5527:             } else {
                   5528:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5529:             }
1.1075.2.115  raeburn  5530:         } else {
                   5531:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  5532:         }
1.898     raeburn  5533:         if ($env{'request.course.sec'}) {
                   5534:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5535:         }   
1.359     albertel 5536: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5537:     } else {
                   5538:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5539:     }
1.433     albertel 5540: 
1.359     albertel 5541:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5542: 
1.438     albertel 5543:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5544: 
1.101     www      5545: # construct main body tag
1.359     albertel 5546:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  5547: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5548: 
1.1075.2.38  raeburn  5549:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5550: 
                   5551:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5552:         return $bodytag;
1.1075.2.38  raeburn  5553:     }
1.359     albertel 5554: 
1.954     raeburn  5555:     if ($public) {
1.433     albertel 5556: 	undef($role);
                   5557:     }
1.359     albertel 5558:     
1.762     bisitz   5559:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5560:     #
                   5561:     # Extra info if you are the DC
                   5562:     my $dc_info = '';
                   5563:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5564:                         $env{'course.'.$env{'request.course.id'}.
                   5565:                                  '.domain'}.'/'})) {
                   5566:         my $cid = $env{'request.course.id'};
1.917     raeburn  5567:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5568:         $dc_info =~ s/\s+$//;
1.359     albertel 5569:     }
                   5570: 
1.1075.2.108  raeburn  5571:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 5572: 
1.1075.2.13  raeburn  5573:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5574: 
1.1075.2.38  raeburn  5575: 
                   5576: 
1.1075.2.21  raeburn  5577:     my $funclist;
                   5578:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5579:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5580:                     Apache::lonmenu::serverform();
                   5581:         my $forbodytag;
                   5582:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5583:                                             $forcereg,$args->{'group'},
                   5584:                                             $args->{'bread_crumbs'},
                   5585:                                             $advtoolsref,'',\$forbodytag);
                   5586:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5587:             $funclist = $forbodytag;
                   5588:         }
                   5589:     } else {
1.903     droeschl 5590: 
                   5591:         #    if ($env{'request.state'} eq 'construct') {
                   5592:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5593:         #    }
                   5594: 
1.1075.2.38  raeburn  5595:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5596:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5597: 
1.1075.2.38  raeburn  5598:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5599: 
1.916     droeschl 5600:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5601:             if ($dc_info) {
                   5602:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5603:             }
1.1075.2.38  raeburn  5604:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5605:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5606:             return $bodytag;
                   5607:         }
1.894     droeschl 5608: 
1.927     raeburn  5609:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5610:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5611:         }
1.916     droeschl 5612: 
1.1075.2.38  raeburn  5613:         $bodytag .= $right;
1.852     droeschl 5614: 
1.917     raeburn  5615:         if ($dc_info) {
                   5616:             $dc_info = &dc_courseid_toggle($dc_info);
                   5617:         }
                   5618:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5619: 
1.1075.2.61  raeburn  5620:         #if directed to not display the secondary menu, don't.
                   5621:         if ($args->{'no_secondary_menu'}) {
                   5622:             return $bodytag;
                   5623:         }
1.903     droeschl 5624:         #don't show menus for public users
1.954     raeburn  5625:         if (!$public){
1.1075.2.52  raeburn  5626:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5627:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5628:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5629:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5630:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5631:                                 $args->{'bread_crumbs'});
1.1075.2.116  raeburn  5632:             } elsif ($forcereg) {
1.1075.2.22  raeburn  5633:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.116  raeburn  5634:                                                             $args->{'group'},
                   5635:                                                             $args->{'hide_buttons'});
1.1075.2.15  raeburn  5636:             } else {
1.1075.2.21  raeburn  5637:                 my $forbodytag;
                   5638:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5639:                                                     $forcereg,$args->{'group'},
                   5640:                                                     $args->{'bread_crumbs'},
                   5641:                                                     $advtoolsref,'',\$forbodytag);
                   5642:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5643:                     $bodytag .= $forbodytag;
                   5644:                 }
1.920     raeburn  5645:             }
1.903     droeschl 5646:         }else{
                   5647:             # this is to seperate menu from content when there's no secondary
                   5648:             # menu. Especially needed for public accessible ressources.
                   5649:             $bodytag .= '<hr style="clear:both" />';
                   5650:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5651:         }
1.903     droeschl 5652: 
1.235     raeburn  5653:         return $bodytag;
1.1075.2.12  raeburn  5654:     }
                   5655: 
                   5656: #
                   5657: # Top frame rendering, Remote is up
                   5658: #
                   5659: 
                   5660:     my $imgsrc = $img;
                   5661:     if ($img =~ /^\/adm/) {
                   5662:         $imgsrc = &lonhttpdurl($img);
                   5663:     }
                   5664:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5665: 
1.1075.2.60  raeburn  5666:     my $help=($no_inline_link?''
                   5667:               :&Apache::loncommon::top_nav_help('Help'));
                   5668: 
1.1075.2.12  raeburn  5669:     # Explicit link to get inline menu
                   5670:     my $menu= ($no_inline_link?''
                   5671:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5672: 
                   5673:     if ($dc_info) {
                   5674:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5675:     }
                   5676: 
1.1075.2.38  raeburn  5677:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5678:     unless ($public) {
                   5679:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5680:                                 undef,'LC_menubuttons_link');
                   5681:     }
                   5682: 
1.1075.2.12  raeburn  5683:     unless ($env{'form.inhibitmenu'}) {
                   5684:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5685:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5686:                        <li>$help</li>
1.1075.2.12  raeburn  5687:                        <li>$menu</li>
                   5688:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5689:     }
1.1075.2.13  raeburn  5690:     if ($env{'request.state'} eq 'construct') {
                   5691:         if (!$public){
                   5692:             if ($env{'request.state'} eq 'construct') {
                   5693:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5694:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5695:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5696:                             &Apache::lonmenu::innerregister($forcereg,
                   5697:                                                             $args->{'bread_crumbs'});
                   5698:             }
                   5699:         }
                   5700:     }
1.1075.2.21  raeburn  5701:     return $bodytag."\n".$funclist;
1.182     matthew  5702: }
                   5703: 
1.917     raeburn  5704: sub dc_courseid_toggle {
                   5705:     my ($dc_info) = @_;
1.980     raeburn  5706:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5707:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5708:            &mt('(More ...)').'</a></span>'.
                   5709:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5710: }
                   5711: 
1.330     albertel 5712: sub make_attr_string {
                   5713:     my ($register,$attr_ref) = @_;
                   5714: 
                   5715:     if ($attr_ref && !ref($attr_ref)) {
                   5716: 	die("addentries Must be a hash ref ".
                   5717: 	    join(':',caller(1))." ".
                   5718: 	    join(':',caller(0))." ");
                   5719:     }
                   5720: 
                   5721:     if ($register) {
1.339     albertel 5722: 	my ($on_load,$on_unload);
                   5723: 	foreach my $key (keys(%{$attr_ref})) {
                   5724: 	    if      (lc($key) eq 'onload') {
                   5725: 		$on_load.=$attr_ref->{$key}.';';
                   5726: 		delete($attr_ref->{$key});
                   5727: 
                   5728: 	    } elsif (lc($key) eq 'onunload') {
                   5729: 		$on_unload.=$attr_ref->{$key}.';';
                   5730: 		delete($attr_ref->{$key});
                   5731: 	    }
                   5732: 	}
1.1075.2.12  raeburn  5733:         if ($env{'environment.remote'} eq 'on') {
                   5734:             $attr_ref->{'onload'}  =
                   5735:                 &Apache::lonmenu::loadevents().  $on_load;
                   5736:             $attr_ref->{'onunload'}=
                   5737:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5738:         } else {  
                   5739: 	    $attr_ref->{'onload'}  = $on_load;
                   5740: 	    $attr_ref->{'onunload'}= $on_unload;
                   5741:         }
1.330     albertel 5742:     }
1.339     albertel 5743: 
1.330     albertel 5744:     my $attr_string;
1.1075.2.56  raeburn  5745:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5746: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5747:     }
                   5748:     return $attr_string;
                   5749: }
                   5750: 
                   5751: 
1.182     matthew  5752: ###############################################
1.251     albertel 5753: ###############################################
                   5754: 
                   5755: =pod
                   5756: 
                   5757: =item * &endbodytag()
                   5758: 
                   5759: Returns a uniform footer for LON-CAPA web pages.
                   5760: 
1.635     raeburn  5761: Inputs: 1 - optional reference to an args hash
                   5762: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5763: a 'Continue' link is not displayed if the page contains an
                   5764: internal redirect in the <head></head> section,
                   5765: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5766: 
                   5767: =cut
                   5768: 
                   5769: sub endbodytag {
1.635     raeburn  5770:     my ($args) = @_;
1.1075.2.6  raeburn  5771:     my $endbodytag;
                   5772:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5773:         $endbodytag='</body>';
                   5774:     }
1.315     albertel 5775:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5776:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5777: 	    $endbodytag=
                   5778: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5779: 	        &mt('Continue').'</a>'.
                   5780: 	        $endbodytag;
                   5781:         }
1.315     albertel 5782:     }
1.251     albertel 5783:     return $endbodytag;
                   5784: }
                   5785: 
1.352     albertel 5786: =pod
                   5787: 
                   5788: =item * &standard_css()
                   5789: 
                   5790: Returns a style sheet
                   5791: 
                   5792: Inputs: (all optional)
                   5793:             domain         -> force to color decorate a page for a specific
                   5794:                                domain
                   5795:             function       -> force usage of a specific rolish color scheme
                   5796:             bgcolor        -> override the default page bgcolor
                   5797: 
                   5798: =cut
                   5799: 
1.343     albertel 5800: sub standard_css {
1.345     albertel 5801:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5802:     $function  = &get_users_function() if (!$function);
                   5803:     my $img    = &designparm($function.'.img',   $domain);
                   5804:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5805:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5806:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5807: #second colour for later usage
1.345     albertel 5808:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5809:     my $pgbg_or_bgcolor =
                   5810: 	         $bgcolor ||
1.352     albertel 5811: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5812:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5813:     my $alink  = &designparm($function.'.alink', $domain);
                   5814:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5815:     my $link   = &designparm($function.'.link',  $domain);
                   5816: 
1.602     albertel 5817:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5818:     my $mono                 = 'monospace';
1.850     bisitz   5819:     my $data_table_head      = $sidebg;
                   5820:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5821:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5822:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5823:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5824:     my $mail_new             = '#FFBB77';
                   5825:     my $mail_new_hover       = '#DD9955';
                   5826:     my $mail_read            = '#BBBB77';
                   5827:     my $mail_read_hover      = '#999944';
                   5828:     my $mail_replied         = '#AAAA88';
                   5829:     my $mail_replied_hover   = '#888855';
                   5830:     my $mail_other           = '#99BBBB';
                   5831:     my $mail_other_hover     = '#669999';
1.391     albertel 5832:     my $table_header         = '#DDDDDD';
1.489     raeburn  5833:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5834:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5835:     my $button_hover         = '#BF2317';
1.392     albertel 5836: 
1.608     albertel 5837:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5838:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5839:                                              : '0 3px 0 4px';
1.448     albertel 5840: 
1.523     albertel 5841: 
1.343     albertel 5842:     return <<END;
1.947     droeschl 5843: 
                   5844: /* needed for iframe to allow 100% height in FF */
                   5845: body, html { 
                   5846:     margin: 0;
                   5847:     padding: 0 0.5%;
                   5848:     height: 99%; /* to avoid scrollbars */
                   5849: }
                   5850: 
1.795     www      5851: body {
1.911     bisitz   5852:   font-family: $sans;
                   5853:   line-height:130%;
                   5854:   font-size:0.83em;
                   5855:   color:$font;
1.795     www      5856: }
                   5857: 
1.959     onken    5858: a:focus,
                   5859: a:focus img {
1.795     www      5860:   color: red;
                   5861: }
1.698     harmsja  5862: 
1.911     bisitz   5863: form, .inline {
                   5864:   display: inline;
1.795     www      5865: }
1.721     harmsja  5866: 
1.795     www      5867: .LC_right {
1.911     bisitz   5868:   text-align:right;
1.795     www      5869: }
                   5870: 
                   5871: .LC_middle {
1.911     bisitz   5872:   vertical-align:middle;
1.795     www      5873: }
1.721     harmsja  5874: 
1.1075.2.38  raeburn  5875: .LC_floatleft {
                   5876:   float: left;
                   5877: }
                   5878: 
                   5879: .LC_floatright {
                   5880:   float: right;
                   5881: }
                   5882: 
1.911     bisitz   5883: .LC_400Box {
                   5884:   width:400px;
                   5885: }
1.721     harmsja  5886: 
1.947     droeschl 5887: .LC_iframecontainer {
                   5888:     width: 98%;
                   5889:     margin: 0;
                   5890:     position: fixed;
                   5891:     top: 8.5em;
                   5892:     bottom: 0;
                   5893: }
                   5894: 
                   5895: .LC_iframecontainer iframe{
                   5896:     border: none;
                   5897:     width: 100%;
                   5898:     height: 100%;
                   5899: }
                   5900: 
1.778     bisitz   5901: .LC_filename {
                   5902:   font-family: $mono;
                   5903:   white-space:pre;
1.921     bisitz   5904:   font-size: 120%;
1.778     bisitz   5905: }
                   5906: 
                   5907: .LC_fileicon {
                   5908:   border: none;
                   5909:   height: 1.3em;
                   5910:   vertical-align: text-bottom;
                   5911:   margin-right: 0.3em;
                   5912:   text-decoration:none;
                   5913: }
                   5914: 
1.1008    www      5915: .LC_setting {
                   5916:   text-decoration:underline;
                   5917: }
                   5918: 
1.350     albertel 5919: .LC_error {
                   5920:   color: red;
                   5921: }
1.795     www      5922: 
1.1075.2.15  raeburn  5923: .LC_warning {
                   5924:   color: darkorange;
                   5925: }
                   5926: 
1.457     albertel 5927: .LC_diff_removed {
1.733     bisitz   5928:   color: red;
1.394     albertel 5929: }
1.532     albertel 5930: 
                   5931: .LC_info,
1.457     albertel 5932: .LC_success,
                   5933: .LC_diff_added {
1.350     albertel 5934:   color: green;
                   5935: }
1.795     www      5936: 
1.802     bisitz   5937: div.LC_confirm_box {
                   5938:   background-color: #FAFAFA;
                   5939:   border: 1px solid $lg_border_color;
                   5940:   margin-right: 0;
                   5941:   padding: 5px;
                   5942: }
                   5943: 
                   5944: div.LC_confirm_box .LC_error img,
                   5945: div.LC_confirm_box .LC_success img {
                   5946:   vertical-align: middle;
                   5947: }
                   5948: 
1.1075.2.108  raeburn  5949: .LC_maxwidth {
                   5950:   max-width: 100%;
                   5951:   height: auto;
                   5952: }
                   5953: 
                   5954: .LC_textsize_mobile {
                   5955:   \@media only screen and (max-device-width: 480px) {
                   5956:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   5957:   }
                   5958: }
                   5959: 
1.440     albertel 5960: .LC_icon {
1.771     droeschl 5961:   border: none;
1.790     droeschl 5962:   vertical-align: middle;
1.771     droeschl 5963: }
                   5964: 
1.543     albertel 5965: .LC_docs_spacer {
                   5966:   width: 25px;
                   5967:   height: 1px;
1.771     droeschl 5968:   border: none;
1.543     albertel 5969: }
1.346     albertel 5970: 
1.532     albertel 5971: .LC_internal_info {
1.735     bisitz   5972:   color: #999999;
1.532     albertel 5973: }
                   5974: 
1.794     www      5975: .LC_discussion {
1.1050    www      5976:   background: $data_table_dark;
1.911     bisitz   5977:   border: 1px solid black;
                   5978:   margin: 2px;
1.794     www      5979: }
                   5980: 
                   5981: .LC_disc_action_left {
1.1050    www      5982:   background: $sidebg;
1.911     bisitz   5983:   text-align: left;
1.1050    www      5984:   padding: 4px;
                   5985:   margin: 2px;
1.794     www      5986: }
                   5987: 
                   5988: .LC_disc_action_right {
1.1050    www      5989:   background: $sidebg;
1.911     bisitz   5990:   text-align: right;
1.1050    www      5991:   padding: 4px;
                   5992:   margin: 2px;
1.794     www      5993: }
                   5994: 
                   5995: .LC_disc_new_item {
1.911     bisitz   5996:   background: white;
                   5997:   border: 2px solid red;
1.1050    www      5998:   margin: 4px;
                   5999:   padding: 4px;
1.794     www      6000: }
                   6001: 
                   6002: .LC_disc_old_item {
1.911     bisitz   6003:   background: white;
1.1050    www      6004:   margin: 4px;
                   6005:   padding: 4px;
1.794     www      6006: }
                   6007: 
1.458     albertel 6008: table.LC_pastsubmission {
                   6009:   border: 1px solid black;
                   6010:   margin: 2px;
                   6011: }
                   6012: 
1.924     bisitz   6013: table#LC_menubuttons {
1.345     albertel 6014:   width: 100%;
                   6015:   background: $pgbg;
1.392     albertel 6016:   border: 2px;
1.402     albertel 6017:   border-collapse: separate;
1.803     bisitz   6018:   padding: 0;
1.345     albertel 6019: }
1.392     albertel 6020: 
1.801     tempelho 6021: table#LC_title_bar a {
                   6022:   color: $fontmenu;
                   6023: }
1.836     bisitz   6024: 
1.807     droeschl 6025: table#LC_title_bar {
1.819     tempelho 6026:   clear: both;
1.836     bisitz   6027:   display: none;
1.807     droeschl 6028: }
                   6029: 
1.795     www      6030: table#LC_title_bar,
1.933     droeschl 6031: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6032: table#LC_title_bar.LC_with_remote {
1.359     albertel 6033:   width: 100%;
1.392     albertel 6034:   border-color: $pgbg;
                   6035:   border-style: solid;
                   6036:   border-width: $border;
1.379     albertel 6037:   background: $pgbg;
1.801     tempelho 6038:   color: $fontmenu;
1.392     albertel 6039:   border-collapse: collapse;
1.803     bisitz   6040:   padding: 0;
1.819     tempelho 6041:   margin: 0;
1.359     albertel 6042: }
1.795     www      6043: 
1.933     droeschl 6044: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6045:     margin: 0;
                   6046:     padding: 0;
1.933     droeschl 6047:     position: relative;
                   6048:     list-style: none;
1.913     droeschl 6049: }
1.933     droeschl 6050: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6051:     display: inline;
                   6052: }
1.933     droeschl 6053: 
                   6054: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6055:     padding: 0;
1.933     droeschl 6056:     margin: 0;
                   6057:     float: left;
1.913     droeschl 6058: }
1.933     droeschl 6059: .LC_breadcrumb_tools_tools {
                   6060:     padding: 0;
                   6061:     margin: 0;
1.913     droeschl 6062:     float: right;
                   6063: }
                   6064: 
1.359     albertel 6065: table#LC_title_bar td {
                   6066:   background: $tabbg;
                   6067: }
1.795     www      6068: 
1.911     bisitz   6069: table#LC_menubuttons img {
1.803     bisitz   6070:   border: none;
1.346     albertel 6071: }
1.795     www      6072: 
1.842     droeschl 6073: .LC_breadcrumbs_component {
1.911     bisitz   6074:   float: right;
                   6075:   margin: 0 1em;
1.357     albertel 6076: }
1.842     droeschl 6077: .LC_breadcrumbs_component img {
1.911     bisitz   6078:   vertical-align: middle;
1.777     tempelho 6079: }
1.795     www      6080: 
1.1075.2.108  raeburn  6081: .LC_breadcrumbs_hoverable {
                   6082:   background: $sidebg;
                   6083: }
                   6084: 
1.383     albertel 6085: td.LC_table_cell_checkbox {
                   6086:   text-align: center;
                   6087: }
1.795     www      6088: 
                   6089: .LC_fontsize_small {
1.911     bisitz   6090:   font-size: 70%;
1.705     tempelho 6091: }
                   6092: 
1.844     bisitz   6093: #LC_breadcrumbs {
1.911     bisitz   6094:   clear:both;
                   6095:   background: $sidebg;
                   6096:   border-bottom: 1px solid $lg_border_color;
                   6097:   line-height: 2.5em;
1.933     droeschl 6098:   overflow: hidden;
1.911     bisitz   6099:   margin: 0;
                   6100:   padding: 0;
1.995     raeburn  6101:   text-align: left;
1.819     tempelho 6102: }
1.862     bisitz   6103: 
1.1075.2.16  raeburn  6104: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6105:   clear:both;
                   6106:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6107:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6108:   margin: 0 0 10px 0;
1.966     bisitz   6109:   padding: 3px;
1.995     raeburn  6110:   text-align: left;
1.822     bisitz   6111: }
                   6112: 
1.795     www      6113: .LC_fontsize_medium {
1.911     bisitz   6114:   font-size: 85%;
1.705     tempelho 6115: }
                   6116: 
1.795     www      6117: .LC_fontsize_large {
1.911     bisitz   6118:   font-size: 120%;
1.705     tempelho 6119: }
                   6120: 
1.346     albertel 6121: .LC_menubuttons_inline_text {
                   6122:   color: $font;
1.698     harmsja  6123:   font-size: 90%;
1.701     harmsja  6124:   padding-left:3px;
1.346     albertel 6125: }
                   6126: 
1.934     droeschl 6127: .LC_menubuttons_inline_text img{
                   6128:   vertical-align: middle;
                   6129: }
                   6130: 
1.1051    www      6131: li.LC_menubuttons_inline_text img {
1.951     onken    6132:   cursor:pointer;
1.1002    droeschl 6133:   text-decoration: none;
1.951     onken    6134: }
                   6135: 
1.526     www      6136: .LC_menubuttons_link {
                   6137:   text-decoration: none;
                   6138: }
1.795     www      6139: 
1.522     albertel 6140: .LC_menubuttons_category {
1.521     www      6141:   color: $font;
1.526     www      6142:   background: $pgbg;
1.521     www      6143:   font-size: larger;
                   6144:   font-weight: bold;
                   6145: }
                   6146: 
1.346     albertel 6147: td.LC_menubuttons_text {
1.911     bisitz   6148:   color: $font;
1.346     albertel 6149: }
1.706     harmsja  6150: 
1.346     albertel 6151: .LC_current_location {
                   6152:   background: $tabbg;
                   6153: }
1.795     www      6154: 
1.938     bisitz   6155: table.LC_data_table {
1.347     albertel 6156:   border: 1px solid #000000;
1.402     albertel 6157:   border-collapse: separate;
1.426     albertel 6158:   border-spacing: 1px;
1.610     albertel 6159:   background: $pgbg;
1.347     albertel 6160: }
1.795     www      6161: 
1.422     albertel 6162: .LC_data_table_dense {
                   6163:   font-size: small;
                   6164: }
1.795     www      6165: 
1.507     raeburn  6166: table.LC_nested_outer {
                   6167:   border: 1px solid #000000;
1.589     raeburn  6168:   border-collapse: collapse;
1.803     bisitz   6169:   border-spacing: 0;
1.507     raeburn  6170:   width: 100%;
                   6171: }
1.795     www      6172: 
1.879     raeburn  6173: table.LC_innerpickbox,
1.507     raeburn  6174: table.LC_nested {
1.803     bisitz   6175:   border: none;
1.589     raeburn  6176:   border-collapse: collapse;
1.803     bisitz   6177:   border-spacing: 0;
1.507     raeburn  6178:   width: 100%;
                   6179: }
1.795     www      6180: 
1.911     bisitz   6181: table.LC_data_table tr th,
                   6182: table.LC_calendar tr th,
1.879     raeburn  6183: table.LC_prior_tries tr th,
                   6184: table.LC_innerpickbox tr th {
1.349     albertel 6185:   font-weight: bold;
                   6186:   background-color: $data_table_head;
1.801     tempelho 6187:   color:$fontmenu;
1.701     harmsja  6188:   font-size:90%;
1.347     albertel 6189: }
1.795     www      6190: 
1.879     raeburn  6191: table.LC_innerpickbox tr th,
                   6192: table.LC_innerpickbox tr td {
                   6193:   vertical-align: top;
                   6194: }
                   6195: 
1.711     raeburn  6196: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6197:   background-color: #CCCCCC;
1.711     raeburn  6198:   font-weight: bold;
                   6199:   text-align: left;
                   6200: }
1.795     www      6201: 
1.912     bisitz   6202: table.LC_data_table tr.LC_odd_row > td {
                   6203:   background-color: $data_table_light;
                   6204:   padding: 2px;
                   6205:   vertical-align: top;
                   6206: }
                   6207: 
1.809     bisitz   6208: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6209:   background-color: $data_table_light;
1.912     bisitz   6210:   vertical-align: top;
                   6211: }
                   6212: 
                   6213: table.LC_data_table tr.LC_even_row > td {
                   6214:   background-color: $data_table_dark;
1.425     albertel 6215:   padding: 2px;
1.900     bisitz   6216:   vertical-align: top;
1.347     albertel 6217: }
1.795     www      6218: 
1.809     bisitz   6219: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6220:   background-color: $data_table_dark;
1.900     bisitz   6221:   vertical-align: top;
1.347     albertel 6222: }
1.795     www      6223: 
1.425     albertel 6224: table.LC_data_table tr.LC_data_table_highlight td {
                   6225:   background-color: $data_table_darker;
                   6226: }
1.795     www      6227: 
1.639     raeburn  6228: table.LC_data_table tr td.LC_leftcol_header {
                   6229:   background-color: $data_table_head;
                   6230:   font-weight: bold;
                   6231: }
1.795     www      6232: 
1.451     albertel 6233: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6234: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6235:   font-weight: bold;
                   6236:   font-style: italic;
                   6237:   text-align: center;
                   6238:   padding: 8px;
1.347     albertel 6239: }
1.795     www      6240: 
1.1075.2.30  raeburn  6241: table.LC_data_table tr.LC_empty_row td,
                   6242: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6243:   background-color: $sidebg;
                   6244: }
                   6245: 
                   6246: table.LC_nested tr.LC_empty_row td {
                   6247:   background-color: #FFFFFF;
                   6248: }
                   6249: 
1.890     droeschl 6250: table.LC_caption {
                   6251: }
                   6252: 
1.507     raeburn  6253: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6254:   padding: 4ex
                   6255: }
1.795     www      6256: 
1.507     raeburn  6257: table.LC_nested_outer tr th {
                   6258:   font-weight: bold;
1.801     tempelho 6259:   color:$fontmenu;
1.507     raeburn  6260:   background-color: $data_table_head;
1.701     harmsja  6261:   font-size: small;
1.507     raeburn  6262:   border-bottom: 1px solid #000000;
                   6263: }
1.795     www      6264: 
1.507     raeburn  6265: table.LC_nested_outer tr td.LC_subheader {
                   6266:   background-color: $data_table_head;
                   6267:   font-weight: bold;
                   6268:   font-size: small;
                   6269:   border-bottom: 1px solid #000000;
                   6270:   text-align: right;
1.451     albertel 6271: }
1.795     www      6272: 
1.507     raeburn  6273: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6274:   background-color: #CCCCCC;
1.451     albertel 6275:   font-weight: bold;
                   6276:   font-size: small;
1.507     raeburn  6277:   text-align: center;
                   6278: }
1.795     www      6279: 
1.589     raeburn  6280: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6281: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6282:   text-align: left;
1.451     albertel 6283: }
1.795     www      6284: 
1.507     raeburn  6285: table.LC_nested td {
1.735     bisitz   6286:   background-color: #FFFFFF;
1.451     albertel 6287:   font-size: small;
1.507     raeburn  6288: }
1.795     www      6289: 
1.507     raeburn  6290: table.LC_nested_outer tr th.LC_right_item,
                   6291: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6292: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6293: table.LC_nested tr td.LC_right_item {
1.451     albertel 6294:   text-align: right;
                   6295: }
                   6296: 
1.507     raeburn  6297: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6298:   background-color: #EEEEEE;
1.451     albertel 6299: }
                   6300: 
1.473     raeburn  6301: table.LC_createuser {
                   6302: }
                   6303: 
                   6304: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6305:   font-size: small;
1.473     raeburn  6306: }
                   6307: 
                   6308: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6309:   background-color: #CCCCCC;
1.473     raeburn  6310:   font-weight: bold;
                   6311:   text-align: center;
                   6312: }
                   6313: 
1.349     albertel 6314: table.LC_calendar {
                   6315:   border: 1px solid #000000;
                   6316:   border-collapse: collapse;
1.917     raeburn  6317:   width: 98%;
1.349     albertel 6318: }
1.795     www      6319: 
1.349     albertel 6320: table.LC_calendar_pickdate {
                   6321:   font-size: xx-small;
                   6322: }
1.795     www      6323: 
1.349     albertel 6324: table.LC_calendar tr td {
                   6325:   border: 1px solid #000000;
                   6326:   vertical-align: top;
1.917     raeburn  6327:   width: 14%;
1.349     albertel 6328: }
1.795     www      6329: 
1.349     albertel 6330: table.LC_calendar tr td.LC_calendar_day_empty {
                   6331:   background-color: $data_table_dark;
                   6332: }
1.795     www      6333: 
1.779     bisitz   6334: table.LC_calendar tr td.LC_calendar_day_current {
                   6335:   background-color: $data_table_highlight;
1.777     tempelho 6336: }
1.795     www      6337: 
1.938     bisitz   6338: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6339:   background-color: $mail_new;
                   6340: }
1.795     www      6341: 
1.938     bisitz   6342: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6343:   background-color: $mail_new_hover;
                   6344: }
1.795     www      6345: 
1.938     bisitz   6346: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6347:   background-color: $mail_read;
                   6348: }
1.795     www      6349: 
1.938     bisitz   6350: /*
                   6351: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6352:   background-color: $mail_read_hover;
                   6353: }
1.938     bisitz   6354: */
1.795     www      6355: 
1.938     bisitz   6356: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6357:   background-color: $mail_replied;
                   6358: }
1.795     www      6359: 
1.938     bisitz   6360: /*
                   6361: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6362:   background-color: $mail_replied_hover;
                   6363: }
1.938     bisitz   6364: */
1.795     www      6365: 
1.938     bisitz   6366: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6367:   background-color: $mail_other;
                   6368: }
1.795     www      6369: 
1.938     bisitz   6370: /*
                   6371: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6372:   background-color: $mail_other_hover;
                   6373: }
1.938     bisitz   6374: */
1.494     raeburn  6375: 
1.777     tempelho 6376: table.LC_data_table tr > td.LC_browser_file,
                   6377: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6378:   background: #AAEE77;
1.389     albertel 6379: }
1.795     www      6380: 
1.777     tempelho 6381: table.LC_data_table tr > td.LC_browser_file_locked,
                   6382: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6383:   background: #FFAA99;
1.387     albertel 6384: }
1.795     www      6385: 
1.777     tempelho 6386: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6387:   background: #888888;
1.779     bisitz   6388: }
1.795     www      6389: 
1.777     tempelho 6390: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6391: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6392:   background: #F8F866;
1.777     tempelho 6393: }
1.795     www      6394: 
1.696     bisitz   6395: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6396:   background: #E0E8FF;
1.387     albertel 6397: }
1.696     bisitz   6398: 
1.707     bisitz   6399: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6400:   /* background: #77FF77; */
1.707     bisitz   6401: }
1.795     www      6402: 
1.707     bisitz   6403: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6404:   border-right: 8px solid #FFFF77;
1.707     bisitz   6405: }
1.795     www      6406: 
1.707     bisitz   6407: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6408:   border-right: 8px solid #FFAA77;
1.707     bisitz   6409: }
1.795     www      6410: 
1.707     bisitz   6411: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6412:   border-right: 8px solid #FF7777;
1.707     bisitz   6413: }
1.795     www      6414: 
1.707     bisitz   6415: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6416:   border-right: 8px solid #AAFF77;
1.707     bisitz   6417: }
1.795     www      6418: 
1.707     bisitz   6419: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6420:   border-right: 8px solid #11CC55;
1.707     bisitz   6421: }
                   6422: 
1.388     albertel 6423: span.LC_current_location {
1.701     harmsja  6424:   font-size:larger;
1.388     albertel 6425:   background: $pgbg;
                   6426: }
1.387     albertel 6427: 
1.1029    www      6428: span.LC_current_nav_location {
                   6429:   font-weight:bold;
                   6430:   background: $sidebg;
                   6431: }
                   6432: 
1.395     albertel 6433: span.LC_parm_menu_item {
                   6434:   font-size: larger;
                   6435: }
1.795     www      6436: 
1.395     albertel 6437: span.LC_parm_scope_all {
                   6438:   color: red;
                   6439: }
1.795     www      6440: 
1.395     albertel 6441: span.LC_parm_scope_folder {
                   6442:   color: green;
                   6443: }
1.795     www      6444: 
1.395     albertel 6445: span.LC_parm_scope_resource {
                   6446:   color: orange;
                   6447: }
1.795     www      6448: 
1.395     albertel 6449: span.LC_parm_part {
                   6450:   color: blue;
                   6451: }
1.795     www      6452: 
1.911     bisitz   6453: span.LC_parm_folder,
                   6454: span.LC_parm_symb {
1.395     albertel 6455:   font-size: x-small;
                   6456:   font-family: $mono;
                   6457:   color: #AAAAAA;
                   6458: }
                   6459: 
1.977     bisitz   6460: ul.LC_parm_parmlist li {
                   6461:   display: inline-block;
                   6462:   padding: 0.3em 0.8em;
                   6463:   vertical-align: top;
                   6464:   width: 150px;
                   6465:   border-top:1px solid $lg_border_color;
                   6466: }
                   6467: 
1.795     www      6468: td.LC_parm_overview_level_menu,
                   6469: td.LC_parm_overview_map_menu,
                   6470: td.LC_parm_overview_parm_selectors,
                   6471: td.LC_parm_overview_restrictions  {
1.396     albertel 6472:   border: 1px solid black;
                   6473:   border-collapse: collapse;
                   6474: }
1.795     www      6475: 
1.396     albertel 6476: table.LC_parm_overview_restrictions td {
                   6477:   border-width: 1px 4px 1px 4px;
                   6478:   border-style: solid;
                   6479:   border-color: $pgbg;
                   6480:   text-align: center;
                   6481: }
1.795     www      6482: 
1.396     albertel 6483: table.LC_parm_overview_restrictions th {
                   6484:   background: $tabbg;
                   6485:   border-width: 1px 4px 1px 4px;
                   6486:   border-style: solid;
                   6487:   border-color: $pgbg;
                   6488: }
1.795     www      6489: 
1.398     albertel 6490: table#LC_helpmenu {
1.803     bisitz   6491:   border: none;
1.398     albertel 6492:   height: 55px;
1.803     bisitz   6493:   border-spacing: 0;
1.398     albertel 6494: }
                   6495: 
                   6496: table#LC_helpmenu fieldset legend {
                   6497:   font-size: larger;
                   6498: }
1.795     www      6499: 
1.397     albertel 6500: table#LC_helpmenu_links {
                   6501:   width: 100%;
                   6502:   border: 1px solid black;
                   6503:   background: $pgbg;
1.803     bisitz   6504:   padding: 0;
1.397     albertel 6505:   border-spacing: 1px;
                   6506: }
1.795     www      6507: 
1.397     albertel 6508: table#LC_helpmenu_links tr td {
                   6509:   padding: 1px;
                   6510:   background: $tabbg;
1.399     albertel 6511:   text-align: center;
                   6512:   font-weight: bold;
1.397     albertel 6513: }
1.396     albertel 6514: 
1.795     www      6515: table#LC_helpmenu_links a:link,
                   6516: table#LC_helpmenu_links a:visited,
1.397     albertel 6517: table#LC_helpmenu_links a:active {
                   6518:   text-decoration: none;
                   6519:   color: $font;
                   6520: }
1.795     www      6521: 
1.397     albertel 6522: table#LC_helpmenu_links a:hover {
                   6523:   text-decoration: underline;
                   6524:   color: $vlink;
                   6525: }
1.396     albertel 6526: 
1.417     albertel 6527: .LC_chrt_popup_exists {
                   6528:   border: 1px solid #339933;
                   6529:   margin: -1px;
                   6530: }
1.795     www      6531: 
1.417     albertel 6532: .LC_chrt_popup_up {
                   6533:   border: 1px solid yellow;
                   6534:   margin: -1px;
                   6535: }
1.795     www      6536: 
1.417     albertel 6537: .LC_chrt_popup {
                   6538:   border: 1px solid #8888FF;
                   6539:   background: #CCCCFF;
                   6540: }
1.795     www      6541: 
1.421     albertel 6542: table.LC_pick_box {
                   6543:   border-collapse: separate;
                   6544:   background: white;
                   6545:   border: 1px solid black;
                   6546:   border-spacing: 1px;
                   6547: }
1.795     www      6548: 
1.421     albertel 6549: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6550:   background: $sidebg;
1.421     albertel 6551:   font-weight: bold;
1.900     bisitz   6552:   text-align: left;
1.740     bisitz   6553:   vertical-align: top;
1.421     albertel 6554:   width: 184px;
                   6555:   padding: 8px;
                   6556: }
1.795     www      6557: 
1.579     raeburn  6558: table.LC_pick_box td.LC_pick_box_value {
                   6559:   text-align: left;
                   6560:   padding: 8px;
                   6561: }
1.795     www      6562: 
1.579     raeburn  6563: table.LC_pick_box td.LC_pick_box_select {
                   6564:   text-align: left;
                   6565:   padding: 8px;
                   6566: }
1.795     www      6567: 
1.424     albertel 6568: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6569:   padding: 0;
1.421     albertel 6570:   height: 1px;
                   6571:   background: black;
                   6572: }
1.795     www      6573: 
1.421     albertel 6574: table.LC_pick_box td.LC_pick_box_submit {
                   6575:   text-align: right;
                   6576: }
1.795     www      6577: 
1.579     raeburn  6578: table.LC_pick_box td.LC_evenrow_value {
                   6579:   text-align: left;
                   6580:   padding: 8px;
                   6581:   background-color: $data_table_light;
                   6582: }
1.795     www      6583: 
1.579     raeburn  6584: table.LC_pick_box td.LC_oddrow_value {
                   6585:   text-align: left;
                   6586:   padding: 8px;
                   6587:   background-color: $data_table_light;
                   6588: }
1.795     www      6589: 
1.579     raeburn  6590: span.LC_helpform_receipt_cat {
                   6591:   font-weight: bold;
                   6592: }
1.795     www      6593: 
1.424     albertel 6594: table.LC_group_priv_box {
                   6595:   background: white;
                   6596:   border: 1px solid black;
                   6597:   border-spacing: 1px;
                   6598: }
1.795     www      6599: 
1.424     albertel 6600: table.LC_group_priv_box td.LC_pick_box_title {
                   6601:   background: $tabbg;
                   6602:   font-weight: bold;
                   6603:   text-align: right;
                   6604:   width: 184px;
                   6605: }
1.795     www      6606: 
1.424     albertel 6607: table.LC_group_priv_box td.LC_groups_fixed {
                   6608:   background: $data_table_light;
                   6609:   text-align: center;
                   6610: }
1.795     www      6611: 
1.424     albertel 6612: table.LC_group_priv_box td.LC_groups_optional {
                   6613:   background: $data_table_dark;
                   6614:   text-align: center;
                   6615: }
1.795     www      6616: 
1.424     albertel 6617: table.LC_group_priv_box td.LC_groups_functionality {
                   6618:   background: $data_table_darker;
                   6619:   text-align: center;
                   6620:   font-weight: bold;
                   6621: }
1.795     www      6622: 
1.424     albertel 6623: table.LC_group_priv td {
                   6624:   text-align: left;
1.803     bisitz   6625:   padding: 0;
1.424     albertel 6626: }
                   6627: 
                   6628: .LC_navbuttons {
                   6629:   margin: 2ex 0ex 2ex 0ex;
                   6630: }
1.795     www      6631: 
1.423     albertel 6632: .LC_topic_bar {
                   6633:   font-weight: bold;
                   6634:   background: $tabbg;
1.918     wenzelju 6635:   margin: 1em 0em 1em 2em;
1.805     bisitz   6636:   padding: 3px;
1.918     wenzelju 6637:   font-size: 1.2em;
1.423     albertel 6638: }
1.795     www      6639: 
1.423     albertel 6640: .LC_topic_bar span {
1.918     wenzelju 6641:   left: 0.5em;
                   6642:   position: absolute;
1.423     albertel 6643:   vertical-align: middle;
1.918     wenzelju 6644:   font-size: 1.2em;
1.423     albertel 6645: }
1.795     www      6646: 
1.423     albertel 6647: table.LC_course_group_status {
                   6648:   margin: 20px;
                   6649: }
1.795     www      6650: 
1.423     albertel 6651: table.LC_status_selector td {
                   6652:   vertical-align: top;
                   6653:   text-align: center;
1.424     albertel 6654:   padding: 4px;
                   6655: }
1.795     www      6656: 
1.599     albertel 6657: div.LC_feedback_link {
1.616     albertel 6658:   clear: both;
1.829     kalberla 6659:   background: $sidebg;
1.779     bisitz   6660:   width: 100%;
1.829     kalberla 6661:   padding-bottom: 10px;
                   6662:   border: 1px $tabbg solid;
1.833     kalberla 6663:   height: 22px;
                   6664:   line-height: 22px;
                   6665:   padding-top: 5px;
                   6666: }
                   6667: 
                   6668: div.LC_feedback_link img {
                   6669:   height: 22px;
1.867     kalberla 6670:   vertical-align:middle;
1.829     kalberla 6671: }
                   6672: 
1.911     bisitz   6673: div.LC_feedback_link a {
1.829     kalberla 6674:   text-decoration: none;
1.489     raeburn  6675: }
1.795     www      6676: 
1.867     kalberla 6677: div.LC_comblock {
1.911     bisitz   6678:   display:inline;
1.867     kalberla 6679:   color:$font;
                   6680:   font-size:90%;
                   6681: }
                   6682: 
                   6683: div.LC_feedback_link div.LC_comblock {
                   6684:   padding-left:5px;
                   6685: }
                   6686: 
                   6687: div.LC_feedback_link div.LC_comblock a {
                   6688:   color:$font;
                   6689: }
                   6690: 
1.489     raeburn  6691: span.LC_feedback_link {
1.858     bisitz   6692:   /* background: $feedback_link_bg; */
1.599     albertel 6693:   font-size: larger;
                   6694: }
1.795     www      6695: 
1.599     albertel 6696: span.LC_message_link {
1.858     bisitz   6697:   /* background: $feedback_link_bg; */
1.599     albertel 6698:   font-size: larger;
                   6699:   position: absolute;
                   6700:   right: 1em;
1.489     raeburn  6701: }
1.421     albertel 6702: 
1.515     albertel 6703: table.LC_prior_tries {
1.524     albertel 6704:   border: 1px solid #000000;
                   6705:   border-collapse: separate;
                   6706:   border-spacing: 1px;
1.515     albertel 6707: }
1.523     albertel 6708: 
1.515     albertel 6709: table.LC_prior_tries td {
1.524     albertel 6710:   padding: 2px;
1.515     albertel 6711: }
1.523     albertel 6712: 
                   6713: .LC_answer_correct {
1.795     www      6714:   background: lightgreen;
                   6715:   color: darkgreen;
                   6716:   padding: 6px;
1.523     albertel 6717: }
1.795     www      6718: 
1.523     albertel 6719: .LC_answer_charged_try {
1.797     www      6720:   background: #FFAAAA;
1.795     www      6721:   color: darkred;
                   6722:   padding: 6px;
1.523     albertel 6723: }
1.795     www      6724: 
1.779     bisitz   6725: .LC_answer_not_charged_try,
1.523     albertel 6726: .LC_answer_no_grade,
                   6727: .LC_answer_late {
1.795     www      6728:   background: lightyellow;
1.523     albertel 6729:   color: black;
1.795     www      6730:   padding: 6px;
1.523     albertel 6731: }
1.795     www      6732: 
1.523     albertel 6733: .LC_answer_previous {
1.795     www      6734:   background: lightblue;
                   6735:   color: darkblue;
                   6736:   padding: 6px;
1.523     albertel 6737: }
1.795     www      6738: 
1.779     bisitz   6739: .LC_answer_no_message {
1.777     tempelho 6740:   background: #FFFFFF;
                   6741:   color: black;
1.795     www      6742:   padding: 6px;
1.779     bisitz   6743: }
1.795     www      6744: 
1.779     bisitz   6745: .LC_answer_unknown {
                   6746:   background: orange;
                   6747:   color: black;
1.795     www      6748:   padding: 6px;
1.777     tempelho 6749: }
1.795     www      6750: 
1.529     albertel 6751: span.LC_prior_numerical,
                   6752: span.LC_prior_string,
                   6753: span.LC_prior_custom,
                   6754: span.LC_prior_reaction,
                   6755: span.LC_prior_math {
1.925     bisitz   6756:   font-family: $mono;
1.523     albertel 6757:   white-space: pre;
                   6758: }
                   6759: 
1.525     albertel 6760: span.LC_prior_string {
1.925     bisitz   6761:   font-family: $mono;
1.525     albertel 6762:   white-space: pre;
                   6763: }
                   6764: 
1.523     albertel 6765: table.LC_prior_option {
                   6766:   width: 100%;
                   6767:   border-collapse: collapse;
                   6768: }
1.795     www      6769: 
1.911     bisitz   6770: table.LC_prior_rank,
1.795     www      6771: table.LC_prior_match {
1.528     albertel 6772:   border-collapse: collapse;
                   6773: }
1.795     www      6774: 
1.528     albertel 6775: table.LC_prior_option tr td,
                   6776: table.LC_prior_rank tr td,
                   6777: table.LC_prior_match tr td {
1.524     albertel 6778:   border: 1px solid #000000;
1.515     albertel 6779: }
                   6780: 
1.855     bisitz   6781: .LC_nobreak {
1.544     albertel 6782:   white-space: nowrap;
1.519     raeburn  6783: }
                   6784: 
1.576     raeburn  6785: span.LC_cusr_emph {
                   6786:   font-style: italic;
                   6787: }
                   6788: 
1.633     raeburn  6789: span.LC_cusr_subheading {
                   6790:   font-weight: normal;
                   6791:   font-size: 85%;
                   6792: }
                   6793: 
1.861     bisitz   6794: div.LC_docs_entry_move {
1.859     bisitz   6795:   border: 1px solid #BBBBBB;
1.545     albertel 6796:   background: #DDDDDD;
1.861     bisitz   6797:   width: 22px;
1.859     bisitz   6798:   padding: 1px;
                   6799:   margin: 0;
1.545     albertel 6800: }
                   6801: 
1.861     bisitz   6802: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6803: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6804:   font-size: x-small;
                   6805: }
1.795     www      6806: 
1.861     bisitz   6807: .LC_docs_entry_parameter {
                   6808:   white-space: nowrap;
                   6809: }
                   6810: 
1.544     albertel 6811: .LC_docs_copy {
1.545     albertel 6812:   color: #000099;
1.544     albertel 6813: }
1.795     www      6814: 
1.544     albertel 6815: .LC_docs_cut {
1.545     albertel 6816:   color: #550044;
1.544     albertel 6817: }
1.795     www      6818: 
1.544     albertel 6819: .LC_docs_rename {
1.545     albertel 6820:   color: #009900;
1.544     albertel 6821: }
1.795     www      6822: 
1.544     albertel 6823: .LC_docs_remove {
1.545     albertel 6824:   color: #990000;
                   6825: }
                   6826: 
1.547     albertel 6827: .LC_docs_reinit_warn,
                   6828: .LC_docs_ext_edit {
                   6829:   font-size: x-small;
                   6830: }
                   6831: 
1.545     albertel 6832: table.LC_docs_adddocs td,
                   6833: table.LC_docs_adddocs th {
                   6834:   border: 1px solid #BBBBBB;
                   6835:   padding: 4px;
                   6836:   background: #DDDDDD;
1.543     albertel 6837: }
                   6838: 
1.584     albertel 6839: table.LC_sty_begin {
                   6840:   background: #BBFFBB;
                   6841: }
1.795     www      6842: 
1.584     albertel 6843: table.LC_sty_end {
                   6844:   background: #FFBBBB;
                   6845: }
                   6846: 
1.589     raeburn  6847: table.LC_double_column {
1.803     bisitz   6848:   border-width: 0;
1.589     raeburn  6849:   border-collapse: collapse;
                   6850:   width: 100%;
                   6851:   padding: 2px;
                   6852: }
                   6853: 
                   6854: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6855:   top: 2px;
1.589     raeburn  6856:   left: 2px;
                   6857:   width: 47%;
                   6858:   vertical-align: top;
                   6859: }
                   6860: 
                   6861: table.LC_double_column tr td.LC_right_col {
                   6862:   top: 2px;
1.779     bisitz   6863:   right: 2px;
1.589     raeburn  6864:   width: 47%;
                   6865:   vertical-align: top;
                   6866: }
                   6867: 
1.591     raeburn  6868: div.LC_left_float {
                   6869:   float: left;
                   6870:   padding-right: 5%;
1.597     albertel 6871:   padding-bottom: 4px;
1.591     raeburn  6872: }
                   6873: 
                   6874: div.LC_clear_float_header {
1.597     albertel 6875:   padding-bottom: 2px;
1.591     raeburn  6876: }
                   6877: 
                   6878: div.LC_clear_float_footer {
1.597     albertel 6879:   padding-top: 10px;
1.591     raeburn  6880:   clear: both;
                   6881: }
                   6882: 
1.597     albertel 6883: div.LC_grade_show_user {
1.941     bisitz   6884: /*  border-left: 5px solid $sidebg; */
                   6885:   border-top: 5px solid #000000;
                   6886:   margin: 50px 0 0 0;
1.936     bisitz   6887:   padding: 15px 0 5px 10px;
1.597     albertel 6888: }
1.795     www      6889: 
1.936     bisitz   6890: div.LC_grade_show_user_odd_row {
1.941     bisitz   6891: /*  border-left: 5px solid #000000; */
                   6892: }
                   6893: 
                   6894: div.LC_grade_show_user div.LC_Box {
                   6895:   margin-right: 50px;
1.597     albertel 6896: }
                   6897: 
                   6898: div.LC_grade_submissions,
                   6899: div.LC_grade_message_center,
1.936     bisitz   6900: div.LC_grade_info_links {
1.597     albertel 6901:   margin: 5px;
                   6902:   width: 99%;
                   6903:   background: #FFFFFF;
                   6904: }
1.795     www      6905: 
1.597     albertel 6906: div.LC_grade_submissions_header,
1.936     bisitz   6907: div.LC_grade_message_center_header {
1.705     tempelho 6908:   font-weight: bold;
                   6909:   font-size: large;
1.597     albertel 6910: }
1.795     www      6911: 
1.597     albertel 6912: div.LC_grade_submissions_body,
1.936     bisitz   6913: div.LC_grade_message_center_body {
1.597     albertel 6914:   border: 1px solid black;
                   6915:   width: 99%;
                   6916:   background: #FFFFFF;
                   6917: }
1.795     www      6918: 
1.613     albertel 6919: table.LC_scantron_action {
                   6920:   width: 100%;
                   6921: }
1.795     www      6922: 
1.613     albertel 6923: table.LC_scantron_action tr th {
1.698     harmsja  6924:   font-weight:bold;
                   6925:   font-style:normal;
1.613     albertel 6926: }
1.795     www      6927: 
1.779     bisitz   6928: .LC_edit_problem_header,
1.614     albertel 6929: div.LC_edit_problem_footer {
1.705     tempelho 6930:   font-weight: normal;
                   6931:   font-size:  medium;
1.602     albertel 6932:   margin: 2px;
1.1060    bisitz   6933:   background-color: $sidebg;
1.600     albertel 6934: }
1.795     www      6935: 
1.600     albertel 6936: div.LC_edit_problem_header,
1.602     albertel 6937: div.LC_edit_problem_header div,
1.614     albertel 6938: div.LC_edit_problem_footer,
                   6939: div.LC_edit_problem_footer div,
1.602     albertel 6940: div.LC_edit_problem_editxml_header,
                   6941: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  6942:   z-index: 100;
1.600     albertel 6943: }
1.795     www      6944: 
1.600     albertel 6945: div.LC_edit_problem_header_title {
1.705     tempelho 6946:   font-weight: bold;
                   6947:   font-size: larger;
1.602     albertel 6948:   background: $tabbg;
                   6949:   padding: 3px;
1.1060    bisitz   6950:   margin: 0 0 5px 0;
1.602     albertel 6951: }
1.795     www      6952: 
1.602     albertel 6953: table.LC_edit_problem_header_title {
                   6954:   width: 100%;
1.600     albertel 6955:   background: $tabbg;
1.602     albertel 6956: }
                   6957: 
1.1075.2.112  raeburn  6958: div.LC_edit_actionbar {
                   6959:     background-color: $sidebg;
                   6960:     margin: 0;
                   6961:     padding: 0;
                   6962:     line-height: 200%;
1.602     albertel 6963: }
1.795     www      6964: 
1.1075.2.112  raeburn  6965: div.LC_edit_actionbar div{
                   6966:     padding: 0;
                   6967:     margin: 0;
                   6968:     display: inline-block;
1.600     albertel 6969: }
1.795     www      6970: 
1.1075.2.34  raeburn  6971: .LC_edit_opt {
                   6972:   padding-left: 1em;
                   6973:   white-space: nowrap;
                   6974: }
                   6975: 
1.1075.2.57  raeburn  6976: .LC_edit_problem_latexhelper{
                   6977:     text-align: right;
                   6978: }
                   6979: 
                   6980: #LC_edit_problem_colorful div{
                   6981:     margin-left: 40px;
                   6982: }
                   6983: 
1.1075.2.112  raeburn  6984: #LC_edit_problem_codemirror div{
                   6985:     margin-left: 0px;
                   6986: }
                   6987: 
1.911     bisitz   6988: img.stift {
1.803     bisitz   6989:   border-width: 0;
                   6990:   vertical-align: middle;
1.677     riegler  6991: }
1.680     riegler  6992: 
1.923     bisitz   6993: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6994:   vertical-align: top;
1.777     tempelho 6995: }
1.795     www      6996: 
1.716     raeburn  6997: div.LC_createcourse {
1.911     bisitz   6998:   margin: 10px 10px 10px 10px;
1.716     raeburn  6999: }
                   7000: 
1.917     raeburn  7001: .LC_dccid {
1.1075.2.38  raeburn  7002:   float: right;
1.917     raeburn  7003:   margin: 0.2em 0 0 0;
                   7004:   padding: 0;
                   7005:   font-size: 90%;
                   7006:   display:none;
                   7007: }
                   7008: 
1.897     wenzelju 7009: ol.LC_primary_menu a:hover,
1.721     harmsja  7010: ol#LC_MenuBreadcrumbs a:hover,
                   7011: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7012: ul#LC_secondary_menu a:hover,
1.721     harmsja  7013: .LC_FormSectionClearButton input:hover
1.795     www      7014: ul.LC_TabContent   li:hover a {
1.952     onken    7015:   color:$button_hover;
1.911     bisitz   7016:   text-decoration:none;
1.693     droeschl 7017: }
                   7018: 
1.779     bisitz   7019: h1 {
1.911     bisitz   7020:   padding: 0;
                   7021:   line-height:130%;
1.693     droeschl 7022: }
1.698     harmsja  7023: 
1.911     bisitz   7024: h2,
                   7025: h3,
                   7026: h4,
                   7027: h5,
                   7028: h6 {
                   7029:   margin: 5px 0 5px 0;
                   7030:   padding: 0;
                   7031:   line-height:130%;
1.693     droeschl 7032: }
1.795     www      7033: 
                   7034: .LC_hcell {
1.911     bisitz   7035:   padding:3px 15px 3px 15px;
                   7036:   margin: 0;
                   7037:   background-color:$tabbg;
                   7038:   color:$fontmenu;
                   7039:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7040: }
1.795     www      7041: 
1.840     bisitz   7042: .LC_Box > .LC_hcell {
1.911     bisitz   7043:   margin: 0 -10px 10px -10px;
1.835     bisitz   7044: }
                   7045: 
1.721     harmsja  7046: .LC_noBorder {
1.911     bisitz   7047:   border: 0;
1.698     harmsja  7048: }
1.693     droeschl 7049: 
1.721     harmsja  7050: .LC_FormSectionClearButton input {
1.911     bisitz   7051:   background-color:transparent;
                   7052:   border: none;
                   7053:   cursor:pointer;
                   7054:   text-decoration:underline;
1.693     droeschl 7055: }
1.763     bisitz   7056: 
                   7057: .LC_help_open_topic {
1.911     bisitz   7058:   color: #FFFFFF;
                   7059:   background-color: #EEEEFF;
                   7060:   margin: 1px;
                   7061:   padding: 4px;
                   7062:   border: 1px solid #000033;
                   7063:   white-space: nowrap;
                   7064:   /* vertical-align: middle; */
1.759     neumanie 7065: }
1.693     droeschl 7066: 
1.911     bisitz   7067: dl,
                   7068: ul,
                   7069: div,
                   7070: fieldset {
                   7071:   margin: 10px 10px 10px 0;
                   7072:   /* overflow: hidden; */
1.693     droeschl 7073: }
1.795     www      7074: 
1.1075.2.90  raeburn  7075: article.geogebraweb div {
                   7076:     margin: 0;
                   7077: }
                   7078: 
1.838     bisitz   7079: fieldset > legend {
1.911     bisitz   7080:   font-weight: bold;
                   7081:   padding: 0 5px 0 5px;
1.838     bisitz   7082: }
                   7083: 
1.813     bisitz   7084: #LC_nav_bar {
1.911     bisitz   7085:   float: left;
1.995     raeburn  7086:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7087:   margin: 0 0 2px 0;
1.807     droeschl 7088: }
                   7089: 
1.916     droeschl 7090: #LC_realm {
                   7091:   margin: 0.2em 0 0 0;
                   7092:   padding: 0;
                   7093:   font-weight: bold;
                   7094:   text-align: center;
1.995     raeburn  7095:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7096: }
                   7097: 
1.911     bisitz   7098: #LC_nav_bar em {
                   7099:   font-weight: bold;
                   7100:   font-style: normal;
1.807     droeschl 7101: }
                   7102: 
1.897     wenzelju 7103: ol.LC_primary_menu {
1.934     droeschl 7104:   margin: 0;
1.1075.2.2  raeburn  7105:   padding: 0;
1.807     droeschl 7106: }
                   7107: 
1.852     droeschl 7108: ol#LC_PathBreadcrumbs {
1.911     bisitz   7109:   margin: 0;
1.693     droeschl 7110: }
                   7111: 
1.897     wenzelju 7112: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7113:   color: RGB(80, 80, 80);
                   7114:   vertical-align: middle;
                   7115:   text-align: left;
                   7116:   list-style: none;
1.1075.2.112  raeburn  7117:   position: relative;
1.1075.2.2  raeburn  7118:   float: left;
1.1075.2.112  raeburn  7119:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7120:   line-height: 1.5em;
1.1075.2.2  raeburn  7121: }
                   7122: 
1.1075.2.113  raeburn  7123: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7124: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7125:   display: block;
                   7126:   margin: 0;
                   7127:   padding: 0 5px 0 10px;
                   7128:   text-decoration: none;
                   7129: }
                   7130: 
1.1075.2.112  raeburn  7131: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7132:   display: inline-block;
                   7133:   width: 95%;
                   7134:   text-align: left;
                   7135: }
                   7136: 
                   7137: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7138:   display: inline-block;
                   7139:   width: 5%;
                   7140:   float: right;
                   7141:   text-align: right;
                   7142:   font-size: 70%;
                   7143: }
                   7144: 
                   7145: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7146:   display: none;
1.1075.2.112  raeburn  7147:   width: 15em;
1.1075.2.2  raeburn  7148:   background-color: $data_table_light;
1.1075.2.112  raeburn  7149:   position: absolute;
                   7150:   top: 100%;
                   7151: }
                   7152: 
                   7153: ol.LC_primary_menu ul ul {
                   7154:   left: 100%;
                   7155:   top: 0;
1.1075.2.2  raeburn  7156: }
                   7157: 
1.1075.2.112  raeburn  7158: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7159:   display: block;
                   7160:   position: absolute;
                   7161:   margin: 0;
                   7162:   padding: 0;
1.1075.2.5  raeburn  7163:   z-index: 2;
1.1075.2.2  raeburn  7164: }
                   7165: 
                   7166: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7167: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7168:   font-size: 90%;
1.911     bisitz   7169:   vertical-align: top;
1.1075.2.2  raeburn  7170:   float: none;
1.1075.2.5  raeburn  7171:   border-left: 1px solid black;
                   7172:   border-right: 1px solid black;
1.1075.2.112  raeburn  7173: /* A dark bottom border to visualize different menu options;
                   7174: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7175:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7176: }
                   7177: 
1.1075.2.112  raeburn  7178: ol.LC_primary_menu li li p:hover {
                   7179:   color:$button_hover;
                   7180:   text-decoration:none;
                   7181:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7182: }
                   7183: 
                   7184: ol.LC_primary_menu li li a:hover {
                   7185:    color:$button_hover;
                   7186:    background-color:$data_table_dark;
1.693     droeschl 7187: }
                   7188: 
1.1075.2.112  raeburn  7189: /* Font-size equal to the size of the predecessors*/
                   7190: ol.LC_primary_menu li:hover li li {
                   7191:   font-size: 100%;
                   7192: }
                   7193: 
1.897     wenzelju 7194: ol.LC_primary_menu li img {
1.911     bisitz   7195:   vertical-align: bottom;
1.934     droeschl 7196:   height: 1.1em;
1.1075.2.3  raeburn  7197:   margin: 0.2em 0 0 0;
1.693     droeschl 7198: }
                   7199: 
1.897     wenzelju 7200: ol.LC_primary_menu a {
1.911     bisitz   7201:   color: RGB(80, 80, 80);
                   7202:   text-decoration: none;
1.693     droeschl 7203: }
1.795     www      7204: 
1.949     droeschl 7205: ol.LC_primary_menu a.LC_new_message {
                   7206:   font-weight:bold;
                   7207:   color: darkred;
                   7208: }
                   7209: 
1.975     raeburn  7210: ol.LC_docs_parameters {
                   7211:   margin-left: 0;
                   7212:   padding: 0;
                   7213:   list-style: none;
                   7214: }
                   7215: 
                   7216: ol.LC_docs_parameters li {
                   7217:   margin: 0;
                   7218:   padding-right: 20px;
                   7219:   display: inline;
                   7220: }
                   7221: 
1.976     raeburn  7222: ol.LC_docs_parameters li:before {
                   7223:   content: "\\002022 \\0020";
                   7224: }
                   7225: 
                   7226: li.LC_docs_parameters_title {
                   7227:   font-weight: bold;
                   7228: }
                   7229: 
                   7230: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7231:   content: "";
                   7232: }
                   7233: 
1.897     wenzelju 7234: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7235:   clear: right;
1.911     bisitz   7236:   color: $fontmenu;
                   7237:   background: $tabbg;
                   7238:   list-style: none;
                   7239:   padding: 0;
                   7240:   margin: 0;
                   7241:   width: 100%;
1.995     raeburn  7242:   text-align: left;
1.1075.2.4  raeburn  7243:   float: left;
1.808     droeschl 7244: }
                   7245: 
1.897     wenzelju 7246: ul#LC_secondary_menu li {
1.911     bisitz   7247:   font-weight: bold;
                   7248:   line-height: 1.8em;
                   7249:   border-right: 1px solid black;
1.1075.2.4  raeburn  7250:   float: left;
                   7251: }
                   7252: 
                   7253: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7254:   background-color: $data_table_light;
                   7255: }
                   7256: 
                   7257: ul#LC_secondary_menu li a {
                   7258:   padding: 0 0.8em;
                   7259: }
                   7260: 
                   7261: ul#LC_secondary_menu li ul {
                   7262:   display: none;
                   7263: }
                   7264: 
                   7265: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7266:   display: block;
                   7267:   position: absolute;
                   7268:   margin: 0;
                   7269:   padding: 0;
                   7270:   list-style:none;
                   7271:   float: none;
                   7272:   background-color: $data_table_light;
1.1075.2.5  raeburn  7273:   z-index: 2;
1.1075.2.10  raeburn  7274:   margin-left: -1px;
1.1075.2.4  raeburn  7275: }
                   7276: 
                   7277: ul#LC_secondary_menu li ul li {
                   7278:   font-size: 90%;
                   7279:   vertical-align: top;
                   7280:   border-left: 1px solid black;
                   7281:   border-right: 1px solid black;
1.1075.2.33  raeburn  7282:   background-color: $data_table_light;
1.1075.2.4  raeburn  7283:   list-style:none;
                   7284:   float: none;
                   7285: }
                   7286: 
                   7287: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7288:   background-color: $data_table_dark;
1.807     droeschl 7289: }
                   7290: 
1.847     tempelho 7291: ul.LC_TabContent {
1.911     bisitz   7292:   display:block;
                   7293:   background: $sidebg;
                   7294:   border-bottom: solid 1px $lg_border_color;
                   7295:   list-style:none;
1.1020    raeburn  7296:   margin: -1px -10px 0 -10px;
1.911     bisitz   7297:   padding: 0;
1.693     droeschl 7298: }
                   7299: 
1.795     www      7300: ul.LC_TabContent li,
                   7301: ul.LC_TabContentBigger li {
1.911     bisitz   7302:   float:left;
1.741     harmsja  7303: }
1.795     www      7304: 
1.897     wenzelju 7305: ul#LC_secondary_menu li a {
1.911     bisitz   7306:   color: $fontmenu;
                   7307:   text-decoration: none;
1.693     droeschl 7308: }
1.795     www      7309: 
1.721     harmsja  7310: ul.LC_TabContent {
1.952     onken    7311:   min-height:20px;
1.721     harmsja  7312: }
1.795     www      7313: 
                   7314: ul.LC_TabContent li {
1.911     bisitz   7315:   vertical-align:middle;
1.959     onken    7316:   padding: 0 16px 0 10px;
1.911     bisitz   7317:   background-color:$tabbg;
                   7318:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7319:   border-left: solid 1px $font;
1.721     harmsja  7320: }
1.795     www      7321: 
1.847     tempelho 7322: ul.LC_TabContent .right {
1.911     bisitz   7323:   float:right;
1.847     tempelho 7324: }
                   7325: 
1.911     bisitz   7326: ul.LC_TabContent li a,
                   7327: ul.LC_TabContent li {
                   7328:   color:rgb(47,47,47);
                   7329:   text-decoration:none;
                   7330:   font-size:95%;
                   7331:   font-weight:bold;
1.952     onken    7332:   min-height:20px;
                   7333: }
                   7334: 
1.959     onken    7335: ul.LC_TabContent li a:hover,
                   7336: ul.LC_TabContent li a:focus {
1.952     onken    7337:   color: $button_hover;
1.959     onken    7338:   background:none;
                   7339:   outline:none;
1.952     onken    7340: }
                   7341: 
                   7342: ul.LC_TabContent li:hover {
                   7343:   color: $button_hover;
                   7344:   cursor:pointer;
1.721     harmsja  7345: }
1.795     www      7346: 
1.911     bisitz   7347: ul.LC_TabContent li.active {
1.952     onken    7348:   color: $font;
1.911     bisitz   7349:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7350:   border-bottom:solid 1px #FFFFFF;
                   7351:   cursor: default;
1.744     ehlerst  7352: }
1.795     www      7353: 
1.959     onken    7354: ul.LC_TabContent li.active a {
                   7355:   color:$font;
                   7356:   background:#FFFFFF;
                   7357:   outline: none;
                   7358: }
1.1047    raeburn  7359: 
                   7360: ul.LC_TabContent li.goback {
                   7361:   float: left;
                   7362:   border-left: none;
                   7363: }
                   7364: 
1.870     tempelho 7365: #maincoursedoc {
1.911     bisitz   7366:   clear:both;
1.870     tempelho 7367: }
                   7368: 
                   7369: ul.LC_TabContentBigger {
1.911     bisitz   7370:   display:block;
                   7371:   list-style:none;
                   7372:   padding: 0;
1.870     tempelho 7373: }
                   7374: 
1.795     www      7375: ul.LC_TabContentBigger li {
1.911     bisitz   7376:   vertical-align:bottom;
                   7377:   height: 30px;
                   7378:   font-size:110%;
                   7379:   font-weight:bold;
                   7380:   color: #737373;
1.841     tempelho 7381: }
                   7382: 
1.957     onken    7383: ul.LC_TabContentBigger li.active {
                   7384:   position: relative;
                   7385:   top: 1px;
                   7386: }
                   7387: 
1.870     tempelho 7388: ul.LC_TabContentBigger li a {
1.911     bisitz   7389:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7390:   height: 30px;
                   7391:   line-height: 30px;
                   7392:   text-align: center;
                   7393:   display: block;
                   7394:   text-decoration: none;
1.958     onken    7395:   outline: none;  
1.741     harmsja  7396: }
1.795     www      7397: 
1.870     tempelho 7398: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7399:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7400:   color:$font;
1.744     ehlerst  7401: }
1.795     www      7402: 
1.870     tempelho 7403: ul.LC_TabContentBigger li b {
1.911     bisitz   7404:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7405:   display: block;
                   7406:   float: left;
                   7407:   padding: 0 30px;
1.957     onken    7408:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7409: }
                   7410: 
1.956     onken    7411: ul.LC_TabContentBigger li:hover b {
                   7412:   color:$button_hover;
                   7413: }
                   7414: 
1.870     tempelho 7415: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7416:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7417:   color:$font;
1.957     onken    7418:   border: 0;
1.741     harmsja  7419: }
1.693     droeschl 7420: 
1.870     tempelho 7421: 
1.862     bisitz   7422: ul.LC_CourseBreadcrumbs {
                   7423:   background: $sidebg;
1.1020    raeburn  7424:   height: 2em;
1.862     bisitz   7425:   padding-left: 10px;
1.1020    raeburn  7426:   margin: 0;
1.862     bisitz   7427:   list-style-position: inside;
                   7428: }
                   7429: 
1.911     bisitz   7430: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7431: ol#LC_PathBreadcrumbs {
1.911     bisitz   7432:   padding-left: 10px;
                   7433:   margin: 0;
1.933     droeschl 7434:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7435: }
                   7436: 
1.911     bisitz   7437: ol#LC_MenuBreadcrumbs li,
                   7438: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7439: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7440:   display: inline;
1.933     droeschl 7441:   white-space: normal;  
1.693     droeschl 7442: }
                   7443: 
1.823     bisitz   7444: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7445: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7446:   text-decoration: none;
                   7447:   font-size:90%;
1.693     droeschl 7448: }
1.795     www      7449: 
1.969     droeschl 7450: ol#LC_MenuBreadcrumbs h1 {
                   7451:   display: inline;
                   7452:   font-size: 90%;
                   7453:   line-height: 2.5em;
                   7454:   margin: 0;
                   7455:   padding: 0;
                   7456: }
                   7457: 
1.795     www      7458: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7459:   text-decoration:none;
                   7460:   font-size:100%;
                   7461:   font-weight:bold;
1.693     droeschl 7462: }
1.795     www      7463: 
1.840     bisitz   7464: .LC_Box {
1.911     bisitz   7465:   border: solid 1px $lg_border_color;
                   7466:   padding: 0 10px 10px 10px;
1.746     neumanie 7467: }
1.795     www      7468: 
1.1020    raeburn  7469: .LC_DocsBox {
                   7470:   border: solid 1px $lg_border_color;
                   7471:   padding: 0 0 10px 10px;
                   7472: }
                   7473: 
1.795     www      7474: .LC_AboutMe_Image {
1.911     bisitz   7475:   float:left;
                   7476:   margin-right:10px;
1.747     neumanie 7477: }
1.795     www      7478: 
                   7479: .LC_Clear_AboutMe_Image {
1.911     bisitz   7480:   clear:left;
1.747     neumanie 7481: }
1.795     www      7482: 
1.721     harmsja  7483: dl.LC_ListStyleClean dt {
1.911     bisitz   7484:   padding-right: 5px;
                   7485:   display: table-header-group;
1.693     droeschl 7486: }
                   7487: 
1.721     harmsja  7488: dl.LC_ListStyleClean dd {
1.911     bisitz   7489:   display: table-row;
1.693     droeschl 7490: }
                   7491: 
1.721     harmsja  7492: .LC_ListStyleClean,
                   7493: .LC_ListStyleSimple,
                   7494: .LC_ListStyleNormal,
1.795     www      7495: .LC_ListStyleSpecial {
1.911     bisitz   7496:   /* display:block; */
                   7497:   list-style-position: inside;
                   7498:   list-style-type: none;
                   7499:   overflow: hidden;
                   7500:   padding: 0;
1.693     droeschl 7501: }
                   7502: 
1.721     harmsja  7503: .LC_ListStyleSimple li,
                   7504: .LC_ListStyleSimple dd,
                   7505: .LC_ListStyleNormal li,
                   7506: .LC_ListStyleNormal dd,
                   7507: .LC_ListStyleSpecial li,
1.795     www      7508: .LC_ListStyleSpecial dd {
1.911     bisitz   7509:   margin: 0;
                   7510:   padding: 5px 5px 5px 10px;
                   7511:   clear: both;
1.693     droeschl 7512: }
                   7513: 
1.721     harmsja  7514: .LC_ListStyleClean li,
                   7515: .LC_ListStyleClean dd {
1.911     bisitz   7516:   padding-top: 0;
                   7517:   padding-bottom: 0;
1.693     droeschl 7518: }
                   7519: 
1.721     harmsja  7520: .LC_ListStyleSimple dd,
1.795     www      7521: .LC_ListStyleSimple li {
1.911     bisitz   7522:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7523: }
                   7524: 
1.721     harmsja  7525: .LC_ListStyleSpecial li,
                   7526: .LC_ListStyleSpecial dd {
1.911     bisitz   7527:   list-style-type: none;
                   7528:   background-color: RGB(220, 220, 220);
                   7529:   margin-bottom: 4px;
1.693     droeschl 7530: }
                   7531: 
1.721     harmsja  7532: table.LC_SimpleTable {
1.911     bisitz   7533:   margin:5px;
                   7534:   border:solid 1px $lg_border_color;
1.795     www      7535: }
1.693     droeschl 7536: 
1.721     harmsja  7537: table.LC_SimpleTable tr {
1.911     bisitz   7538:   padding: 0;
                   7539:   border:solid 1px $lg_border_color;
1.693     droeschl 7540: }
1.795     www      7541: 
                   7542: table.LC_SimpleTable thead {
1.911     bisitz   7543:   background:rgb(220,220,220);
1.693     droeschl 7544: }
                   7545: 
1.721     harmsja  7546: div.LC_columnSection {
1.911     bisitz   7547:   display: block;
                   7548:   clear: both;
                   7549:   overflow: hidden;
                   7550:   margin: 0;
1.693     droeschl 7551: }
                   7552: 
1.721     harmsja  7553: div.LC_columnSection>* {
1.911     bisitz   7554:   float: left;
                   7555:   margin: 10px 20px 10px 0;
                   7556:   overflow:hidden;
1.693     droeschl 7557: }
1.721     harmsja  7558: 
1.795     www      7559: table em {
1.911     bisitz   7560:   font-weight: bold;
                   7561:   font-style: normal;
1.748     schulted 7562: }
1.795     www      7563: 
1.779     bisitz   7564: table.LC_tableBrowseRes,
1.795     www      7565: table.LC_tableOfContent {
1.911     bisitz   7566:   border:none;
                   7567:   border-spacing: 1px;
                   7568:   padding: 3px;
                   7569:   background-color: #FFFFFF;
                   7570:   font-size: 90%;
1.753     droeschl 7571: }
1.789     droeschl 7572: 
1.911     bisitz   7573: table.LC_tableOfContent {
                   7574:   border-collapse: collapse;
1.789     droeschl 7575: }
                   7576: 
1.771     droeschl 7577: table.LC_tableBrowseRes a,
1.768     schulted 7578: table.LC_tableOfContent a {
1.911     bisitz   7579:   background-color: transparent;
                   7580:   text-decoration: none;
1.753     droeschl 7581: }
                   7582: 
1.795     www      7583: table.LC_tableOfContent img {
1.911     bisitz   7584:   border: none;
                   7585:   height: 1.3em;
                   7586:   vertical-align: text-bottom;
                   7587:   margin-right: 0.3em;
1.753     droeschl 7588: }
1.757     schulted 7589: 
1.795     www      7590: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7591:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7592: }
                   7593: 
1.795     www      7594: a#LC_content_toolbar_everything {
1.911     bisitz   7595:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7596: }
                   7597: 
1.795     www      7598: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7599:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7600: }
                   7601: 
1.795     www      7602: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7603:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7604: }
                   7605: 
1.795     www      7606: a#LC_content_toolbar_changefolder {
1.911     bisitz   7607:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7608: }
                   7609: 
1.795     www      7610: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7611:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7612: }
                   7613: 
1.1043    raeburn  7614: a#LC_content_toolbar_edittoplevel {
                   7615:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7616: }
                   7617: 
1.795     www      7618: ul#LC_toolbar li a:hover {
1.911     bisitz   7619:   background-position: bottom center;
1.757     schulted 7620: }
                   7621: 
1.795     www      7622: ul#LC_toolbar {
1.911     bisitz   7623:   padding: 0;
                   7624:   margin: 2px;
                   7625:   list-style:none;
                   7626:   position:relative;
                   7627:   background-color:white;
1.1075.2.9  raeburn  7628:   overflow: auto;
1.757     schulted 7629: }
                   7630: 
1.795     www      7631: ul#LC_toolbar li {
1.911     bisitz   7632:   border:1px solid white;
                   7633:   padding: 0;
                   7634:   margin: 0;
                   7635:   float: left;
                   7636:   display:inline;
                   7637:   vertical-align:middle;
1.1075.2.9  raeburn  7638:   white-space: nowrap;
1.911     bisitz   7639: }
1.757     schulted 7640: 
1.783     amueller 7641: 
1.795     www      7642: a.LC_toolbarItem {
1.911     bisitz   7643:   display:block;
                   7644:   padding: 0;
                   7645:   margin: 0;
                   7646:   height: 32px;
                   7647:   width: 32px;
                   7648:   color:white;
                   7649:   border: none;
                   7650:   background-repeat:no-repeat;
                   7651:   background-color:transparent;
1.757     schulted 7652: }
                   7653: 
1.915     droeschl 7654: ul.LC_funclist {
                   7655:     margin: 0;
                   7656:     padding: 0.5em 1em 0.5em 0;
                   7657: }
                   7658: 
1.933     droeschl 7659: ul.LC_funclist > li:first-child {
                   7660:     font-weight:bold; 
                   7661:     margin-left:0.8em;
                   7662: }
                   7663: 
1.915     droeschl 7664: ul.LC_funclist + ul.LC_funclist {
                   7665:     /* 
                   7666:        left border as a seperator if we have more than
                   7667:        one list 
                   7668:     */
                   7669:     border-left: 1px solid $sidebg;
                   7670:     /* 
                   7671:        this hides the left border behind the border of the 
                   7672:        outer box if element is wrapped to the next 'line' 
                   7673:     */
                   7674:     margin-left: -1px;
                   7675: }
                   7676: 
1.843     bisitz   7677: ul.LC_funclist li {
1.915     droeschl 7678:   display: inline;
1.782     bisitz   7679:   white-space: nowrap;
1.915     droeschl 7680:   margin: 0 0 0 25px;
                   7681:   line-height: 150%;
1.782     bisitz   7682: }
                   7683: 
1.974     wenzelju 7684: .LC_hidden {
                   7685:   display: none;
                   7686: }
                   7687: 
1.1030    www      7688: .LCmodal-overlay {
                   7689: 		position:fixed;
                   7690: 		top:0;
                   7691: 		right:0;
                   7692: 		bottom:0;
                   7693: 		left:0;
                   7694: 		height:100%;
                   7695: 		width:100%;
                   7696: 		margin:0;
                   7697: 		padding:0;
                   7698: 		background:#999;
                   7699: 		opacity:.75;
                   7700: 		filter: alpha(opacity=75);
                   7701: 		-moz-opacity: 0.75;
                   7702: 		z-index:101;
                   7703: }
                   7704: 
                   7705: * html .LCmodal-overlay {   
                   7706: 		position: absolute;
                   7707: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7708: }
                   7709: 
                   7710: .LCmodal-window {
                   7711: 		position:fixed;
                   7712: 		top:50%;
                   7713: 		left:50%;
                   7714: 		margin:0;
                   7715: 		padding:0;
                   7716: 		z-index:102;
                   7717: 	}
                   7718: 
                   7719: * html .LCmodal-window {
                   7720: 		position:absolute;
                   7721: }
                   7722: 
                   7723: .LCclose-window {
                   7724: 		position:absolute;
                   7725: 		width:32px;
                   7726: 		height:32px;
                   7727: 		right:8px;
                   7728: 		top:8px;
                   7729: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7730: 		text-indent:-99999px;
                   7731: 		overflow:hidden;
                   7732: 		cursor:pointer;
                   7733: }
                   7734: 
1.1075.2.17  raeburn  7735: /*
                   7736:   styles used by TTH when "Default set of options to pass to tth/m
                   7737:   when converting TeX" in course settings has been set
                   7738: 
                   7739:   option passed: -t
                   7740: 
                   7741: */
                   7742: 
                   7743: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7744: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7745: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7746: td div.norm {line-height:normal;}
                   7747: 
                   7748: /*
                   7749:   option passed -y3
                   7750: */
                   7751: 
                   7752: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7753: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7754: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7755: 
1.1075.2.121  raeburn  7756: #LC_minitab_header {
                   7757:   float:left;
                   7758:   width:100%;
                   7759:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   7760:   font-size:93%;
                   7761:   line-height:normal;
                   7762:   margin: 0.5em 0 0.5em 0;
                   7763: }
                   7764: #LC_minitab_header ul {
                   7765:   margin:0;
                   7766:   padding:10px 10px 0;
                   7767:   list-style:none;
                   7768: }
                   7769: #LC_minitab_header li {
                   7770:   float:left;
                   7771:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   7772:   margin:0;
                   7773:   padding:0 0 0 9px;
                   7774: }
                   7775: #LC_minitab_header a {
                   7776:   display:block;
                   7777:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   7778:   padding:5px 15px 4px 6px;
                   7779: }
                   7780: #LC_minitab_header #LC_current_minitab {
                   7781:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   7782: }
                   7783: #LC_minitab_header #LC_current_minitab a {
                   7784:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   7785:   padding-bottom:5px;
                   7786: }
                   7787: 
                   7788: 
1.343     albertel 7789: END
                   7790: }
                   7791: 
1.306     albertel 7792: =pod
                   7793: 
                   7794: =item * &headtag()
                   7795: 
                   7796: Returns a uniform footer for LON-CAPA web pages.
                   7797: 
1.307     albertel 7798: Inputs: $title - optional title for the head
                   7799:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7800:         $args - optional arguments
1.319     albertel 7801:             force_register - if is true call registerurl so the remote is 
                   7802:                              informed
1.415     albertel 7803:             redirect       -> array ref of
                   7804:                                    1- seconds before redirect occurs
                   7805:                                    2- url to redirect to
                   7806:                                    3- whether the side effect should occur
1.315     albertel 7807:                            (side effect of setting 
                   7808:                                $env{'internal.head.redirect'} to the url 
                   7809:                                redirected too)
1.352     albertel 7810:             domain         -> force to color decorate a page for a specific
                   7811:                                domain
                   7812:             function       -> force usage of a specific rolish color scheme
                   7813:             bgcolor        -> override the default page bgcolor
1.460     albertel 7814:             no_auto_mt_title
                   7815:                            -> prevent &mt()ing the title arg
1.464     albertel 7816: 
1.306     albertel 7817: =cut
                   7818: 
                   7819: sub headtag {
1.313     albertel 7820:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7821:     
1.363     albertel 7822:     my $function = $args->{'function'} || &get_users_function();
                   7823:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7824:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7825:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7826:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7827: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7828: 		   #time(),
1.418     albertel 7829: 		   $env{'environment.color.timestamp'},
1.363     albertel 7830: 		   $function,$domain,$bgcolor);
                   7831: 
1.369     www      7832:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7833: 
1.308     albertel 7834:     my $result =
                   7835: 	'<head>'.
1.1075.2.56  raeburn  7836: 	&font_settings($args);
1.319     albertel 7837: 
1.1075.2.72  raeburn  7838:     my $inhibitprint;
                   7839:     if ($args->{'print_suppress'}) {
                   7840:         $inhibitprint = &print_suppression();
                   7841:     }
1.1064    raeburn  7842: 
1.461     albertel 7843:     if (!$args->{'frameset'}) {
                   7844: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7845:     }
1.1075.2.12  raeburn  7846:     if ($args->{'force_register'}) {
                   7847:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7848:     }
1.436     albertel 7849:     if (!$args->{'no_nav_bar'} 
                   7850: 	&& !$args->{'only_body'}
                   7851: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7852: 	$result .= &help_menu_js($httphost);
1.1032    www      7853:         $result.=&modal_window();
1.1038    www      7854:         $result.=&togglebox_script();
1.1034    www      7855:         $result.=&wishlist_window();
1.1041    www      7856:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7857:     } else {
                   7858:         if ($args->{'add_modal'}) {
                   7859:            $result.=&modal_window();
                   7860:         }
                   7861:         if ($args->{'add_wishlist'}) {
                   7862:            $result.=&wishlist_window();
                   7863:         }
1.1038    www      7864:         if ($args->{'add_togglebox'}) {
                   7865:            $result.=&togglebox_script();
                   7866:         }
1.1041    www      7867:         if ($args->{'add_progressbar'}) {
                   7868:            $result.=&LCprogressbarUpdate_script();
                   7869:         }
1.436     albertel 7870:     }
1.314     albertel 7871:     if (ref($args->{'redirect'})) {
1.414     albertel 7872: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7873: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7874: 	if (!$inhibit_continue) {
                   7875: 	    $env{'internal.head.redirect'} = $url;
                   7876: 	}
1.313     albertel 7877: 	$result.=<<ADDMETA
                   7878: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7879: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7880: ADDMETA
1.1075.2.89  raeburn  7881:     } else {
                   7882:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7883:             my $requrl = $env{'request.uri'};
                   7884:             if ($requrl eq '') {
                   7885:                 $requrl = $ENV{'REQUEST_URI'};
                   7886:                 $requrl =~ s/\?.+$//;
                   7887:             }
                   7888:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7889:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7890:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7891:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7892:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7893:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7894:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7895:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7896:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7897:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7898:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7899:                                 my $numsec = 5;
                   7900:                                 my $timeout = $numsec * 1000;
                   7901:                                 my ($newurl,$locknum,%locks,$msg);
                   7902:                                 if ($env{'request.role.adv'}) {
                   7903:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7904:                                 }
                   7905:                                 my $disable_submit = 0;
                   7906:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7907:                                     $disable_submit = 1;
                   7908:                                 }
                   7909:                                 if ($locknum) {
                   7910:                                     my @lockinfo = sort(values(%locks));
                   7911:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7912:                                            join(", ",sort(values(%locks)))."\\n".
                   7913:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7914:                                 } else {
                   7915:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7916:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7917:                                     }
                   7918:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7919:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7920:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7921:                                         $newurl .= '&role='.$env{'request.role'};
                   7922:                                     }
                   7923:                                     if ($env{'request.symb'}) {
                   7924:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7925:                                     } else {
                   7926:                                         $newurl .= '&origurl='.$requrl;
                   7927:                                     }
                   7928:                                 }
1.1075.2.98  raeburn  7929:                                 &js_escape(\$msg);
1.1075.2.89  raeburn  7930:                                 $result.=<<OFFLOAD
                   7931: <meta http-equiv="pragma" content="no-cache" />
                   7932: <script type="text/javascript">
1.1075.2.92  raeburn  7933: // <![CDATA[
1.1075.2.89  raeburn  7934: function LC_Offload_Now() {
                   7935:     var dest = "$newurl";
                   7936:     if (dest != '') {
                   7937:         window.location.href="$newurl";
                   7938:     }
                   7939: }
1.1075.2.92  raeburn  7940: \$(document).ready(function () {
                   7941:     window.alert('$msg');
                   7942:     if ($disable_submit) {
1.1075.2.89  raeburn  7943:         \$(".LC_hwk_submit").prop("disabled", true);
                   7944:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  7945:     }
                   7946:     setTimeout('LC_Offload_Now()', $timeout);
                   7947: });
                   7948: // ]]>
1.1075.2.89  raeburn  7949: </script>
                   7950: OFFLOAD
                   7951:                             }
                   7952:                         }
                   7953:                     }
                   7954:                 }
                   7955:             }
                   7956:         }
1.313     albertel 7957:     }
1.306     albertel 7958:     if (!defined($title)) {
                   7959: 	$title = 'The LearningOnline Network with CAPA';
                   7960:     }
1.460     albertel 7961:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7962:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  7963: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7964:     if (!$args->{'frameset'}) {
                   7965:         $result .= ' /';
                   7966:     }
                   7967:     $result .= '>'
1.1064    raeburn  7968:         .$inhibitprint
1.414     albertel 7969: 	.$head_extra;
1.1075.2.108  raeburn  7970:     my $clientmobile;
                   7971:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   7972:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   7973:     } else {
                   7974:         $clientmobile = $env{'browser.mobile'};
                   7975:     }
                   7976:     if ($clientmobile) {
1.1075.2.42  raeburn  7977:         $result .= '
                   7978: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7979: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7980:     }
1.1075.2.126  raeburn  7981:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 7982:     return $result.'</head>';
1.306     albertel 7983: }
                   7984: 
                   7985: =pod
                   7986: 
1.340     albertel 7987: =item * &font_settings()
                   7988: 
                   7989: Returns neccessary <meta> to set the proper encoding
                   7990: 
1.1075.2.56  raeburn  7991: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7992: 
                   7993: =cut
                   7994: 
                   7995: sub font_settings {
1.1075.2.56  raeburn  7996:     my ($args) = @_;
1.340     albertel 7997:     my $headerstring='';
1.1075.2.56  raeburn  7998:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7999:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 8000: 	$headerstring.=
1.1075.2.61  raeburn  8001: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8002:         if (!$args->{'frameset'}) {
                   8003:             $headerstring.= ' /';
                   8004:         }
                   8005:         $headerstring .= '>'."\n";
1.340     albertel 8006:     }
                   8007:     return $headerstring;
                   8008: }
                   8009: 
1.341     albertel 8010: =pod
                   8011: 
1.1064    raeburn  8012: =item * &print_suppression()
                   8013: 
                   8014: In course context returns css which causes the body to be blank when media="print",
                   8015: if printout generation is unavailable for the current resource.
                   8016: 
                   8017: This could be because:
                   8018: 
                   8019: (a) printstartdate is in the future
                   8020: 
                   8021: (b) printenddate is in the past
                   8022: 
                   8023: (c) there is an active exam block with "printout"
                   8024: functionality blocked
                   8025: 
                   8026: Users with pav, pfo or evb privileges are exempt.
                   8027: 
                   8028: Inputs: none
                   8029: 
                   8030: =cut
                   8031: 
                   8032: 
                   8033: sub print_suppression {
                   8034:     my $noprint;
                   8035:     if ($env{'request.course.id'}) {
                   8036:         my $scope = $env{'request.course.id'};
                   8037:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8038:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8039:             return;
                   8040:         }
                   8041:         if ($env{'request.course.sec'} ne '') {
                   8042:             $scope .= "/$env{'request.course.sec'}";
                   8043:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8044:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8045:                 return;
1.1064    raeburn  8046:             }
                   8047:         }
                   8048:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8049:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.73  raeburn  8050:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8051:         if ($blocked) {
                   8052:             my $checkrole = "cm./$cdom/$cnum";
                   8053:             if ($env{'request.course.sec'} ne '') {
                   8054:                 $checkrole .= "/$env{'request.course.sec'}";
                   8055:             }
                   8056:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8057:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8058:                 $noprint = 1;
                   8059:             }
                   8060:         }
                   8061:         unless ($noprint) {
                   8062:             my $symb = &Apache::lonnet::symbread();
                   8063:             if ($symb ne '') {
                   8064:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8065:                 if (ref($navmap)) {
                   8066:                     my $res = $navmap->getBySymb($symb);
                   8067:                     if (ref($res)) {
                   8068:                         if (!$res->resprintable()) {
                   8069:                             $noprint = 1;
                   8070:                         }
                   8071:                     }
                   8072:                 }
                   8073:             }
                   8074:         }
                   8075:         if ($noprint) {
                   8076:             return <<"ENDSTYLE";
                   8077: <style type="text/css" media="print">
                   8078:     body { display:none }
                   8079: </style>
                   8080: ENDSTYLE
                   8081:         }
                   8082:     }
                   8083:     return;
                   8084: }
                   8085: 
                   8086: =pod
                   8087: 
1.341     albertel 8088: =item * &xml_begin()
                   8089: 
                   8090: Returns the needed doctype and <html>
                   8091: 
                   8092: Inputs: none
                   8093: 
                   8094: =cut
                   8095: 
                   8096: sub xml_begin {
1.1075.2.61  raeburn  8097:     my ($is_frameset) = @_;
1.341     albertel 8098:     my $output='';
                   8099: 
                   8100:     if ($env{'browser.mathml'}) {
                   8101: 	$output='<?xml version="1.0"?>'
                   8102:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8103: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8104:             
                   8105: #	    .'<!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">] >'
                   8106: 	    .'<!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">'
                   8107:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8108: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  8109:     } elsif ($is_frameset) {
                   8110:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8111:                 '<html>'."\n";
1.341     albertel 8112:     } else {
1.1075.2.61  raeburn  8113: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8114:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8115:     }
                   8116:     return $output;
                   8117: }
1.340     albertel 8118: 
                   8119: =pod
                   8120: 
1.306     albertel 8121: =item * &start_page()
                   8122: 
                   8123: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8124: 
1.648     raeburn  8125: Inputs:
                   8126: 
                   8127: =over 4
                   8128: 
                   8129: $title - optional title for the page
                   8130: 
                   8131: $head_extra - optional extra HTML to incude inside the <head>
                   8132: 
                   8133: $args - additional optional args supported are:
                   8134: 
                   8135: =over 8
                   8136: 
                   8137:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8138:                                     arg on
1.814     bisitz   8139:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8140:              add_entries    -> additional attributes to add to the  <body>
                   8141:              domain         -> force to color decorate a page for a 
1.317     albertel 8142:                                     specific domain
1.648     raeburn  8143:              function       -> force usage of a specific rolish color
1.317     albertel 8144:                                     scheme
1.648     raeburn  8145:              redirect       -> see &headtag()
                   8146:              bgcolor        -> override the default page bg color
                   8147:              js_ready       -> return a string ready for being used in 
1.317     albertel 8148:                                     a javascript writeln
1.648     raeburn  8149:              html_encode    -> return a string ready for being used in 
1.320     albertel 8150:                                     a html attribute
1.648     raeburn  8151:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8152:                                     $forcereg arg
1.648     raeburn  8153:              frameset       -> if true will start with a <frameset>
1.330     albertel 8154:                                     rather than <body>
1.648     raeburn  8155:              skip_phases    -> hash ref of 
1.338     albertel 8156:                                     head -> skip the <html><head> generation
                   8157:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8158:              no_inline_link -> if true and in remote mode, don't show the
                   8159:                                     'Switch To Inline Menu' link
1.648     raeburn  8160:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8161:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8162:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  8163:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8164:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  8165:              group          -> includes the current group, if page is for a
                   8166:                                specific group
1.361     albertel 8167: 
1.648     raeburn  8168: =back
1.460     albertel 8169: 
1.648     raeburn  8170: =back
1.562     albertel 8171: 
1.306     albertel 8172: =cut
                   8173: 
                   8174: sub start_page {
1.309     albertel 8175:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8176:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8177: 
1.315     albertel 8178:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  8179:     my ($result,@advtools);
1.964     droeschl 8180: 
1.338     albertel 8181:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8182:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8183:     }
                   8184:     
                   8185:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8186: 	if ($args->{'frameset'}) {
                   8187: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8188: 						$args->{'add_entries'});
                   8189: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8190:         } else {
                   8191:             $result .=
                   8192:                 &bodytag($title, 
                   8193:                          $args->{'function'},       $args->{'add_entries'},
                   8194:                          $args->{'only_body'},      $args->{'domain'},
                   8195:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8196:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  8197:                          $args,                     \@advtools);
1.831     bisitz   8198:         }
1.330     albertel 8199:     }
1.338     albertel 8200: 
1.315     albertel 8201:     if ($args->{'js_ready'}) {
1.713     kaisler  8202: 		$result = &js_ready($result);
1.315     albertel 8203:     }
1.320     albertel 8204:     if ($args->{'html_encode'}) {
1.713     kaisler  8205: 		$result = &html_encode($result);
                   8206:     }
                   8207: 
1.813     bisitz   8208:     # Preparation for new and consistent functionlist at top of screen
                   8209:     # if ($args->{'functionlist'}) {
                   8210:     #            $result .= &build_functionlist();
                   8211:     #}
                   8212: 
1.964     droeschl 8213:     # Don't add anything more if only_body wanted or in const space
                   8214:     return $result if    $args->{'only_body'} 
                   8215:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8216: 
                   8217:     #Breadcrumbs
1.758     kaisler  8218:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8219: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8220: 		#if any br links exists, add them to the breadcrumbs
                   8221: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8222: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8223: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8224: 			}
                   8225: 		}
1.1075.2.19  raeburn  8226:                 # if @advtools array contains items add then to the breadcrumbs
                   8227:                 if (@advtools > 0) {
                   8228:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8229:                 }
1.1075.2.123  raeburn  8230:                 my $menulink;
                   8231:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8232:                 if (exists($args->{'bread_crumbs_nomenu'})) {
                   8233:                     $menulink = 0;
                   8234:                 } else {
                   8235:                     undef($menulink);
                   8236:                 }
1.758     kaisler  8237: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8238: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  8239: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.758     kaisler  8240: 		}else{
1.1075.2.123  raeburn  8241: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8242: 		}
1.1075.2.24  raeburn  8243:     } elsif (($env{'environment.remote'} eq 'on') &&
                   8244:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   8245:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   8246:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  8247:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 8248:     }
1.315     albertel 8249:     return $result;
1.306     albertel 8250: }
                   8251: 
                   8252: sub end_page {
1.315     albertel 8253:     my ($args) = @_;
                   8254:     $env{'internal.end_page'}++;
1.330     albertel 8255:     my $result;
1.335     albertel 8256:     if ($args->{'discussion'}) {
                   8257: 	my ($target,$parser);
                   8258: 	if (ref($args->{'discussion'})) {
                   8259: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8260: 				$args->{'discussion'}{'parser'});
                   8261: 	}
                   8262: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8263:     }
1.330     albertel 8264:     if ($args->{'frameset'}) {
                   8265: 	$result .= '</frameset>';
                   8266:     } else {
1.635     raeburn  8267: 	$result .= &endbodytag($args);
1.330     albertel 8268:     }
1.1075.2.6  raeburn  8269:     unless ($args->{'notbody'}) {
                   8270:         $result .= "\n</html>";
                   8271:     }
1.330     albertel 8272: 
1.315     albertel 8273:     if ($args->{'js_ready'}) {
1.317     albertel 8274: 	$result = &js_ready($result);
1.315     albertel 8275:     }
1.335     albertel 8276: 
1.320     albertel 8277:     if ($args->{'html_encode'}) {
                   8278: 	$result = &html_encode($result);
                   8279:     }
1.335     albertel 8280: 
1.315     albertel 8281:     return $result;
                   8282: }
                   8283: 
1.1034    www      8284: sub wishlist_window {
                   8285:     return(<<'ENDWISHLIST');
1.1046    raeburn  8286: <script type="text/javascript">
1.1034    www      8287: // <![CDATA[
                   8288: // <!-- BEGIN LON-CAPA Internal
                   8289: function set_wishlistlink(title, path) {
                   8290:     if (!title) {
                   8291:         title = document.title;
                   8292:         title = title.replace(/^LON-CAPA /,'');
                   8293:     }
1.1075.2.65  raeburn  8294:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  8295:     title = title.replace("'","\\\'");
1.1034    www      8296:     if (!path) {
                   8297:         path = location.pathname;
                   8298:     }
1.1075.2.65  raeburn  8299:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  8300:     path = path.replace("'","\\\'");
1.1034    www      8301:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8302:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8303: }
                   8304: // END LON-CAPA Internal -->
                   8305: // ]]>
                   8306: </script>
                   8307: ENDWISHLIST
                   8308: }
                   8309: 
1.1030    www      8310: sub modal_window {
                   8311:     return(<<'ENDMODAL');
1.1046    raeburn  8312: <script type="text/javascript">
1.1030    www      8313: // <![CDATA[
                   8314: // <!-- BEGIN LON-CAPA Internal
                   8315: var modalWindow = {
                   8316: 	parent:"body",
                   8317: 	windowId:null,
                   8318: 	content:null,
                   8319: 	width:null,
                   8320: 	height:null,
                   8321: 	close:function()
                   8322: 	{
                   8323: 	        $(".LCmodal-window").remove();
                   8324: 	        $(".LCmodal-overlay").remove();
                   8325: 	},
                   8326: 	open:function()
                   8327: 	{
                   8328: 		var modal = "";
                   8329: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8330: 		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;\">";
                   8331: 		modal += this.content;
                   8332: 		modal += "</div>";	
                   8333: 
                   8334: 		$(this.parent).append(modal);
                   8335: 
                   8336: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8337: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8338: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8339: 	}
                   8340: };
1.1075.2.42  raeburn  8341: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8342: 	{
1.1075.2.119  raeburn  8343:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8344: 		modalWindow.windowId = "myModal";
                   8345: 		modalWindow.width = width;
                   8346: 		modalWindow.height = height;
1.1075.2.80  raeburn  8347: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8348: 		modalWindow.open();
1.1075.2.87  raeburn  8349: 	};
1.1030    www      8350: // END LON-CAPA Internal -->
                   8351: // ]]>
                   8352: </script>
                   8353: ENDMODAL
                   8354: }
                   8355: 
                   8356: sub modal_link {
1.1075.2.42  raeburn  8357:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8358:     unless ($width) { $width=480; }
                   8359:     unless ($height) { $height=400; }
1.1031    www      8360:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  8361:     unless ($transparency) { $transparency='true'; }
                   8362: 
1.1074    raeburn  8363:     my $target_attr;
                   8364:     if (defined($target)) {
                   8365:         $target_attr = 'target="'.$target.'"';
                   8366:     }
                   8367:     return <<"ENDLINK";
1.1075.2.42  raeburn  8368: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8369:            $linktext</a>
                   8370: ENDLINK
1.1030    www      8371: }
                   8372: 
1.1032    www      8373: sub modal_adhoc_script {
                   8374:     my ($funcname,$width,$height,$content)=@_;
                   8375:     return (<<ENDADHOC);
1.1046    raeburn  8376: <script type="text/javascript">
1.1032    www      8377: // <![CDATA[
                   8378:         var $funcname = function()
                   8379:         {
                   8380:                 modalWindow.windowId = "myModal";
                   8381:                 modalWindow.width = $width;
                   8382:                 modalWindow.height = $height;
                   8383:                 modalWindow.content = '$content';
                   8384:                 modalWindow.open();
                   8385:         };  
                   8386: // ]]>
                   8387: </script>
                   8388: ENDADHOC
                   8389: }
                   8390: 
1.1041    www      8391: sub modal_adhoc_inner {
                   8392:     my ($funcname,$width,$height,$content)=@_;
                   8393:     my $innerwidth=$width-20;
                   8394:     $content=&js_ready(
1.1042    www      8395:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  8396:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8397:                  $content.
1.1041    www      8398:                  &end_scrollbox().
1.1075.2.42  raeburn  8399:                  &end_page()
1.1041    www      8400:              );
                   8401:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8402: }
                   8403: 
                   8404: sub modal_adhoc_window {
                   8405:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8406:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8407:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8408: }
                   8409: 
                   8410: sub modal_adhoc_launch {
                   8411:     my ($funcname,$width,$height,$content)=@_;
                   8412:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8413: <script type="text/javascript">
                   8414: // <![CDATA[
                   8415: $funcname();
                   8416: // ]]>
                   8417: </script>
                   8418: ENDLAUNCH
                   8419: }
                   8420: 
                   8421: sub modal_adhoc_close {
                   8422:     return (<<ENDCLOSE);
                   8423: <script type="text/javascript">
                   8424: // <![CDATA[
                   8425: modalWindow.close();
                   8426: // ]]>
                   8427: </script>
                   8428: ENDCLOSE
                   8429: }
                   8430: 
1.1038    www      8431: sub togglebox_script {
                   8432:    return(<<ENDTOGGLE);
                   8433: <script type="text/javascript"> 
                   8434: // <![CDATA[
                   8435: function LCtoggleDisplay(id,hidetext,showtext) {
                   8436:    link = document.getElementById(id + "link").childNodes[0];
                   8437:    with (document.getElementById(id).style) {
                   8438:       if (display == "none" ) {
                   8439:           display = "inline";
                   8440:           link.nodeValue = hidetext;
                   8441:         } else {
                   8442:           display = "none";
                   8443:           link.nodeValue = showtext;
                   8444:        }
                   8445:    }
                   8446: }
                   8447: // ]]>
                   8448: </script>
                   8449: ENDTOGGLE
                   8450: }
                   8451: 
1.1039    www      8452: sub start_togglebox {
                   8453:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8454:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8455:     unless ($showtext) { $showtext=&mt('show'); }
                   8456:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8457:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8458:     return &start_data_table().
                   8459:            &start_data_table_header_row().
                   8460:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8461:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8462:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8463:            &end_data_table_header_row().
                   8464:            '<tr id="'.$id.'" style="display:none""><td>';
                   8465: }
                   8466: 
                   8467: sub end_togglebox {
                   8468:     return '</td></tr>'.&end_data_table();
                   8469: }
                   8470: 
1.1041    www      8471: sub LCprogressbar_script {
1.1045    www      8472:    my ($id)=@_;
1.1041    www      8473:    return(<<ENDPROGRESS);
                   8474: <script type="text/javascript">
                   8475: // <![CDATA[
1.1045    www      8476: \$('#progressbar$id').progressbar({
1.1041    www      8477:   value: 0,
                   8478:   change: function(event, ui) {
                   8479:     var newVal = \$(this).progressbar('option', 'value');
                   8480:     \$('.pblabel', this).text(LCprogressTxt);
                   8481:   }
                   8482: });
                   8483: // ]]>
                   8484: </script>
                   8485: ENDPROGRESS
                   8486: }
                   8487: 
                   8488: sub LCprogressbarUpdate_script {
                   8489:    return(<<ENDPROGRESSUPDATE);
                   8490: <style type="text/css">
                   8491: .ui-progressbar { position:relative; }
                   8492: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8493: </style>
                   8494: <script type="text/javascript">
                   8495: // <![CDATA[
1.1045    www      8496: var LCprogressTxt='---';
                   8497: 
                   8498: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8499:    LCprogressTxt=progresstext;
1.1045    www      8500:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8501: }
                   8502: // ]]>
                   8503: </script>
                   8504: ENDPROGRESSUPDATE
                   8505: }
                   8506: 
1.1042    www      8507: my $LClastpercent;
1.1045    www      8508: my $LCidcnt;
                   8509: my $LCcurrentid;
1.1042    www      8510: 
1.1041    www      8511: sub LCprogressbar {
1.1042    www      8512:     my ($r)=(@_);
                   8513:     $LClastpercent=0;
1.1045    www      8514:     $LCidcnt++;
                   8515:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8516:     my $starting=&mt('Starting');
                   8517:     my $content=(<<ENDPROGBAR);
1.1045    www      8518:   <div id="progressbar$LCcurrentid">
1.1041    www      8519:     <span class="pblabel">$starting</span>
                   8520:   </div>
                   8521: ENDPROGBAR
1.1045    www      8522:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8523: }
                   8524: 
                   8525: sub LCprogressbarUpdate {
1.1042    www      8526:     my ($r,$val,$text)=@_;
                   8527:     unless ($val) { 
                   8528:        if ($LClastpercent) {
                   8529:            $val=$LClastpercent;
                   8530:        } else {
                   8531:            $val=0;
                   8532:        }
                   8533:     }
1.1041    www      8534:     if ($val<0) { $val=0; }
                   8535:     if ($val>100) { $val=0; }
1.1042    www      8536:     $LClastpercent=$val;
1.1041    www      8537:     unless ($text) { $text=$val.'%'; }
                   8538:     $text=&js_ready($text);
1.1044    www      8539:     &r_print($r,<<ENDUPDATE);
1.1041    www      8540: <script type="text/javascript">
                   8541: // <![CDATA[
1.1045    www      8542: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8543: // ]]>
                   8544: </script>
                   8545: ENDUPDATE
1.1035    www      8546: }
                   8547: 
1.1042    www      8548: sub LCprogressbarClose {
                   8549:     my ($r)=@_;
                   8550:     $LClastpercent=0;
1.1044    www      8551:     &r_print($r,<<ENDCLOSE);
1.1042    www      8552: <script type="text/javascript">
                   8553: // <![CDATA[
1.1045    www      8554: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8555: // ]]>
                   8556: </script>
                   8557: ENDCLOSE
1.1044    www      8558: }
                   8559: 
                   8560: sub r_print {
                   8561:     my ($r,$to_print)=@_;
                   8562:     if ($r) {
                   8563:       $r->print($to_print);
                   8564:       $r->rflush();
                   8565:     } else {
                   8566:       print($to_print);
                   8567:     }
1.1042    www      8568: }
                   8569: 
1.320     albertel 8570: sub html_encode {
                   8571:     my ($result) = @_;
                   8572: 
1.322     albertel 8573:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8574:     
                   8575:     return $result;
                   8576: }
1.1044    www      8577: 
1.317     albertel 8578: sub js_ready {
                   8579:     my ($result) = @_;
                   8580: 
1.323     albertel 8581:     $result =~ s/[\n\r]/ /xmsg;
                   8582:     $result =~ s/\\/\\\\/xmsg;
                   8583:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8584:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8585:     
                   8586:     return $result;
                   8587: }
                   8588: 
1.315     albertel 8589: sub validate_page {
                   8590:     if (  exists($env{'internal.start_page'})
1.316     albertel 8591: 	  &&     $env{'internal.start_page'} > 1) {
                   8592: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8593: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8594: 				 $ENV{'request.filename'});
1.315     albertel 8595:     }
                   8596:     if (  exists($env{'internal.end_page'})
1.316     albertel 8597: 	  &&     $env{'internal.end_page'} > 1) {
                   8598: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8599: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8600: 				 $env{'request.filename'});
1.315     albertel 8601:     }
                   8602:     if (     exists($env{'internal.start_page'})
                   8603: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8604: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8605: 				 $env{'request.filename'});
1.315     albertel 8606:     }
                   8607:     if (   ! exists($env{'internal.start_page'})
                   8608: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8609: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8610: 				 $env{'request.filename'});
1.315     albertel 8611:     }
1.306     albertel 8612: }
1.315     albertel 8613: 
1.996     www      8614: 
                   8615: sub start_scrollbox {
1.1075.2.56  raeburn  8616:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8617:     unless ($outerwidth) { $outerwidth='520px'; }
                   8618:     unless ($width) { $width='500px'; }
                   8619:     unless ($height) { $height='200px'; }
1.1075    raeburn  8620:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8621:     if ($id ne '') {
1.1075.2.42  raeburn  8622:         $table_id = ' id="table_'.$id.'"';
                   8623:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8624:     }
1.1075    raeburn  8625:     if ($bgcolor ne '') {
                   8626:         $tdcol = "background-color: $bgcolor;";
                   8627:     }
1.1075.2.42  raeburn  8628:     my $nicescroll_js;
                   8629:     if ($env{'browser.mobile'}) {
                   8630:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8631:     }
1.1075    raeburn  8632:     return <<"END";
1.1075.2.42  raeburn  8633: $nicescroll_js
                   8634: 
                   8635: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8636: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8637: END
1.996     www      8638: }
                   8639: 
                   8640: sub end_scrollbox {
1.1036    www      8641:     return '</div></td></tr></table>';
1.996     www      8642: }
                   8643: 
1.1075.2.42  raeburn  8644: sub nicescroll_javascript {
                   8645:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8646:     my %options;
                   8647:     if (ref($cursor) eq 'HASH') {
                   8648:         %options = %{$cursor};
                   8649:     }
                   8650:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8651:         $options{'railalign'} = 'left';
                   8652:     }
                   8653:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8654:         my $function  = &get_users_function();
                   8655:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8656:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8657:             $options{'cursorcolor'} = '#00F';
                   8658:         }
                   8659:     }
                   8660:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8661:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8662:             $options{'cursoropacity'}='1.0';
                   8663:         }
                   8664:     } else {
                   8665:         $options{'cursoropacity'}='1.0';
                   8666:     }
                   8667:     if ($options{'cursorfixedheight'} eq 'none') {
                   8668:         delete($options{'cursorfixedheight'});
                   8669:     } else {
                   8670:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8671:     }
                   8672:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8673:         delete($options{'railoffset'});
                   8674:     }
                   8675:     my @niceoptions;
                   8676:     while (my($key,$value) = each(%options)) {
                   8677:         if ($value =~ /^\{.+\}$/) {
                   8678:             push(@niceoptions,$key.':'.$value);
                   8679:         } else {
                   8680:             push(@niceoptions,$key.':"'.$value.'"');
                   8681:         }
                   8682:     }
                   8683:     my $nicescroll_js = '
                   8684: $(document).ready(
                   8685:       function() {
                   8686:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8687:       }
                   8688: );
                   8689: ';
                   8690:     if ($framecheck) {
                   8691:         $nicescroll_js .= '
                   8692: function expand_div(caller) {
                   8693:     if (top === self) {
                   8694:         document.getElementById("'.$id.'").style.width = "auto";
                   8695:         document.getElementById("'.$id.'").style.height = "auto";
                   8696:     } else {
                   8697:         try {
                   8698:             if (parent.frames) {
                   8699:                 if (parent.frames.length > 1) {
                   8700:                     var framesrc = parent.frames[1].location.href;
                   8701:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8702:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8703:                         document.getElementById("'.$id.'").style.width = "auto";
                   8704:                         document.getElementById("'.$id.'").style.height = "auto";
                   8705:                     }
                   8706:                 }
                   8707:             }
                   8708:         } catch (e) {
                   8709:             return;
                   8710:         }
                   8711:     }
                   8712:     return;
                   8713: }
                   8714: ';
                   8715:     }
                   8716:     if ($needjsready) {
                   8717:         $nicescroll_js = '
                   8718: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8719:     } else {
                   8720:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8721:     }
                   8722:     return $nicescroll_js;
                   8723: }
                   8724: 
1.318     albertel 8725: sub simple_error_page {
1.1075.2.49  raeburn  8726:     my ($r,$title,$msg,$args) = @_;
                   8727:     if (ref($args) eq 'HASH') {
                   8728:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8729:     } else {
                   8730:         $msg = &mt($msg);
                   8731:     }
                   8732: 
1.318     albertel 8733:     my $page =
                   8734: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8735: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8736: 	&Apache::loncommon::end_page();
                   8737:     if (ref($r)) {
                   8738: 	$r->print($page);
1.327     albertel 8739: 	return;
1.318     albertel 8740:     }
                   8741:     return $page;
                   8742: }
1.347     albertel 8743: 
                   8744: {
1.610     albertel 8745:     my @row_count;
1.961     onken    8746: 
                   8747:     sub start_data_table_count {
                   8748:         unshift(@row_count, 0);
                   8749:         return;
                   8750:     }
                   8751: 
                   8752:     sub end_data_table_count {
                   8753:         shift(@row_count);
                   8754:         return;
                   8755:     }
                   8756: 
1.347     albertel 8757:     sub start_data_table {
1.1018    raeburn  8758: 	my ($add_class,$id) = @_;
1.422     albertel 8759: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8760:         my $table_id;
                   8761:         if (defined($id)) {
                   8762:             $table_id = ' id="'.$id.'"';
                   8763:         }
1.961     onken    8764: 	&start_data_table_count();
1.1018    raeburn  8765: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8766:     }
                   8767: 
                   8768:     sub end_data_table {
1.961     onken    8769: 	&end_data_table_count();
1.389     albertel 8770: 	return '</table>'."\n";;
1.347     albertel 8771:     }
                   8772: 
                   8773:     sub start_data_table_row {
1.974     wenzelju 8774: 	my ($add_class, $id) = @_;
1.610     albertel 8775: 	$row_count[0]++;
                   8776: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8777: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8778:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8779:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8780:     }
1.471     banghart 8781:     
                   8782:     sub continue_data_table_row {
1.974     wenzelju 8783: 	my ($add_class, $id) = @_;
1.610     albertel 8784: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8785: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8786:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8787:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8788:     }
1.347     albertel 8789: 
                   8790:     sub end_data_table_row {
1.389     albertel 8791: 	return '</tr>'."\n";;
1.347     albertel 8792:     }
1.367     www      8793: 
1.421     albertel 8794:     sub start_data_table_empty_row {
1.707     bisitz   8795: #	$row_count[0]++;
1.421     albertel 8796: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8797:     }
                   8798: 
                   8799:     sub end_data_table_empty_row {
                   8800: 	return '</tr>'."\n";;
                   8801:     }
                   8802: 
1.367     www      8803:     sub start_data_table_header_row {
1.389     albertel 8804: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8805:     }
                   8806: 
                   8807:     sub end_data_table_header_row {
1.389     albertel 8808: 	return '</tr>'."\n";;
1.367     www      8809:     }
1.890     droeschl 8810: 
                   8811:     sub data_table_caption {
                   8812:         my $caption = shift;
                   8813:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8814:     }
1.347     albertel 8815: }
                   8816: 
1.548     albertel 8817: =pod
                   8818: 
                   8819: =item * &inhibit_menu_check($arg)
                   8820: 
                   8821: Checks for a inhibitmenu state and generates output to preserve it
                   8822: 
                   8823: Inputs:         $arg - can be any of
                   8824:                      - undef - in which case the return value is a string 
                   8825:                                to add  into arguments list of a uri
                   8826:                      - 'input' - in which case the return value is a HTML
                   8827:                                  <form> <input> field of type hidden to
                   8828:                                  preserve the value
                   8829:                      - a url - in which case the return value is the url with
                   8830:                                the neccesary cgi args added to preserve the
                   8831:                                inhibitmenu state
                   8832:                      - a ref to a url - no return value, but the string is
                   8833:                                         updated to include the neccessary cgi
                   8834:                                         args to preserve the inhibitmenu state
                   8835: 
                   8836: =cut
                   8837: 
                   8838: sub inhibit_menu_check {
                   8839:     my ($arg) = @_;
                   8840:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8841:     if ($arg eq 'input') {
                   8842: 	if ($env{'form.inhibitmenu'}) {
                   8843: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8844: 	} else {
                   8845: 	    return
                   8846: 	}
                   8847:     }
                   8848:     if ($env{'form.inhibitmenu'}) {
                   8849: 	if (ref($arg)) {
                   8850: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8851: 	} elsif ($arg eq '') {
                   8852: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8853: 	} else {
                   8854: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8855: 	}
                   8856:     }
                   8857:     if (!ref($arg)) {
                   8858: 	return $arg;
                   8859:     }
                   8860: }
                   8861: 
1.251     albertel 8862: ###############################################
1.182     matthew  8863: 
                   8864: =pod
                   8865: 
1.549     albertel 8866: =back
                   8867: 
                   8868: =head1 User Information Routines
                   8869: 
                   8870: =over 4
                   8871: 
1.405     albertel 8872: =item * &get_users_function()
1.182     matthew  8873: 
                   8874: Used by &bodytag to determine the current users primary role.
                   8875: Returns either 'student','coordinator','admin', or 'author'.
                   8876: 
                   8877: =cut
                   8878: 
                   8879: ###############################################
                   8880: sub get_users_function {
1.815     tempelho 8881:     my $function = 'norole';
1.818     tempelho 8882:     if ($env{'request.role'}=~/^(st)/) {
                   8883:         $function='student';
                   8884:     }
1.907     raeburn  8885:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8886:         $function='coordinator';
                   8887:     }
1.258     albertel 8888:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8889:         $function='admin';
                   8890:     }
1.826     bisitz   8891:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8892:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8893:         $function='author';
                   8894:     }
                   8895:     return $function;
1.54      www      8896: }
1.99      www      8897: 
                   8898: ###############################################
                   8899: 
1.233     raeburn  8900: =pod
                   8901: 
1.821     raeburn  8902: =item * &show_course()
                   8903: 
                   8904: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8905: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8906: 
                   8907: Inputs:
                   8908: None
                   8909: 
                   8910: Outputs:
                   8911: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8912: 
                   8913: =cut
                   8914: 
                   8915: ###############################################
                   8916: sub show_course {
                   8917:     my $course = !$env{'user.adv'};
                   8918:     if (!$env{'user.adv'}) {
                   8919:         foreach my $env (keys(%env)) {
                   8920:             next if ($env !~ m/^user\.priv\./);
                   8921:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8922:                 $course = 0;
                   8923:                 last;
                   8924:             }
                   8925:         }
                   8926:     }
                   8927:     return $course;
                   8928: }
                   8929: 
                   8930: ###############################################
                   8931: 
                   8932: =pod
                   8933: 
1.542     raeburn  8934: =item * &check_user_status()
1.274     raeburn  8935: 
                   8936: Determines current status of supplied role for a
                   8937: specific user. Roles can be active, previous or future.
                   8938: 
                   8939: Inputs: 
                   8940: user's domain, user's username, course's domain,
1.375     raeburn  8941: course's number, optional section ID.
1.274     raeburn  8942: 
                   8943: Outputs:
                   8944: role status: active, previous or future. 
                   8945: 
                   8946: =cut
                   8947: 
                   8948: sub check_user_status {
1.412     raeburn  8949:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8950:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  8951:     my @uroles = keys(%userinfo);
1.274     raeburn  8952:     my $srchstr;
                   8953:     my $active_chk = 'none';
1.412     raeburn  8954:     my $now = time;
1.274     raeburn  8955:     if (@uroles > 0) {
1.908     raeburn  8956:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8957:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8958:         } else {
1.412     raeburn  8959:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8960:         }
                   8961:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8962:             my $role_end = 0;
                   8963:             my $role_start = 0;
                   8964:             $active_chk = 'active';
1.412     raeburn  8965:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8966:                 $role_end = $1;
                   8967:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8968:                     $role_start = $1;
1.274     raeburn  8969:                 }
                   8970:             }
                   8971:             if ($role_start > 0) {
1.412     raeburn  8972:                 if ($now < $role_start) {
1.274     raeburn  8973:                     $active_chk = 'future';
                   8974:                 }
                   8975:             }
                   8976:             if ($role_end > 0) {
1.412     raeburn  8977:                 if ($now > $role_end) {
1.274     raeburn  8978:                     $active_chk = 'previous';
                   8979:                 }
                   8980:             }
                   8981:         }
                   8982:     }
                   8983:     return $active_chk;
                   8984: }
                   8985: 
                   8986: ###############################################
                   8987: 
                   8988: =pod
                   8989: 
1.405     albertel 8990: =item * &get_sections()
1.233     raeburn  8991: 
                   8992: Determines all the sections for a course including
                   8993: sections with students and sections containing other roles.
1.419     raeburn  8994: Incoming parameters: 
                   8995: 
                   8996: 1. domain
                   8997: 2. course number 
                   8998: 3. reference to array containing roles for which sections should 
                   8999: be gathered (optional).
                   9000: 4. reference to array containing status types for which sections 
                   9001: should be gathered (optional).
                   9002: 
                   9003: If the third argument is undefined, sections are gathered for any role. 
                   9004: If the fourth argument is undefined, sections are gathered for any status.
                   9005: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9006:  
1.374     raeburn  9007: Returns section hash (keys are section IDs, values are
                   9008: number of users in each section), subject to the
1.419     raeburn  9009: optional roles filter, optional status filter 
1.233     raeburn  9010: 
                   9011: =cut
                   9012: 
                   9013: ###############################################
                   9014: sub get_sections {
1.419     raeburn  9015:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9016:     if (!defined($cdom) || !defined($cnum)) {
                   9017:         my $cid =  $env{'request.course.id'};
                   9018: 
                   9019: 	return if (!defined($cid));
                   9020: 
                   9021:         $cdom = $env{'course.'.$cid.'.domain'};
                   9022:         $cnum = $env{'course.'.$cid.'.num'};
                   9023:     }
                   9024: 
                   9025:     my %sectioncount;
1.419     raeburn  9026:     my $now = time;
1.240     albertel 9027: 
1.1075.2.33  raeburn  9028:     my $check_students = 1;
                   9029:     my $only_students = 0;
                   9030:     if (ref($possible_roles) eq 'ARRAY') {
                   9031:         if (grep(/^st$/,@{$possible_roles})) {
                   9032:             if (@{$possible_roles} == 1) {
                   9033:                 $only_students = 1;
                   9034:             }
                   9035:         } else {
                   9036:             $check_students = 0;
                   9037:         }
                   9038:     }
                   9039: 
                   9040:     if ($check_students) {
1.276     albertel 9041: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9042: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9043: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9044:         my $start_index = &Apache::loncoursedata::CL_START();
                   9045:         my $end_index = &Apache::loncoursedata::CL_END();
                   9046:         my $status;
1.366     albertel 9047: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9048: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9049: 				                     $data->[$status_index],
                   9050:                                                      $data->[$start_index],
                   9051:                                                      $data->[$end_index]);
                   9052:             if ($stu_status eq 'Active') {
                   9053:                 $status = 'active';
                   9054:             } elsif ($end < $now) {
                   9055:                 $status = 'previous';
                   9056:             } elsif ($start > $now) {
                   9057:                 $status = 'future';
                   9058:             } 
                   9059: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9060:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9061:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9062: 		    $sectioncount{$section}++;
                   9063:                 }
1.240     albertel 9064: 	    }
                   9065: 	}
                   9066:     }
1.1075.2.33  raeburn  9067:     if ($only_students) {
                   9068:         return %sectioncount;
                   9069:     }
1.240     albertel 9070:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9071:     foreach my $user (sort(keys(%courseroles))) {
                   9072: 	if ($user !~ /^(\w{2})/) { next; }
                   9073: 	my ($role) = ($user =~ /^(\w{2})/);
                   9074: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9075: 	my ($section,$status);
1.240     albertel 9076: 	if ($role eq 'cr' &&
                   9077: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9078: 	    $section=$1;
                   9079: 	}
                   9080: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9081: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9082:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9083:         if ($end == -1 && $start == -1) {
                   9084:             next; #deleted role
                   9085:         }
                   9086:         if (!defined($possible_status)) { 
                   9087:             $sectioncount{$section}++;
                   9088:         } else {
                   9089:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9090:                 $status = 'active';
                   9091:             } elsif ($end < $now) {
                   9092:                 $status = 'future';
                   9093:             } elsif ($start > $now) {
                   9094:                 $status = 'previous';
                   9095:             }
                   9096:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9097:                 $sectioncount{$section}++;
                   9098:             }
                   9099:         }
1.233     raeburn  9100:     }
1.366     albertel 9101:     return %sectioncount;
1.233     raeburn  9102: }
                   9103: 
1.274     raeburn  9104: ###############################################
1.294     raeburn  9105: 
                   9106: =pod
1.405     albertel 9107: 
                   9108: =item * &get_course_users()
                   9109: 
1.275     raeburn  9110: Retrieves usernames:domains for users in the specified course
                   9111: with specific role(s), and access status. 
                   9112: 
                   9113: Incoming parameters:
1.277     albertel 9114: 1. course domain
                   9115: 2. course number
                   9116: 3. access status: users must have - either active, 
1.275     raeburn  9117: previous, future, or all.
1.277     albertel 9118: 4. reference to array of permissible roles
1.288     raeburn  9119: 5. reference to array of section restrictions (optional)
                   9120: 6. reference to results object (hash of hashes).
                   9121: 7. reference to optional userdata hash
1.609     raeburn  9122: 8. reference to optional statushash
1.630     raeburn  9123: 9. flag if privileged users (except those set to unhide in
                   9124:    course settings) should be excluded    
1.609     raeburn  9125: Keys of top level results hash are roles.
1.275     raeburn  9126: Keys of inner hashes are username:domain, with 
                   9127: values set to access type.
1.288     raeburn  9128: Optional userdata hash returns an array with arguments in the 
                   9129: same order as loncoursedata::get_classlist() for student data.
                   9130: 
1.609     raeburn  9131: Optional statushash returns
                   9132: 
1.288     raeburn  9133: Entries for end, start, section and status are blank because
                   9134: of the possibility of multiple values for non-student roles.
                   9135: 
1.275     raeburn  9136: =cut
1.405     albertel 9137: 
1.275     raeburn  9138: ###############################################
1.405     albertel 9139: 
1.275     raeburn  9140: sub get_course_users {
1.630     raeburn  9141:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9142:     my %idx = ();
1.419     raeburn  9143:     my %seclists;
1.288     raeburn  9144: 
                   9145:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9146:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9147:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9148:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9149:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9150:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9151:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9152:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9153: 
1.290     albertel 9154:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9155:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9156:         my $now = time;
1.277     albertel 9157:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9158:             my $match = 0;
1.412     raeburn  9159:             my $secmatch = 0;
1.419     raeburn  9160:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9161:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9162:             if ($section eq '') {
                   9163:                 $section = 'none';
                   9164:             }
1.291     albertel 9165:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9166:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9167:                     $secmatch = 1;
                   9168:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9169:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9170:                         $secmatch = 1;
                   9171:                     }
                   9172:                 } else {  
1.419     raeburn  9173: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9174: 		        $secmatch = 1;
                   9175:                     }
1.290     albertel 9176: 		}
1.412     raeburn  9177:                 if (!$secmatch) {
                   9178:                     next;
                   9179:                 }
1.419     raeburn  9180:             }
1.275     raeburn  9181:             if (defined($$types{'active'})) {
1.288     raeburn  9182:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9183:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9184:                     $match = 1;
1.275     raeburn  9185:                 }
                   9186:             }
                   9187:             if (defined($$types{'previous'})) {
1.609     raeburn  9188:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9189:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9190:                     $match = 1;
1.275     raeburn  9191:                 }
                   9192:             }
                   9193:             if (defined($$types{'future'})) {
1.609     raeburn  9194:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9195:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9196:                     $match = 1;
1.275     raeburn  9197:                 }
                   9198:             }
1.609     raeburn  9199:             if ($match) {
                   9200:                 push(@{$seclists{$student}},$section);
                   9201:                 if (ref($userdata) eq 'HASH') {
                   9202:                     $$userdata{$student} = $$classlist{$student};
                   9203:                 }
                   9204:                 if (ref($statushash) eq 'HASH') {
                   9205:                     $statushash->{$student}{'st'}{$section} = $status;
                   9206:                 }
1.288     raeburn  9207:             }
1.275     raeburn  9208:         }
                   9209:     }
1.412     raeburn  9210:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9211:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9212:         my $now = time;
1.609     raeburn  9213:         my %displaystatus = ( previous => 'Expired',
                   9214:                               active   => 'Active',
                   9215:                               future   => 'Future',
                   9216:                             );
1.1075.2.36  raeburn  9217:         my (%nothide,@possdoms);
1.630     raeburn  9218:         if ($hidepriv) {
                   9219:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9220:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9221:                 if ($user !~ /:/) {
                   9222:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9223:                 } else {
                   9224:                     $nothide{$user} = 1;
                   9225:                 }
                   9226:             }
1.1075.2.36  raeburn  9227:             my @possdoms = ($cdom);
                   9228:             if ($coursehash{'checkforpriv'}) {
                   9229:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9230:             }
1.630     raeburn  9231:         }
1.439     raeburn  9232:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9233:             my $match = 0;
1.412     raeburn  9234:             my $secmatch = 0;
1.439     raeburn  9235:             my $status;
1.412     raeburn  9236:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9237:             $user =~ s/:$//;
1.439     raeburn  9238:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9239:             if ($end == -1 || $start == -1) {
                   9240:                 next;
                   9241:             }
                   9242:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9243:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9244:                 my ($uname,$udom) = split(/:/,$user);
                   9245:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9246:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9247:                         $secmatch = 1;
                   9248:                     } elsif ($usec eq '') {
1.420     albertel 9249:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9250:                             $secmatch = 1;
                   9251:                         }
                   9252:                     } else {
                   9253:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9254:                             $secmatch = 1;
                   9255:                         }
                   9256:                     }
                   9257:                     if (!$secmatch) {
                   9258:                         next;
                   9259:                     }
1.288     raeburn  9260:                 }
1.419     raeburn  9261:                 if ($usec eq '') {
                   9262:                     $usec = 'none';
                   9263:                 }
1.275     raeburn  9264:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9265:                     if ($hidepriv) {
1.1075.2.36  raeburn  9266:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9267:                             (!$nothide{$uname.':'.$udom})) {
                   9268:                             next;
                   9269:                         }
                   9270:                     }
1.503     raeburn  9271:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9272:                         $status = 'previous';
                   9273:                     } elsif ($start > $now) {
                   9274:                         $status = 'future';
                   9275:                     } else {
                   9276:                         $status = 'active';
                   9277:                     }
1.277     albertel 9278:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9279:                         if ($status eq $type) {
1.420     albertel 9280:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9281:                                 push(@{$$users{$role}{$user}},$type);
                   9282:                             }
1.288     raeburn  9283:                             $match = 1;
                   9284:                         }
                   9285:                     }
1.419     raeburn  9286:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9287:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9288: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9289:                         }
1.420     albertel 9290:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9291:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9292:                         }
1.609     raeburn  9293:                         if (ref($statushash) eq 'HASH') {
                   9294:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9295:                         }
1.275     raeburn  9296:                     }
                   9297:                 }
                   9298:             }
                   9299:         }
1.290     albertel 9300:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9301:             if ((defined($cdom)) && (defined($cnum))) {
                   9302:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9303:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9304:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9305:                     next if ($owner eq '');
                   9306:                     my ($ownername,$ownerdom);
                   9307:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9308:                         $ownername = $1;
                   9309:                         $ownerdom = $2;
                   9310:                     } else {
                   9311:                         $ownername = $owner;
                   9312:                         $ownerdom = $cdom;
                   9313:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9314:                     }
                   9315:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9316:                     if (defined($userdata) && 
1.609     raeburn  9317: 			!exists($$userdata{$owner})) {
                   9318: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9319:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9320:                             push(@{$seclists{$owner}},'none');
                   9321:                         }
                   9322:                         if (ref($statushash) eq 'HASH') {
                   9323:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9324:                         }
1.290     albertel 9325: 		    }
1.279     raeburn  9326:                 }
                   9327:             }
                   9328:         }
1.419     raeburn  9329:         foreach my $user (keys(%seclists)) {
                   9330:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9331:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9332:         }
1.275     raeburn  9333:     }
                   9334:     return;
                   9335: }
                   9336: 
1.288     raeburn  9337: sub get_user_info {
                   9338:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9339:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9340: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9341:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9342:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9343:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9344:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9345:     return;
                   9346: }
1.275     raeburn  9347: 
1.472     raeburn  9348: ###############################################
                   9349: 
                   9350: =pod
                   9351: 
                   9352: =item * &get_user_quota()
                   9353: 
1.1075.2.41  raeburn  9354: Retrieves quota assigned for storage of user files.
                   9355: Default is to report quota for portfolio files.
1.472     raeburn  9356: 
                   9357: Incoming parameters:
                   9358: 1. user's username
                   9359: 2. user's domain
1.1075.2.41  raeburn  9360: 3. quota name - portfolio, author, or course
                   9361:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  9362: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  9363:    course
1.472     raeburn  9364: 
                   9365: Returns:
1.1075.2.58  raeburn  9366: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9367: 2. (Optional) Type of setting: custom or default
                   9368:    (individually assigned or default for user's 
                   9369:    institutional status).
                   9370: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9371:    or student - types as defined in localenroll::inst_usertypes 
                   9372:    for user's domain, which determines default quota for user.
                   9373: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9374: 
                   9375: If a value has been stored in the user's environment, 
1.536     raeburn  9376: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  9377: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9378: 
                   9379: =cut
                   9380: 
                   9381: ###############################################
                   9382: 
                   9383: 
                   9384: sub get_user_quota {
1.1075.2.42  raeburn  9385:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9386:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9387:     if (!defined($udom)) {
                   9388:         $udom = $env{'user.domain'};
                   9389:     }
                   9390:     if (!defined($uname)) {
                   9391:         $uname = $env{'user.name'};
                   9392:     }
                   9393:     if (($udom eq '' || $uname eq '') ||
                   9394:         ($udom eq 'public') && ($uname eq 'public')) {
                   9395:         $quota = 0;
1.536     raeburn  9396:         $quotatype = 'default';
                   9397:         $defquota = 0; 
1.472     raeburn  9398:     } else {
1.536     raeburn  9399:         my $inststatus;
1.1075.2.41  raeburn  9400:         if ($quotaname eq 'course') {
                   9401:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9402:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9403:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9404:             } else {
                   9405:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9406:                 $quota = $cenv{'internal.uploadquota'};
                   9407:             }
1.536     raeburn  9408:         } else {
1.1075.2.41  raeburn  9409:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9410:                 if ($quotaname eq 'author') {
                   9411:                     $quota = $env{'environment.authorquota'};
                   9412:                 } else {
                   9413:                     $quota = $env{'environment.portfolioquota'};
                   9414:                 }
                   9415:                 $inststatus = $env{'environment.inststatus'};
                   9416:             } else {
                   9417:                 my %userenv = 
                   9418:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9419:                                          'authorquota','inststatus'],$udom,$uname);
                   9420:                 my ($tmp) = keys(%userenv);
                   9421:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9422:                     if ($quotaname eq 'author') {
                   9423:                         $quota = $userenv{'authorquota'};
                   9424:                     } else {
                   9425:                         $quota = $userenv{'portfolioquota'};
                   9426:                     }
                   9427:                     $inststatus = $userenv{'inststatus'};
                   9428:                 } else {
                   9429:                     undef(%userenv);
                   9430:                 }
                   9431:             }
                   9432:         }
                   9433:         if ($quota eq '' || wantarray) {
                   9434:             if ($quotaname eq 'course') {
                   9435:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  9436:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   9437:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  9438:                     $defquota = $domdefs{$crstype.'quota'};
                   9439:                 }
                   9440:                 if ($defquota eq '') {
                   9441:                     $defquota = 500;
                   9442:                 }
1.1075.2.41  raeburn  9443:             } else {
                   9444:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9445:             }
                   9446:             if ($quota eq '') {
                   9447:                 $quota = $defquota;
                   9448:                 $quotatype = 'default';
                   9449:             } else {
                   9450:                 $quotatype = 'custom';
                   9451:             }
1.472     raeburn  9452:         }
                   9453:     }
1.536     raeburn  9454:     if (wantarray) {
                   9455:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9456:     } else {
                   9457:         return $quota;
                   9458:     }
1.472     raeburn  9459: }
                   9460: 
                   9461: ###############################################
                   9462: 
                   9463: =pod
                   9464: 
                   9465: =item * &default_quota()
                   9466: 
1.536     raeburn  9467: Retrieves default quota assigned for storage of user portfolio files,
                   9468: given an (optional) user's institutional status.
1.472     raeburn  9469: 
                   9470: Incoming parameters:
1.1075.2.42  raeburn  9471: 
1.472     raeburn  9472: 1. domain
1.536     raeburn  9473: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9474:    status types (e.g., faculty, staff, student etc.)
                   9475:    which apply to the user for whom the default is being retrieved.
                   9476:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9477:    default quota will be returned.
                   9478: 3.  quota name - portfolio, author, or course
                   9479:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9480: 
                   9481: Returns:
1.1075.2.42  raeburn  9482: 
1.1075.2.58  raeburn  9483: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9484: 2. (Optional) institutional type which determined the value of the
                   9485:    default quota.
1.472     raeburn  9486: 
                   9487: If a value has been stored in the domain's configuration db,
                   9488: it will return that, otherwise it returns 20 (for backwards 
                   9489: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9490: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9491: 
1.536     raeburn  9492: If the user's status includes multiple types (e.g., staff and student),
                   9493: the largest default quota which applies to the user determines the
                   9494: default quota returned.
                   9495: 
1.472     raeburn  9496: =cut
                   9497: 
                   9498: ###############################################
                   9499: 
                   9500: 
                   9501: sub default_quota {
1.1075.2.41  raeburn  9502:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9503:     my ($defquota,$settingstatus);
                   9504:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9505:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9506:     my $key = 'defaultquota';
                   9507:     if ($quotaname eq 'author') {
                   9508:         $key = 'authorquota';
                   9509:     }
1.622     raeburn  9510:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9511:         if ($inststatus ne '') {
1.765     raeburn  9512:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9513:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9514:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9515:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9516:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9517:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9518:                             $settingstatus = $item;
1.1075.2.41  raeburn  9519:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9520:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9521:                             $settingstatus = $item;
                   9522:                         }
                   9523:                     }
1.1075.2.41  raeburn  9524:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9525:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9526:                         if ($defquota eq '') {
                   9527:                             $defquota = $quotahash{'quotas'}{$item};
                   9528:                             $settingstatus = $item;
                   9529:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9530:                             $defquota = $quotahash{'quotas'}{$item};
                   9531:                             $settingstatus = $item;
                   9532:                         }
1.536     raeburn  9533:                     }
                   9534:                 }
                   9535:             }
                   9536:         }
                   9537:         if ($defquota eq '') {
1.1075.2.41  raeburn  9538:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9539:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9540:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9541:                 $defquota = $quotahash{'quotas'}{'default'};
                   9542:             }
1.536     raeburn  9543:             $settingstatus = 'default';
1.1075.2.42  raeburn  9544:             if ($defquota eq '') {
                   9545:                 if ($quotaname eq 'author') {
                   9546:                     $defquota = 500;
                   9547:                 }
                   9548:             }
1.536     raeburn  9549:         }
                   9550:     } else {
                   9551:         $settingstatus = 'default';
1.1075.2.41  raeburn  9552:         if ($quotaname eq 'author') {
                   9553:             $defquota = 500;
                   9554:         } else {
                   9555:             $defquota = 20;
                   9556:         }
1.536     raeburn  9557:     }
                   9558:     if (wantarray) {
                   9559:         return ($defquota,$settingstatus);
1.472     raeburn  9560:     } else {
1.536     raeburn  9561:         return $defquota;
1.472     raeburn  9562:     }
                   9563: }
                   9564: 
1.1075.2.41  raeburn  9565: ###############################################
                   9566: 
                   9567: =pod
                   9568: 
1.1075.2.42  raeburn  9569: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9570: 
                   9571: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9572: of existing file within authoring space will cause quota for the authoring
                   9573: space to be exceeded.
                   9574: 
                   9575: Same, if upload of a file directly to a course/community via Course Editor
                   9576: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9577: 
1.1075.2.61  raeburn  9578: Inputs: 7 
1.1075.2.42  raeburn  9579: 1. username or coursenum
1.1075.2.41  raeburn  9580: 2. domain
1.1075.2.42  raeburn  9581: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9582: 4. filename of file for which action is being requested
                   9583: 5. filesize (kB) of file
                   9584: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9585: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9586: 
                   9587: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9588:          otherwise return null.
                   9589: 
1.1075.2.42  raeburn  9590: =back
                   9591: 
1.1075.2.41  raeburn  9592: =cut
                   9593: 
1.1075.2.42  raeburn  9594: sub excess_filesize_warning {
1.1075.2.59  raeburn  9595:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9596:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9597:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9598:     if ($context eq 'author') {
                   9599:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9600:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9601:     } else {
                   9602:         foreach my $subdir ('docs','supplemental') {
                   9603:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9604:         }
                   9605:     }
1.1075.2.41  raeburn  9606:     $disk_quota = int($disk_quota * 1000);
                   9607:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9608:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9609:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9610:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9611:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9612:                             $disk_quota,$current_disk_usage).
                   9613:                '</p>';
                   9614:     }
                   9615:     return;
                   9616: }
                   9617: 
                   9618: ###############################################
                   9619: 
                   9620: 
1.384     raeburn  9621: sub get_secgrprole_info {
                   9622:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9623:     my %sections_count = &get_sections($cdom,$cnum);
                   9624:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9625:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9626:     my @groups = sort(keys(%curr_groups));
                   9627:     my $allroles = [];
                   9628:     my $rolehash;
                   9629:     my $accesshash = {
                   9630:                      active => 'Currently has access',
                   9631:                      future => 'Will have future access',
                   9632:                      previous => 'Previously had access',
                   9633:                   };
                   9634:     if ($needroles) {
                   9635:         $rolehash = {'all' => 'all'};
1.385     albertel 9636:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9637: 	if (&Apache::lonnet::error(%user_roles)) {
                   9638: 	    undef(%user_roles);
                   9639: 	}
                   9640:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9641:             my ($role)=split(/\:/,$item,2);
                   9642:             if ($role eq 'cr') { next; }
                   9643:             if ($role =~ /^cr/) {
                   9644:                 $$rolehash{$role} = (split('/',$role))[3];
                   9645:             } else {
                   9646:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9647:             }
                   9648:         }
                   9649:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9650:             push(@{$allroles},$key);
                   9651:         }
                   9652:         push (@{$allroles},'st');
                   9653:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9654:     }
                   9655:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9656: }
                   9657: 
1.555     raeburn  9658: sub user_picker {
1.1075.2.127  raeburn  9659:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  9660:     my $currdom = $dom;
1.1075.2.114  raeburn  9661:     my @alldoms = &Apache::lonnet::all_domains();
                   9662:     if (@alldoms == 1) {
                   9663:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   9664:                                                ['directorysrch'],$alldoms[0]);
                   9665:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   9666:         my $showdom = $domdesc;
                   9667:         if ($showdom eq '') {
                   9668:             $showdom = $dom;
                   9669:         }
                   9670:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   9671:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   9672:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   9673:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   9674:             }
                   9675:         }
                   9676:     }
1.555     raeburn  9677:     my %curr_selected = (
                   9678:                         srchin => 'dom',
1.580     raeburn  9679:                         srchby => 'lastname',
1.555     raeburn  9680:                       );
                   9681:     my $srchterm;
1.625     raeburn  9682:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9683:         if ($srch->{'srchby'} ne '') {
                   9684:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9685:         }
                   9686:         if ($srch->{'srchin'} ne '') {
                   9687:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9688:         }
                   9689:         if ($srch->{'srchtype'} ne '') {
                   9690:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9691:         }
                   9692:         if ($srch->{'srchdomain'} ne '') {
                   9693:             $currdom = $srch->{'srchdomain'};
                   9694:         }
                   9695:         $srchterm = $srch->{'srchterm'};
                   9696:     }
1.1075.2.98  raeburn  9697:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9698:                     'usr'       => 'Search criteria',
1.563     raeburn  9699:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9700:                     'uname'     => 'username',
                   9701:                     'lastname'  => 'last name',
1.555     raeburn  9702:                     'lastfirst' => 'last name, first name',
1.558     albertel 9703:                     'crs'       => 'in this course',
1.576     raeburn  9704:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9705:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9706:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9707:                     'exact'     => 'is',
                   9708:                     'contains'  => 'contains',
1.569     raeburn  9709:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  9710:                                        );
                   9711:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9712:                     'youm'      => "You must include some text to search for.",
                   9713:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9714:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9715:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9716:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9717:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9718:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9719:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9720:                                        );
1.1075.2.98  raeburn  9721:     &html_escape(\%html_lt);
                   9722:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  9723:     my $domform;
1.1075.2.126  raeburn  9724:     my $allow_blank = 1;
1.1075.2.115  raeburn  9725:     if ($fixeddom) {
1.1075.2.126  raeburn  9726:         $allow_blank = 0;
                   9727:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  9728:     } else {
1.1075.2.126  raeburn  9729:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  9730:     }
1.563     raeburn  9731:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9732: 
                   9733:     my @srchins = ('crs','dom','alc','instd');
                   9734: 
                   9735:     foreach my $option (@srchins) {
                   9736:         # FIXME 'alc' option unavailable until 
                   9737:         #       loncreateuser::print_user_query_page()
                   9738:         #       has been completed.
                   9739:         next if ($option eq 'alc');
1.880     raeburn  9740:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9741:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  9742:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  9743:         if ($curr_selected{'srchin'} eq $option) {
                   9744:             $srchinsel .= ' 
1.1075.2.98  raeburn  9745:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9746:         } else {
                   9747:             $srchinsel .= '
1.1075.2.98  raeburn  9748:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9749:         }
1.555     raeburn  9750:     }
1.563     raeburn  9751:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9752: 
                   9753:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9754:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9755:         if ($curr_selected{'srchby'} eq $option) {
                   9756:             $srchbysel .= '
1.1075.2.98  raeburn  9757:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9758:         } else {
                   9759:             $srchbysel .= '
1.1075.2.98  raeburn  9760:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9761:          }
                   9762:     }
                   9763:     $srchbysel .= "\n  </select>\n";
                   9764: 
                   9765:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9766:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9767:         if ($curr_selected{'srchtype'} eq $option) {
                   9768:             $srchtypesel .= '
1.1075.2.98  raeburn  9769:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9770:         } else {
                   9771:             $srchtypesel .= '
1.1075.2.98  raeburn  9772:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9773:         }
                   9774:     }
                   9775:     $srchtypesel .= "\n  </select>\n";
                   9776: 
1.558     albertel 9777:     my ($newuserscript,$new_user_create);
1.994     raeburn  9778:     my $context_dom = $env{'request.role.domain'};
                   9779:     if ($context eq 'requestcrs') {
                   9780:         if ($env{'form.coursedom'} ne '') { 
                   9781:             $context_dom = $env{'form.coursedom'};
                   9782:         }
                   9783:     }
1.556     raeburn  9784:     if ($forcenewuser) {
1.576     raeburn  9785:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9786:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9787:                 if ($cancreate) {
                   9788:                     $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>';
                   9789:                 } else {
1.799     bisitz   9790:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9791:                     my %usertypetext = (
                   9792:                         official   => 'institutional',
                   9793:                         unofficial => 'non-institutional',
                   9794:                     );
1.799     bisitz   9795:                     $new_user_create = '<p class="LC_warning">'
                   9796:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9797:                                       .' '
                   9798:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9799:                                           ,'<a href="'.$helplink.'">','</a>')
                   9800:                                       .'</p><br />';
1.627     raeburn  9801:                 }
1.576     raeburn  9802:             }
                   9803:         }
                   9804: 
1.556     raeburn  9805:         $newuserscript = <<"ENDSCRIPT";
                   9806: 
1.570     raeburn  9807: function setSearch(createnew,callingForm) {
1.556     raeburn  9808:     if (createnew == 1) {
1.570     raeburn  9809:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9810:             if (callingForm.srchby.options[i].value == 'uname') {
                   9811:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9812:             }
                   9813:         }
1.570     raeburn  9814:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9815:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9816: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9817:             }
                   9818:         }
1.570     raeburn  9819:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9820:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9821:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9822:             }
                   9823:         }
1.570     raeburn  9824:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9825:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9826:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9827:             }
                   9828:         }
                   9829:     }
                   9830: }
                   9831: ENDSCRIPT
1.558     albertel 9832: 
1.556     raeburn  9833:     }
                   9834: 
1.555     raeburn  9835:     my $output = <<"END_BLOCK";
1.556     raeburn  9836: <script type="text/javascript">
1.824     bisitz   9837: // <![CDATA[
1.570     raeburn  9838: function validateEntry(callingForm) {
1.558     albertel 9839: 
1.556     raeburn  9840:     var checkok = 1;
1.558     albertel 9841:     var srchin;
1.570     raeburn  9842:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9843: 	if ( callingForm.srchin[i].checked ) {
                   9844: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9845: 	}
                   9846:     }
                   9847: 
1.570     raeburn  9848:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9849:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9850:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9851:     var srchterm =  callingForm.srchterm.value;
                   9852:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9853:     var msg = "";
                   9854: 
                   9855:     if (srchterm == "") {
                   9856:         checkok = 0;
1.1075.2.98  raeburn  9857:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  9858:     }
                   9859: 
1.569     raeburn  9860:     if (srchtype== 'begins') {
                   9861:         if (srchterm.length < 2) {
                   9862:             checkok = 0;
1.1075.2.98  raeburn  9863:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  9864:         }
                   9865:     }
                   9866: 
1.556     raeburn  9867:     if (srchtype== 'contains') {
                   9868:         if (srchterm.length < 3) {
                   9869:             checkok = 0;
1.1075.2.98  raeburn  9870:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  9871:         }
                   9872:     }
                   9873:     if (srchin == 'instd') {
                   9874:         if (srchdomain == '') {
                   9875:             checkok = 0;
1.1075.2.98  raeburn  9876:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  9877:         }
                   9878:     }
                   9879:     if (srchin == 'dom') {
                   9880:         if (srchdomain == '') {
                   9881:             checkok = 0;
1.1075.2.98  raeburn  9882:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  9883:         }
                   9884:     }
                   9885:     if (srchby == 'lastfirst') {
                   9886:         if (srchterm.indexOf(",") == -1) {
                   9887:             checkok = 0;
1.1075.2.98  raeburn  9888:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  9889:         }
                   9890:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9891:             checkok = 0;
1.1075.2.98  raeburn  9892:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  9893:         }
                   9894:     }
                   9895:     if (checkok == 0) {
1.1075.2.98  raeburn  9896:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  9897:         return;
                   9898:     }
                   9899:     if (checkok == 1) {
1.570     raeburn  9900:         callingForm.submit();
1.556     raeburn  9901:     }
                   9902: }
                   9903: 
                   9904: $newuserscript
                   9905: 
1.824     bisitz   9906: // ]]>
1.556     raeburn  9907: </script>
1.558     albertel 9908: 
                   9909: $new_user_create
                   9910: 
1.555     raeburn  9911: END_BLOCK
1.558     albertel 9912: 
1.876     raeburn  9913:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  9914:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  9915:                $domform.
                   9916:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  9917:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  9918:                $srchbysel.
                   9919:                $srchtypesel. 
                   9920:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9921:                $srchinsel.
                   9922:                &Apache::lonhtmlcommon::row_closure(1). 
                   9923:                &Apache::lonhtmlcommon::end_pick_box().
                   9924:                '<br />';
1.1075.2.114  raeburn  9925:     return ($output,1);
1.555     raeburn  9926: }
                   9927: 
1.612     raeburn  9928: sub user_rule_check {
1.615     raeburn  9929:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  9930:     my ($response,%inst_response);
1.612     raeburn  9931:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  9932:         if (keys(%{$usershash}) > 1) {
                   9933:             my (%by_username,%by_id,%userdoms);
                   9934:             my $checkid;
1.612     raeburn  9935:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  9936:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   9937:                     $checkid = 1;
                   9938:                 }
                   9939:             }
                   9940:             foreach my $user (keys(%{$usershash})) {
                   9941:                 my ($uname,$udom) = split(/:/,$user);
                   9942:                 if ($checkid) {
                   9943:                     if (ref($usershash->{$user}) eq 'HASH') {
                   9944:                         if ($usershash->{$user}->{'id'} ne '') {
                   9945:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   9946:                             $userdoms{$udom} = 1;
                   9947:                             if (ref($inst_results) eq 'HASH') {
                   9948:                                 $inst_results->{$uname.':'.$udom} = {};
                   9949:                             }
                   9950:                         }
                   9951:                     }
                   9952:                 } else {
                   9953:                     $by_username{$udom}{$uname} = 1;
                   9954:                     $userdoms{$udom} = 1;
                   9955:                     if (ref($inst_results) eq 'HASH') {
                   9956:                         $inst_results->{$uname.':'.$udom} = {};
                   9957:                     }
                   9958:                 }
                   9959:             }
                   9960:             foreach my $udom (keys(%userdoms)) {
                   9961:                 if (!$got_rules->{$udom}) {
                   9962:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9963:                                                              ['usercreation'],$udom);
                   9964:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9965:                         foreach my $item ('username','id') {
                   9966:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9967:                                 $$curr_rules{$udom}{$item} =
                   9968:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   9969:                             }
                   9970:                         }
                   9971:                     }
                   9972:                     $got_rules->{$udom} = 1;
                   9973:                 }
                   9974:             }
                   9975:             if ($checkid) {
                   9976:                 foreach my $udom (keys(%by_id)) {
                   9977:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   9978:                     if ($outcome eq 'ok') {
                   9979:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   9980:                             my $uname = $by_id{$udom}{$id};
                   9981:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9982:                         }
                   9983:                         if (ref($results) eq 'HASH') {
                   9984:                             foreach my $uname (keys(%{$results})) {
                   9985:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   9986:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   9987:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9988:                                 }
                   9989:                             }
                   9990:                         }
                   9991:                     }
1.612     raeburn  9992:                 }
1.615     raeburn  9993:             } else {
1.1075.2.99  raeburn  9994:                 foreach my $udom (keys(%by_username)) {
                   9995:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   9996:                     if ($outcome eq 'ok') {
                   9997:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   9998:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9999:                         }
                   10000:                         if (ref($results) eq 'HASH') {
                   10001:                             foreach my $uname (keys(%{$results})) {
                   10002:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10003:                             }
                   10004:                         }
                   10005:                     }
                   10006:                 }
1.612     raeburn  10007:             }
1.1075.2.99  raeburn  10008:         } elsif (keys(%{$usershash}) == 1) {
                   10009:             my $user = (keys(%{$usershash}))[0];
                   10010:             my ($uname,$udom) = split(/:/,$user);
                   10011:             if (($udom ne '') && ($uname ne '')) {
                   10012:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10013:                     if (ref($checks) eq 'HASH') {
                   10014:                         if (defined($checks->{'username'})) {
                   10015:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   10016:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10017:                         } elsif (defined($checks->{'id'})) {
                   10018:                             if ($usershash->{$user}->{'id'} ne '') {
                   10019:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10020:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10021:                                                                   $usershash->{$user}->{'id'});
                   10022:                             } else {
                   10023:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10024:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10025:                             }
                   10026:                         }
                   10027:                     } else {
                   10028:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10029:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10030:                        return;
                   10031:                     }
                   10032:                     if (!$got_rules->{$udom}) {
                   10033:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10034:                                                                  ['usercreation'],$udom);
                   10035:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10036:                             foreach my $item ('username','id') {
                   10037:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10038:                                    $$curr_rules{$udom}{$item} =
                   10039:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10040:                                 }
                   10041:                             }
1.585     raeburn  10042:                         }
1.1075.2.99  raeburn  10043:                         $got_rules->{$udom} = 1;
1.585     raeburn  10044:                     }
                   10045:                 }
1.1075.2.99  raeburn  10046:             } else {
                   10047:                 return;
                   10048:             }
                   10049:         } else {
                   10050:             return;
                   10051:         }
                   10052:         foreach my $user (keys(%{$usershash})) {
                   10053:             my ($uname,$udom) = split(/:/,$user);
                   10054:             next if (($udom eq '') || ($uname eq ''));
                   10055:             my $id;
                   10056:             if (ref($inst_results) eq 'HASH') {
                   10057:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10058:                     $id = $inst_results->{$user}->{'id'};
                   10059:                 }
                   10060:             }
                   10061:             if ($id eq '') {
                   10062:                 if (ref($usershash->{$user})) {
                   10063:                     $id = $usershash->{$user}->{'id'};
                   10064:                 }
1.585     raeburn  10065:             }
1.612     raeburn  10066:             foreach my $item (keys(%{$checks})) {
                   10067:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10068:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10069:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  10070:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10071:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10072:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10073:                                 if ($rule_check{$rule}) {
                   10074:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  10075:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10076:                                         if (ref($inst_results) eq 'HASH') {
                   10077:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10078:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10079:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  10080:                                                 } elsif ($item eq 'id') {
                   10081:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10082:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10083:                                                     }
1.615     raeburn  10084:                                                 }
1.612     raeburn  10085:                                             }
                   10086:                                         }
1.615     raeburn  10087:                                     }
                   10088:                                     last;
1.585     raeburn  10089:                                 }
                   10090:                             }
                   10091:                         }
                   10092:                     }
                   10093:                 }
                   10094:             }
                   10095:         }
                   10096:     }
1.612     raeburn  10097:     return;
                   10098: }
                   10099: 
                   10100: sub user_rule_formats {
                   10101:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10102:     my %text = ( 
                   10103:                  'username' => 'Usernames',
                   10104:                  'id'       => 'IDs',
                   10105:                );
                   10106:     my $output;
                   10107:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10108:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10109:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  10110:             $output = '<br />'.
                   10111:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10112:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10113:                       ' <ul>';
1.612     raeburn  10114:             foreach my $rule (@{$ruleorder}) {
                   10115:                 if (ref($curr_rules) eq 'ARRAY') {
                   10116:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10117:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10118:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10119:                                         $rules->{$rule}{'desc'}.'</li>';
                   10120:                         }
                   10121:                     }
                   10122:                 }
                   10123:             }
                   10124:             $output .= '</ul>';
                   10125:         }
                   10126:     }
                   10127:     return $output;
                   10128: }
                   10129: 
                   10130: sub instrule_disallow_msg {
1.615     raeburn  10131:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10132:     my $response;
                   10133:     my %text = (
                   10134:                   item   => 'username',
                   10135:                   items  => 'usernames',
                   10136:                   match  => 'matches',
                   10137:                   do     => 'does',
                   10138:                   action => 'a username',
                   10139:                   one    => 'one',
                   10140:                );
                   10141:     if ($count > 1) {
                   10142:         $text{'item'} = 'usernames';
                   10143:         $text{'match'} ='match';
                   10144:         $text{'do'} = 'do';
                   10145:         $text{'action'} = 'usernames',
                   10146:         $text{'one'} = 'ones';
                   10147:     }
                   10148:     if ($checkitem eq 'id') {
                   10149:         $text{'items'} = 'IDs';
                   10150:         $text{'item'} = 'ID';
                   10151:         $text{'action'} = 'an ID';
1.615     raeburn  10152:         if ($count > 1) {
                   10153:             $text{'item'} = 'IDs';
                   10154:             $text{'action'} = 'IDs';
                   10155:         }
1.612     raeburn  10156:     }
1.674     bisitz   10157:     $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  10158:     if ($mode eq 'upload') {
                   10159:         if ($checkitem eq 'username') {
                   10160:             $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'}.");
                   10161:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10162:             $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  10163:         }
1.669     raeburn  10164:     } elsif ($mode eq 'selfcreate') {
                   10165:         if ($checkitem eq 'id') {
                   10166:             $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.");
                   10167:         }
1.615     raeburn  10168:     } else {
                   10169:         if ($checkitem eq 'username') {
                   10170:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10171:         } elsif ($checkitem eq 'id') {
                   10172:             $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.");
                   10173:         }
1.612     raeburn  10174:     }
                   10175:     return $response;
1.585     raeburn  10176: }
                   10177: 
1.624     raeburn  10178: sub personal_data_fieldtitles {
                   10179:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10180:                         id => 'Student/Employee ID',
                   10181:                         permanentemail => 'E-mail address',
                   10182:                         lastname => 'Last Name',
                   10183:                         firstname => 'First Name',
                   10184:                         middlename => 'Middle Name',
                   10185:                         generation => 'Generation',
                   10186:                         gen => 'Generation',
1.765     raeburn  10187:                         inststatus => 'Affiliation',
1.624     raeburn  10188:                    );
                   10189:     return %fieldtitles;
                   10190: }
                   10191: 
1.642     raeburn  10192: sub sorted_inst_types {
                   10193:     my ($dom) = @_;
1.1075.2.70  raeburn  10194:     my ($usertypes,$order);
                   10195:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10196:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10197:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10198:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10199:     } else {
                   10200:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10201:     }
1.642     raeburn  10202:     my $othertitle = &mt('All users');
                   10203:     if ($env{'request.course.id'}) {
1.668     raeburn  10204:         $othertitle  = &mt('Any users');
1.642     raeburn  10205:     }
                   10206:     my @types;
                   10207:     if (ref($order) eq 'ARRAY') {
                   10208:         @types = @{$order};
                   10209:     }
                   10210:     if (@types == 0) {
                   10211:         if (ref($usertypes) eq 'HASH') {
                   10212:             @types = sort(keys(%{$usertypes}));
                   10213:         }
                   10214:     }
                   10215:     if (keys(%{$usertypes}) > 0) {
                   10216:         $othertitle = &mt('Other users');
                   10217:     }
                   10218:     return ($othertitle,$usertypes,\@types);
                   10219: }
                   10220: 
1.645     raeburn  10221: sub get_institutional_codes {
                   10222:     my ($settings,$allcourses,$LC_code) = @_;
                   10223: # Get complete list of course sections to update
                   10224:     my @currsections = ();
                   10225:     my @currxlists = ();
                   10226:     my $coursecode = $$settings{'internal.coursecode'};
                   10227: 
                   10228:     if ($$settings{'internal.sectionnums'} ne '') {
                   10229:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10230:     }
                   10231: 
                   10232:     if ($$settings{'internal.crosslistings'} ne '') {
                   10233:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10234:     }
                   10235: 
                   10236:     if (@currxlists > 0) {
                   10237:         foreach (@currxlists) {
                   10238:             if (m/^([^:]+):(\w*)$/) {
                   10239:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  10240:                     push(@{$allcourses},$1);
1.645     raeburn  10241:                     $$LC_code{$1} = $2;
                   10242:                 }
                   10243:             }
                   10244:         }
                   10245:     }
                   10246:  
                   10247:     if (@currsections > 0) {
                   10248:         foreach (@currsections) {
                   10249:             if (m/^(\w+):(\w*)$/) {
                   10250:                 my $sec = $coursecode.$1;
                   10251:                 my $lc_sec = $2;
                   10252:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1075.2.119  raeburn  10253:                     push(@{$allcourses},$sec);
1.645     raeburn  10254:                     $$LC_code{$sec} = $lc_sec;
                   10255:                 }
                   10256:             }
                   10257:         }
                   10258:     }
                   10259:     return;
                   10260: }
                   10261: 
1.971     raeburn  10262: sub get_standard_codeitems {
                   10263:     return ('Year','Semester','Department','Number','Section');
                   10264: }
                   10265: 
1.112     bowersj2 10266: =pod
                   10267: 
1.780     raeburn  10268: =head1 Slot Helpers
                   10269: 
                   10270: =over 4
                   10271: 
                   10272: =item * sorted_slots()
                   10273: 
1.1040    raeburn  10274: Sorts an array of slot names in order of an optional sort key,
                   10275: default sort is by slot start time (earliest first). 
1.780     raeburn  10276: 
                   10277: Inputs:
                   10278: 
                   10279: =over 4
                   10280: 
                   10281: slotsarr  - Reference to array of unsorted slot names.
                   10282: 
                   10283: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10284: 
1.1040    raeburn  10285: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10286: 
1.549     albertel 10287: =back
                   10288: 
1.780     raeburn  10289: Returns:
                   10290: 
                   10291: =over 4
                   10292: 
1.1040    raeburn  10293: sorted   - An array of slot names sorted by a specified sort key 
                   10294:            (default sort key is start time of the slot).
1.780     raeburn  10295: 
                   10296: =back
                   10297: 
                   10298: =cut
                   10299: 
                   10300: 
                   10301: sub sorted_slots {
1.1040    raeburn  10302:     my ($slotsarr,$slots,$sortkey) = @_;
                   10303:     if ($sortkey eq '') {
                   10304:         $sortkey = 'starttime';
                   10305:     }
1.780     raeburn  10306:     my @sorted;
                   10307:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10308:         @sorted =
                   10309:             sort {
                   10310:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10311:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10312:                      }
                   10313:                      if (ref($slots->{$a})) { return -1;}
                   10314:                      if (ref($slots->{$b})) { return 1;}
                   10315:                      return 0;
                   10316:                  } @{$slotsarr};
                   10317:     }
                   10318:     return @sorted;
                   10319: }
                   10320: 
1.1040    raeburn  10321: =pod
                   10322: 
                   10323: =item * get_future_slots()
                   10324: 
                   10325: Inputs:
                   10326: 
                   10327: =over 4
                   10328: 
                   10329: cnum - course number
                   10330: 
                   10331: cdom - course domain
                   10332: 
                   10333: now - current UNIX time
                   10334: 
                   10335: symb - optional symb
                   10336: 
                   10337: =back
                   10338: 
                   10339: Returns:
                   10340: 
                   10341: =over 4
                   10342: 
                   10343: sorted_reservable - ref to array of student_schedulable slots currently 
                   10344:                     reservable, ordered by end date of reservation period.
                   10345: 
                   10346: reservable_now - ref to hash of student_schedulable slots currently
                   10347:                  reservable.
                   10348: 
                   10349:     Keys in inner hash are:
                   10350:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  10351:     (b) endreserve: end date of reservation period.
                   10352:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10353:         selected.
1.1040    raeburn  10354: 
                   10355: sorted_future - ref to array of student_schedulable slots reservable in
                   10356:                 the future, ordered by start date of reservation period.
                   10357: 
                   10358: future_reservable - ref to hash of student_schedulable slots reservable
                   10359:                     in the future.
                   10360: 
                   10361:     Keys in inner hash are:
                   10362:     (a) symb: either blank or symb to which slot use is restricted.
                   10363:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  10364:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10365:         selected.
1.1040    raeburn  10366: 
                   10367: =back
                   10368: 
                   10369: =cut
                   10370: 
                   10371: sub get_future_slots {
                   10372:     my ($cnum,$cdom,$now,$symb) = @_;
                   10373:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10374:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10375:     foreach my $slot (keys(%slots)) {
                   10376:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10377:         if ($symb) {
                   10378:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10379:                      ($slots{$slot}->{'symb'} ne $symb));
                   10380:         }
                   10381:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10382:             ($slots{$slot}->{'endtime'} > $now)) {
                   10383:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10384:                 my $userallowed = 0;
                   10385:                 if ($slots{$slot}->{'allowedsections'}) {
                   10386:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10387:                     if (!defined($env{'request.role.sec'})
                   10388:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10389:                         $userallowed=1;
                   10390:                     } else {
                   10391:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10392:                             $userallowed=1;
                   10393:                         }
                   10394:                     }
                   10395:                     unless ($userallowed) {
                   10396:                         if (defined($env{'request.course.groups'})) {
                   10397:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10398:                             foreach my $group (@groups) {
                   10399:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10400:                                     $userallowed=1;
                   10401:                                     last;
                   10402:                                 }
                   10403:                             }
                   10404:                         }
                   10405:                     }
                   10406:                 }
                   10407:                 if ($slots{$slot}->{'allowedusers'}) {
                   10408:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10409:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10410:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10411:                         $userallowed = 1;
                   10412:                     }
                   10413:                 }
                   10414:                 next unless($userallowed);
                   10415:             }
                   10416:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10417:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10418:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  10419:             my $uniqueperiod;
                   10420:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10421:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10422:             }
1.1040    raeburn  10423:             if (($startreserve < $now) &&
                   10424:                 (!$endreserve || $endreserve > $now)) {
                   10425:                 my $lastres = $endreserve;
                   10426:                 if (!$lastres) {
                   10427:                     $lastres = $slots{$slot}->{'starttime'};
                   10428:                 }
                   10429:                 $reservable_now{$slot} = {
                   10430:                                            symb       => $symb,
1.1075.2.104  raeburn  10431:                                            endreserve => $lastres,
                   10432:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  10433:                                          };
                   10434:             } elsif (($startreserve > $now) &&
                   10435:                      (!$endreserve || $endreserve > $startreserve)) {
                   10436:                 $future_reservable{$slot} = {
                   10437:                                               symb         => $symb,
1.1075.2.104  raeburn  10438:                                               startreserve => $startreserve,
                   10439:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10440:                                             };
                   10441:             }
                   10442:         }
                   10443:     }
                   10444:     my @unsorted_reservable = keys(%reservable_now);
                   10445:     if (@unsorted_reservable > 0) {
                   10446:         @sorted_reservable = 
                   10447:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10448:     }
                   10449:     my @unsorted_future = keys(%future_reservable);
                   10450:     if (@unsorted_future > 0) {
                   10451:         @sorted_future =
                   10452:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10453:     }
                   10454:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10455: }
1.780     raeburn  10456: 
                   10457: =pod
                   10458: 
1.1057    foxr     10459: =back
                   10460: 
1.549     albertel 10461: =head1 HTTP Helpers
                   10462: 
                   10463: =over 4
                   10464: 
1.648     raeburn  10465: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10466: 
1.258     albertel 10467: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10468: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10469: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10470: 
                   10471: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10472: $possible_names is an ref to an array of form element names.  As an example:
                   10473: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10474: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10475: 
                   10476: =cut
1.1       albertel 10477: 
1.6       albertel 10478: sub get_unprocessed_cgi {
1.25      albertel 10479:   my ($query,$possible_names)= @_;
1.26      matthew  10480:   # $Apache::lonxml::debug=1;
1.356     albertel 10481:   foreach my $pair (split(/&/,$query)) {
                   10482:     my ($name, $value) = split(/=/,$pair);
1.369     www      10483:     $name = &unescape($name);
1.25      albertel 10484:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10485:       $value =~ tr/+/ /;
                   10486:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10487:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10488:     }
1.16      harris41 10489:   }
1.6       albertel 10490: }
                   10491: 
1.112     bowersj2 10492: =pod
                   10493: 
1.648     raeburn  10494: =item * &cacheheader() 
1.112     bowersj2 10495: 
                   10496: returns cache-controlling header code
                   10497: 
                   10498: =cut
                   10499: 
1.7       albertel 10500: sub cacheheader {
1.258     albertel 10501:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10502:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10503:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10504:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10505:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10506:     return $output;
1.7       albertel 10507: }
                   10508: 
1.112     bowersj2 10509: =pod
                   10510: 
1.648     raeburn  10511: =item * &no_cache($r) 
1.112     bowersj2 10512: 
                   10513: specifies header code to not have cache
                   10514: 
                   10515: =cut
                   10516: 
1.9       albertel 10517: sub no_cache {
1.216     albertel 10518:     my ($r) = @_;
                   10519:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10520: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10521:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10522:     $r->no_cache(1);
                   10523:     $r->header_out("Expires" => $date);
                   10524:     $r->header_out("Pragma" => "no-cache");
1.123     www      10525: }
                   10526: 
                   10527: sub content_type {
1.181     albertel 10528:     my ($r,$type,$charset) = @_;
1.299     foxr     10529:     if ($r) {
                   10530: 	#  Note that printout.pl calls this with undef for $r.
                   10531: 	&no_cache($r);
                   10532:     }
1.258     albertel 10533:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10534:     unless ($charset) {
                   10535: 	$charset=&Apache::lonlocal::current_encoding;
                   10536:     }
                   10537:     if ($charset) { $type.='; charset='.$charset; }
                   10538:     if ($r) {
                   10539: 	$r->content_type($type);
                   10540:     } else {
                   10541: 	print("Content-type: $type\n\n");
                   10542:     }
1.9       albertel 10543: }
1.25      albertel 10544: 
1.112     bowersj2 10545: =pod
                   10546: 
1.648     raeburn  10547: =item * &add_to_env($name,$value) 
1.112     bowersj2 10548: 
1.258     albertel 10549: adds $name to the %env hash with value
1.112     bowersj2 10550: $value, if $name already exists, the entry is converted to an array
                   10551: reference and $value is added to the array.
                   10552: 
                   10553: =cut
                   10554: 
1.25      albertel 10555: sub add_to_env {
                   10556:   my ($name,$value)=@_;
1.258     albertel 10557:   if (defined($env{$name})) {
                   10558:     if (ref($env{$name})) {
1.25      albertel 10559:       #already have multiple values
1.258     albertel 10560:       push(@{ $env{$name} },$value);
1.25      albertel 10561:     } else {
                   10562:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10563:       my $first=$env{$name};
                   10564:       undef($env{$name});
                   10565:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10566:     }
                   10567:   } else {
1.258     albertel 10568:     $env{$name}=$value;
1.25      albertel 10569:   }
1.31      albertel 10570: }
1.149     albertel 10571: 
                   10572: =pod
                   10573: 
1.648     raeburn  10574: =item * &get_env_multiple($name) 
1.149     albertel 10575: 
1.258     albertel 10576: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10577: values may be defined and end up as an array ref.
                   10578: 
                   10579: returns an array of values
                   10580: 
                   10581: =cut
                   10582: 
                   10583: sub get_env_multiple {
                   10584:     my ($name) = @_;
                   10585:     my @values;
1.258     albertel 10586:     if (defined($env{$name})) {
1.149     albertel 10587:         # exists is it an array
1.258     albertel 10588:         if (ref($env{$name})) {
                   10589:             @values=@{ $env{$name} };
1.149     albertel 10590:         } else {
1.258     albertel 10591:             $values[0]=$env{$name};
1.149     albertel 10592:         }
                   10593:     }
                   10594:     return(@values);
                   10595: }
                   10596: 
1.660     raeburn  10597: sub ask_for_embedded_content {
                   10598:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10599:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  10600:         %currsubfile,%unused,$rem);
1.1071    raeburn  10601:     my $counter = 0;
                   10602:     my $numnew = 0;
1.987     raeburn  10603:     my $numremref = 0;
                   10604:     my $numinvalid = 0;
                   10605:     my $numpathchg = 0;
                   10606:     my $numexisting = 0;
1.1071    raeburn  10607:     my $numunused = 0;
                   10608:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10609:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10610:     my $heading = &mt('Upload embedded files');
                   10611:     my $buttontext = &mt('Upload');
                   10612: 
1.1075.2.11  raeburn  10613:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10614:         if ($actionurl eq '/adm/dependencies') {
                   10615:             $navmap = Apache::lonnavmaps::navmap->new();
                   10616:         }
                   10617:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10618:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10619:     }
1.1075.2.35  raeburn  10620:     if (($actionurl eq '/adm/portfolio') ||
                   10621:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10622:         my $current_path='/';
                   10623:         if ($env{'form.currentpath'}) {
                   10624:             $current_path = $env{'form.currentpath'};
                   10625:         }
                   10626:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10627:             $udom = $cdom;
                   10628:             $uname = $cnum;
1.984     raeburn  10629:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10630:         } else {
                   10631:             $udom = $env{'user.domain'};
                   10632:             $uname = $env{'user.name'};
                   10633:             $url = '/userfiles/portfolio';
                   10634:         }
1.987     raeburn  10635:         $toplevel = $url.'/';
1.984     raeburn  10636:         $url .= $current_path;
                   10637:         $getpropath = 1;
1.987     raeburn  10638:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10639:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10640:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10641:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10642:         $toplevel = $url;
1.984     raeburn  10643:         if ($rest ne '') {
1.987     raeburn  10644:             $url .= $rest;
                   10645:         }
                   10646:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10647:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10648:             $url = $args->{'docs_url'};
                   10649:             $toplevel = $url;
1.1075.2.11  raeburn  10650:             if ($args->{'context'} eq 'paste') {
                   10651:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10652:                 ($path) =
                   10653:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10654:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10655:                 $fileloc =~ s{^/}{};
                   10656:             }
1.1071    raeburn  10657:         }
                   10658:     } elsif ($actionurl eq '/adm/dependencies') {
                   10659:         if ($env{'request.course.id'} ne '') {
                   10660:             if (ref($args) eq 'HASH') {
                   10661:                 $url = $args->{'docs_url'};
                   10662:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  10663:                 $toplevel = $url;
                   10664:                 unless ($toplevel =~ m{^/}) {
                   10665:                     $toplevel = "/$url";
                   10666:                 }
1.1075.2.11  raeburn  10667:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  10668:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10669:                     $path = $1;
                   10670:                 } else {
                   10671:                     ($path) =
                   10672:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10673:                 }
1.1075.2.79  raeburn  10674:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10675:                     $fileloc = $toplevel;
                   10676:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10677:                     my ($udom,$uname,$fname) =
                   10678:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10679:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10680:                 } else {
                   10681:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10682:                 }
1.1071    raeburn  10683:                 $fileloc =~ s{^/}{};
                   10684:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10685:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10686:             }
1.987     raeburn  10687:         }
1.1075.2.35  raeburn  10688:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10689:         $udom = $cdom;
                   10690:         $uname = $cnum;
                   10691:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10692:         $toplevel = $url;
                   10693:         $path = $url;
                   10694:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10695:         $fileloc =~ s{^/}{};
                   10696:     }
                   10697:     foreach my $file (keys(%{$allfiles})) {
                   10698:         my $embed_file;
                   10699:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10700:             $embed_file = $1;
                   10701:         } else {
                   10702:             $embed_file = $file;
                   10703:         }
1.1075.2.55  raeburn  10704:         my ($absolutepath,$cleaned_file);
                   10705:         if ($embed_file =~ m{^\w+://}) {
                   10706:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  10707:             $newfiles{$cleaned_file} = 1;
                   10708:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10709:         } else {
1.1075.2.55  raeburn  10710:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10711:             if ($embed_file =~ m{^/}) {
                   10712:                 $absolutepath = $embed_file;
                   10713:             }
1.1075.2.47  raeburn  10714:             if ($cleaned_file =~ m{/}) {
                   10715:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10716:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10717:                 my $item = $fname;
                   10718:                 if ($path ne '') {
                   10719:                     $item = $path.'/'.$fname;
                   10720:                     $subdependencies{$path}{$fname} = 1;
                   10721:                 } else {
                   10722:                     $dependencies{$item} = 1;
                   10723:                 }
                   10724:                 if ($absolutepath) {
                   10725:                     $mapping{$item} = $absolutepath;
                   10726:                 } else {
                   10727:                     $mapping{$item} = $embed_file;
                   10728:                 }
                   10729:             } else {
                   10730:                 $dependencies{$embed_file} = 1;
                   10731:                 if ($absolutepath) {
1.1075.2.47  raeburn  10732:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10733:                 } else {
1.1075.2.47  raeburn  10734:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10735:                 }
                   10736:             }
1.984     raeburn  10737:         }
                   10738:     }
1.1071    raeburn  10739:     my $dirptr = 16384;
1.984     raeburn  10740:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10741:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  10742:         if (($actionurl eq '/adm/portfolio') ||
                   10743:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  10744:             my ($sublistref,$listerror) =
                   10745:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10746:             if (ref($sublistref) eq 'ARRAY') {
                   10747:                 foreach my $line (@{$sublistref}) {
                   10748:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10749:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10750:                 }
1.984     raeburn  10751:             }
1.987     raeburn  10752:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10753:             if (opendir(my $dir,$url.'/'.$path)) {
                   10754:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10755:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10756:             }
1.1075.2.11  raeburn  10757:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10758:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10759:                   ($args->{'context'} eq 'paste')) ||
                   10760:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10761:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  10762:                 my $dir;
                   10763:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10764:                     $dir = $fileloc;
                   10765:                 } else {
                   10766:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10767:                 }
1.1071    raeburn  10768:                 if ($dir ne '') {
                   10769:                     my ($sublistref,$listerror) =
                   10770:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10771:                     if (ref($sublistref) eq 'ARRAY') {
                   10772:                         foreach my $line (@{$sublistref}) {
                   10773:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10774:                                 undef,$mtime)=split(/\&/,$line,12);
                   10775:                             unless (($testdir&$dirptr) ||
                   10776:                                     ($file_name =~ /^\.\.?$/)) {
                   10777:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10778:                             }
                   10779:                         }
                   10780:                     }
                   10781:                 }
1.984     raeburn  10782:             }
                   10783:         }
                   10784:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10785:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10786:                 my $item = $path.'/'.$file;
                   10787:                 unless ($mapping{$item} eq $item) {
                   10788:                     $pathchanges{$item} = 1;
                   10789:                 }
                   10790:                 $existing{$item} = 1;
                   10791:                 $numexisting ++;
                   10792:             } else {
                   10793:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10794:             }
                   10795:         }
1.1071    raeburn  10796:         if ($actionurl eq '/adm/dependencies') {
                   10797:             foreach my $path (keys(%currsubfile)) {
                   10798:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10799:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10800:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  10801:                              next if (($rem ne '') &&
                   10802:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10803:                                        (ref($navmap) &&
                   10804:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10805:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10806:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10807:                              $unused{$path.'/'.$file} = 1; 
                   10808:                          }
                   10809:                     }
                   10810:                 }
                   10811:             }
                   10812:         }
1.984     raeburn  10813:     }
1.987     raeburn  10814:     my %currfile;
1.1075.2.35  raeburn  10815:     if (($actionurl eq '/adm/portfolio') ||
                   10816:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10817:         my ($dirlistref,$listerror) =
                   10818:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10819:         if (ref($dirlistref) eq 'ARRAY') {
                   10820:             foreach my $line (@{$dirlistref}) {
                   10821:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10822:                 $currfile{$file_name} = 1;
                   10823:             }
1.984     raeburn  10824:         }
1.987     raeburn  10825:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10826:         if (opendir(my $dir,$url)) {
1.987     raeburn  10827:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10828:             map {$currfile{$_} = 1;} @dir_list;
                   10829:         }
1.1075.2.11  raeburn  10830:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10831:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10832:               ($args->{'context'} eq 'paste')) ||
                   10833:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10834:         if ($env{'request.course.id'} ne '') {
                   10835:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10836:             if ($dir ne '') {
                   10837:                 my ($dirlistref,$listerror) =
                   10838:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10839:                 if (ref($dirlistref) eq 'ARRAY') {
                   10840:                     foreach my $line (@{$dirlistref}) {
                   10841:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10842:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10843:                         unless (($testdir&$dirptr) ||
                   10844:                                 ($file_name =~ /^\.\.?$/)) {
                   10845:                             $currfile{$file_name} = [$size,$mtime];
                   10846:                         }
                   10847:                     }
                   10848:                 }
                   10849:             }
                   10850:         }
1.984     raeburn  10851:     }
                   10852:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10853:         if (exists($currfile{$file})) {
1.987     raeburn  10854:             unless ($mapping{$file} eq $file) {
                   10855:                 $pathchanges{$file} = 1;
                   10856:             }
                   10857:             $existing{$file} = 1;
                   10858:             $numexisting ++;
                   10859:         } else {
1.984     raeburn  10860:             $newfiles{$file} = 1;
                   10861:         }
                   10862:     }
1.1071    raeburn  10863:     foreach my $file (keys(%currfile)) {
                   10864:         unless (($file eq $filename) ||
                   10865:                 ($file eq $filename.'.bak') ||
                   10866:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  10867:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  10868:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10869:                     next if (($rem ne '') &&
                   10870:                              (($env{"httpref.$rem".$file} ne '') ||
                   10871:                               (ref($navmap) &&
                   10872:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10873:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10874:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10875:                 }
1.1075.2.11  raeburn  10876:             }
1.1071    raeburn  10877:             $unused{$file} = 1;
                   10878:         }
                   10879:     }
1.1075.2.11  raeburn  10880:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10881:         ($args->{'context'} eq 'paste')) {
                   10882:         $counter = scalar(keys(%existing));
                   10883:         $numpathchg = scalar(keys(%pathchanges));
                   10884:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  10885:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   10886:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10887:         $counter = scalar(keys(%existing));
                   10888:         $numpathchg = scalar(keys(%pathchanges));
                   10889:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  10890:     }
1.984     raeburn  10891:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10892:         if ($actionurl eq '/adm/dependencies') {
                   10893:             next if ($embed_file =~ m{^\w+://});
                   10894:         }
1.660     raeburn  10895:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10896:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10897:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10898:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  10899:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10900:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10901:         }
1.1075.2.35  raeburn  10902:         $upload_output .= '</td>';
1.1071    raeburn  10903:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  10904:             $upload_output.='<td align="right">'.
                   10905:                             '<span class="LC_info LC_fontsize_medium">'.
                   10906:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10907:             $numremref++;
1.660     raeburn  10908:         } elsif ($args->{'error_on_invalid_names'}
                   10909:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  10910:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10911:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10912:             $numinvalid++;
1.660     raeburn  10913:         } else {
1.1075.2.35  raeburn  10914:             $upload_output .= '<td>'.
                   10915:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10916:                                                      $embed_file,\%mapping,
1.1071    raeburn  10917:                                                      $allfiles,$codebase,'upload');
                   10918:             $counter ++;
                   10919:             $numnew ++;
1.987     raeburn  10920:         }
                   10921:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10922:     }
                   10923:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10924:         if ($actionurl eq '/adm/dependencies') {
                   10925:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10926:             $modify_output .= &start_data_table_row().
                   10927:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10928:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10929:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10930:                               '<td>'.$size.'</td>'.
                   10931:                               '<td>'.$mtime.'</td>'.
                   10932:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10933:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10934:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10935:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10936:                               &embedded_file_element('upload_embedded',$counter,
                   10937:                                                      $embed_file,\%mapping,
                   10938:                                                      $allfiles,$codebase,'modify').
                   10939:                               '</div></td>'.
                   10940:                               &end_data_table_row()."\n";
                   10941:             $counter ++;
                   10942:         } else {
                   10943:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10944:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10945:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10946:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10947:                               &Apache::loncommon::end_data_table_row()."\n";
                   10948:         }
                   10949:     }
                   10950:     my $delidx = $counter;
                   10951:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10952:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10953:         $delete_output .= &start_data_table_row().
                   10954:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10955:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10956:                           '<td>'.$size.'</td>'.
                   10957:                           '<td>'.$mtime.'</td>'.
                   10958:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10959:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10960:                           &embedded_file_element('upload_embedded',$delidx,
                   10961:                                                  $oldfile,\%mapping,$allfiles,
                   10962:                                                  $codebase,'delete').'</td>'.
                   10963:                           &end_data_table_row()."\n"; 
                   10964:         $numunused ++;
                   10965:         $delidx ++;
1.987     raeburn  10966:     }
                   10967:     if ($upload_output) {
                   10968:         $upload_output = &start_data_table().
                   10969:                          $upload_output.
                   10970:                          &end_data_table()."\n";
                   10971:     }
1.1071    raeburn  10972:     if ($modify_output) {
                   10973:         $modify_output = &start_data_table().
                   10974:                          &start_data_table_header_row().
                   10975:                          '<th>'.&mt('File').'</th>'.
                   10976:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10977:                          '<th>'.&mt('Modified').'</th>'.
                   10978:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10979:                          &end_data_table_header_row().
                   10980:                          $modify_output.
                   10981:                          &end_data_table()."\n";
                   10982:     }
                   10983:     if ($delete_output) {
                   10984:         $delete_output = &start_data_table().
                   10985:                          &start_data_table_header_row().
                   10986:                          '<th>'.&mt('File').'</th>'.
                   10987:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10988:                          '<th>'.&mt('Modified').'</th>'.
                   10989:                          '<th>'.&mt('Delete?').'</th>'.
                   10990:                          &end_data_table_header_row().
                   10991:                          $delete_output.
                   10992:                          &end_data_table()."\n";
                   10993:     }
1.987     raeburn  10994:     my $applies = 0;
                   10995:     if ($numremref) {
                   10996:         $applies ++;
                   10997:     }
                   10998:     if ($numinvalid) {
                   10999:         $applies ++;
                   11000:     }
                   11001:     if ($numexisting) {
                   11002:         $applies ++;
                   11003:     }
1.1071    raeburn  11004:     if ($counter || $numunused) {
1.987     raeburn  11005:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11006:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11007:                   $state.'<h3>'.$heading.'</h3>'; 
                   11008:         if ($actionurl eq '/adm/dependencies') {
                   11009:             if ($numnew) {
                   11010:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11011:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11012:                            $upload_output.'<br />'."\n";
                   11013:             }
                   11014:             if ($numexisting) {
                   11015:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11016:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11017:                            $modify_output.'<br />'."\n";
                   11018:                            $buttontext = &mt('Save changes');
                   11019:             }
                   11020:             if ($numunused) {
                   11021:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11022:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11023:                            $delete_output.'<br />'."\n";
                   11024:                            $buttontext = &mt('Save changes');
                   11025:             }
                   11026:         } else {
                   11027:             $output .= $upload_output.'<br />'."\n";
                   11028:         }
                   11029:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11030:                    $counter.'" />'."\n";
                   11031:         if ($actionurl eq '/adm/dependencies') { 
                   11032:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11033:                        $numnew.'" />'."\n";
                   11034:         } elsif ($actionurl eq '') {
1.987     raeburn  11035:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11036:         }
                   11037:     } elsif ($applies) {
                   11038:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11039:         if ($applies > 1) {
                   11040:             $output .=  
1.1075.2.35  raeburn  11041:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11042:             if ($numremref) {
                   11043:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11044:             }
                   11045:             if ($numinvalid) {
                   11046:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11047:             }
                   11048:             if ($numexisting) {
                   11049:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11050:             }
                   11051:             $output .= '</ul><br />';
                   11052:         } elsif ($numremref) {
                   11053:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11054:         } elsif ($numinvalid) {
                   11055:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11056:         } elsif ($numexisting) {
                   11057:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11058:         }
                   11059:         $output .= $upload_output.'<br />';
                   11060:     }
                   11061:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11062:     $chgcount = $counter;
1.987     raeburn  11063:     if (keys(%pathchanges) > 0) {
                   11064:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11065:             if ($counter) {
1.987     raeburn  11066:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11067:                                                   $embed_file,\%mapping,
1.1071    raeburn  11068:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11069:             } else {
                   11070:                 $pathchange_output .= 
                   11071:                     &start_data_table_row().
                   11072:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11073:                     $chgcount.'" checked="checked" /></td>'.
                   11074:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11075:                     '<td>'.$embed_file.
                   11076:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11077:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11078:                     '</td>'.&end_data_table_row();
1.660     raeburn  11079:             }
1.987     raeburn  11080:             $numpathchg ++;
                   11081:             $chgcount ++;
1.660     raeburn  11082:         }
                   11083:     }
1.1075.2.35  raeburn  11084:     if (($counter) || ($numunused)) {
1.987     raeburn  11085:         if ($numpathchg) {
                   11086:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11087:                        $numpathchg.'" />'."\n";
                   11088:         }
                   11089:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11090:             ($actionurl eq '/adm/imsimport')) {
                   11091:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11092:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11093:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11094:         } elsif ($actionurl eq '/adm/dependencies') {
                   11095:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11096:         }
1.1075.2.35  raeburn  11097:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11098:     } elsif ($numpathchg) {
                   11099:         my %pathchange = ();
                   11100:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11101:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11102:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  11103:         }
1.987     raeburn  11104:     }
1.1071    raeburn  11105:     return ($output,$counter,$numpathchg);
1.987     raeburn  11106: }
                   11107: 
1.1075.2.47  raeburn  11108: =pod
                   11109: 
                   11110: =item * clean_path($name)
                   11111: 
                   11112: Performs clean-up of directories, subdirectories and filename in an
                   11113: embedded object, referenced in an HTML file which is being uploaded
                   11114: to a course or portfolio, where
                   11115: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11116: checked.
                   11117: 
                   11118: Clean-up is similar to replacements in lonnet::clean_filename()
                   11119: except each / between sub-directory and next level is preserved.
                   11120: 
                   11121: =cut
                   11122: 
                   11123: sub clean_path {
                   11124:     my ($embed_file) = @_;
                   11125:     $embed_file =~s{^/+}{};
                   11126:     my @contents;
                   11127:     if ($embed_file =~ m{/}) {
                   11128:         @contents = split(/\//,$embed_file);
                   11129:     } else {
                   11130:         @contents = ($embed_file);
                   11131:     }
                   11132:     my $lastidx = scalar(@contents)-1;
                   11133:     for (my $i=0; $i<=$lastidx; $i++) {
                   11134:         $contents[$i]=~s{\\}{/}g;
                   11135:         $contents[$i]=~s/\s+/\_/g;
                   11136:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11137:         if ($i == $lastidx) {
                   11138:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11139:         }
                   11140:     }
                   11141:     if ($lastidx > 0) {
                   11142:         return join('/',@contents);
                   11143:     } else {
                   11144:         return $contents[0];
                   11145:     }
                   11146: }
                   11147: 
1.987     raeburn  11148: sub embedded_file_element {
1.1071    raeburn  11149:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11150:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11151:                    (ref($codebase) eq 'HASH'));
                   11152:     my $output;
1.1071    raeburn  11153:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11154:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11155:     }
                   11156:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11157:                &escape($embed_file).'" />';
                   11158:     unless (($context eq 'upload_embedded') && 
                   11159:             ($mapping->{$embed_file} eq $embed_file)) {
                   11160:         $output .='
                   11161:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11162:     }
                   11163:     my $attrib;
                   11164:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11165:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11166:     }
                   11167:     $output .=
                   11168:         "\n\t\t".
                   11169:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11170:         $attrib.'" />';
                   11171:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11172:         $output .=
                   11173:             "\n\t\t".
                   11174:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11175:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11176:     }
1.987     raeburn  11177:     return $output;
1.660     raeburn  11178: }
                   11179: 
1.1071    raeburn  11180: sub get_dependency_details {
                   11181:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11182:     my ($size,$mtime,$showsize,$showmtime);
                   11183:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11184:         if ($embed_file =~ m{/}) {
                   11185:             my ($path,$fname) = split(/\//,$embed_file);
                   11186:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11187:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11188:             }
                   11189:         } else {
                   11190:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11191:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11192:             }
                   11193:         }
                   11194:         $showsize = $size/1024.0;
                   11195:         $showsize = sprintf("%.1f",$showsize);
                   11196:         if ($mtime > 0) {
                   11197:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11198:         }
                   11199:     }
                   11200:     return ($showsize,$showmtime);
                   11201: }
                   11202: 
                   11203: sub ask_embedded_js {
                   11204:     return <<"END";
                   11205: <script type="text/javascript"">
                   11206: // <![CDATA[
                   11207: function toggleBrowse(counter) {
                   11208:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11209:     var fileid = document.getElementById('embedded_item_'+counter);
                   11210:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11211:     if (chkboxid.checked == true) {
                   11212:         uploaddivid.style.display='block';
                   11213:     } else {
                   11214:         uploaddivid.style.display='none';
                   11215:         fileid.value = '';
                   11216:     }
                   11217: }
                   11218: // ]]>
                   11219: </script>
                   11220: 
                   11221: END
                   11222: }
                   11223: 
1.661     raeburn  11224: sub upload_embedded {
                   11225:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11226:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11227:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11228:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11229:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11230:         my $orig_uploaded_filename =
                   11231:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11232:         foreach my $type ('orig','ref','attrib','codebase') {
                   11233:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11234:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11235:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11236:             }
                   11237:         }
1.661     raeburn  11238:         my ($path,$fname) =
                   11239:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11240:         # no path, whole string is fname
                   11241:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11242:         $fname = &Apache::lonnet::clean_filename($fname);
                   11243:         # See if there is anything left
                   11244:         next if ($fname eq '');
                   11245: 
                   11246:         # Check if file already exists as a file or directory.
                   11247:         my ($state,$msg);
                   11248:         if ($context eq 'portfolio') {
                   11249:             my $port_path = $dirpath;
                   11250:             if ($group ne '') {
                   11251:                 $port_path = "groups/$group/$port_path";
                   11252:             }
1.987     raeburn  11253:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11254:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11255:                                               $dir_root,$port_path,$disk_quota,
                   11256:                                               $current_disk_usage,$uname,$udom);
                   11257:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11258:                 || $state eq 'file_locked') {
1.661     raeburn  11259:                 $output .= $msg;
                   11260:                 next;
                   11261:             }
                   11262:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11263:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11264:             if ($state eq 'exists') {
                   11265:                 $output .= $msg;
                   11266:                 next;
                   11267:             }
                   11268:         }
                   11269:         # Check if extension is valid
                   11270:         if (($fname =~ /\.(\w+)$/) &&
                   11271:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  11272:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11273:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11274:             next;
                   11275:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11276:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11277:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11278:             next;
                   11279:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  11280:             $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  11281:             next;
                   11282:         }
                   11283:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  11284:         my $subdir = $path;
                   11285:         $subdir =~ s{/+$}{};
1.661     raeburn  11286:         if ($context eq 'portfolio') {
1.984     raeburn  11287:             my $result;
                   11288:             if ($state eq 'existingfile') {
                   11289:                 $result=
                   11290:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  11291:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11292:             } else {
1.984     raeburn  11293:                 $result=
                   11294:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11295:                                                     $dirpath.
1.1075.2.35  raeburn  11296:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11297:                 if ($result !~ m|^/uploaded/|) {
                   11298:                     $output .= '<span class="LC_error">'
                   11299:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11300:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11301:                                .'</span><br />';
                   11302:                     next;
                   11303:                 } else {
1.987     raeburn  11304:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11305:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11306:                 }
1.661     raeburn  11307:             }
1.1075.2.35  raeburn  11308:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   11309:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11310:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11311:             my $result =
1.1075.2.35  raeburn  11312:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11313:             if ($result !~ m|^/uploaded/|) {
                   11314:                 $output .= '<span class="LC_error">'
                   11315:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11316:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11317:                            .'</span><br />';
                   11318:                     next;
                   11319:             } else {
                   11320:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11321:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  11322:                 if ($context eq 'syllabus') {
                   11323:                     &Apache::lonnet::make_public_indefinitely($result);
                   11324:                 }
1.987     raeburn  11325:             }
1.661     raeburn  11326:         } else {
                   11327: # Save the file
                   11328:             my $target = $env{'form.embedded_item_'.$i};
                   11329:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11330:             my $dest = $fullpath.$fname;
                   11331:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11332:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11333:             my $count;
                   11334:             my $filepath = $dir_root;
1.1027    raeburn  11335:             foreach my $subdir (@parts) {
                   11336:                 $filepath .= "/$subdir";
                   11337:                 if (!-e $filepath) {
1.661     raeburn  11338:                     mkdir($filepath,0770);
                   11339:                 }
                   11340:             }
                   11341:             my $fh;
                   11342:             if (!open($fh,'>'.$dest)) {
                   11343:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11344:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11345:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11346:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11347:                            '</span><br />';
                   11348:             } else {
                   11349:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11350:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11351:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11352:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11353:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11354:                               '</span><br />';
                   11355:                 } else {
1.987     raeburn  11356:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11357:                                $url.'</span>').'<br />';
                   11358:                     unless ($context eq 'testbank') {
                   11359:                         $footer .= &mt('View embedded file: [_1]',
                   11360:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11361:                     }
                   11362:                 }
                   11363:                 close($fh);
                   11364:             }
                   11365:         }
                   11366:         if ($env{'form.embedded_ref_'.$i}) {
                   11367:             $pathchange{$i} = 1;
                   11368:         }
                   11369:     }
                   11370:     if ($output) {
                   11371:         $output = '<p>'.$output.'</p>';
                   11372:     }
                   11373:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11374:     $returnflag = 'ok';
1.1071    raeburn  11375:     my $numpathchgs = scalar(keys(%pathchange));
                   11376:     if ($numpathchgs > 0) {
1.987     raeburn  11377:         if ($context eq 'portfolio') {
                   11378:             $output .= '<p>'.&mt('or').'</p>';
                   11379:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11380:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11381:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11382:             $returnflag = 'modify_orightml';
                   11383:         }
                   11384:     }
1.1071    raeburn  11385:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11386: }
                   11387: 
                   11388: sub modify_html_form {
                   11389:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11390:     my $end = 0;
                   11391:     my $modifyform;
                   11392:     if ($context eq 'upload_embedded') {
                   11393:         return unless (ref($pathchange) eq 'HASH');
                   11394:         if ($env{'form.number_embedded_items'}) {
                   11395:             $end += $env{'form.number_embedded_items'};
                   11396:         }
                   11397:         if ($env{'form.number_pathchange_items'}) {
                   11398:             $end += $env{'form.number_pathchange_items'};
                   11399:         }
                   11400:         if ($end) {
                   11401:             for (my $i=0; $i<$end; $i++) {
                   11402:                 if ($i < $env{'form.number_embedded_items'}) {
                   11403:                     next unless($pathchange->{$i});
                   11404:                 }
                   11405:                 $modifyform .=
                   11406:                     &start_data_table_row().
                   11407:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11408:                     'checked="checked" /></td>'.
                   11409:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11410:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11411:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11412:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11413:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11414:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11415:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11416:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11417:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11418:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11419:                     &end_data_table_row();
1.1071    raeburn  11420:             }
1.987     raeburn  11421:         }
                   11422:     } else {
                   11423:         $modifyform = $pathchgtable;
                   11424:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11425:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11426:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11427:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11428:         }
                   11429:     }
                   11430:     if ($modifyform) {
1.1071    raeburn  11431:         if ($actionurl eq '/adm/dependencies') {
                   11432:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11433:         }
1.987     raeburn  11434:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11435:                '<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".
                   11436:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11437:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11438:                '</ol></p>'."\n".'<p>'.
                   11439:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11440:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11441:                &start_data_table()."\n".
                   11442:                &start_data_table_header_row().
                   11443:                '<th>'.&mt('Change?').'</th>'.
                   11444:                '<th>'.&mt('Current reference').'</th>'.
                   11445:                '<th>'.&mt('Required reference').'</th>'.
                   11446:                &end_data_table_header_row()."\n".
                   11447:                $modifyform.
                   11448:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11449:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11450:                '</form>'."\n";
                   11451:     }
                   11452:     return;
                   11453: }
                   11454: 
                   11455: sub modify_html_refs {
1.1075.2.35  raeburn  11456:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11457:     my $container;
                   11458:     if ($context eq 'portfolio') {
                   11459:         $container = $env{'form.container'};
                   11460:     } elsif ($context eq 'coursedoc') {
                   11461:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11462:     } elsif ($context eq 'manage_dependencies') {
                   11463:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11464:         $container = "/$container";
1.1075.2.35  raeburn  11465:     } elsif ($context eq 'syllabus') {
                   11466:         $container = $url;
1.987     raeburn  11467:     } else {
1.1027    raeburn  11468:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11469:     }
                   11470:     my (%allfiles,%codebase,$output,$content);
                   11471:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  11472:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  11473:         if (wantarray) {
                   11474:             return ('',0,0); 
                   11475:         } else {
                   11476:             return;
                   11477:         }
                   11478:     }
                   11479:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11480:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11481:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11482:             if (wantarray) {
                   11483:                 return ('',0,0);
                   11484:             } else {
                   11485:                 return;
                   11486:             }
                   11487:         } 
1.987     raeburn  11488:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11489:         if ($content eq '-1') {
                   11490:             if (wantarray) {
                   11491:                 return ('',0,0);
                   11492:             } else {
                   11493:                 return;
                   11494:             }
                   11495:         }
1.987     raeburn  11496:     } else {
1.1071    raeburn  11497:         unless ($container =~ /^\Q$dir_root\E/) {
                   11498:             if (wantarray) {
                   11499:                 return ('',0,0);
                   11500:             } else {
                   11501:                 return;
                   11502:             }
                   11503:         } 
1.987     raeburn  11504:         if (open(my $fh,"<$container")) {
                   11505:             $content = join('', <$fh>);
                   11506:             close($fh);
                   11507:         } else {
1.1071    raeburn  11508:             if (wantarray) {
                   11509:                 return ('',0,0);
                   11510:             } else {
                   11511:                 return;
                   11512:             }
1.987     raeburn  11513:         }
                   11514:     }
                   11515:     my ($count,$codebasecount) = (0,0);
                   11516:     my $mm = new File::MMagic;
                   11517:     my $mime_type = $mm->checktype_contents($content);
                   11518:     if ($mime_type eq 'text/html') {
                   11519:         my $parse_result = 
                   11520:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11521:                                                     \%codebase,\$content);
                   11522:         if ($parse_result eq 'ok') {
                   11523:             foreach my $i (@changes) {
                   11524:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11525:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11526:                 if ($allfiles{$ref}) {
                   11527:                     my $newname =  $orig;
                   11528:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11529:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11530:                     if ($attrib_regexp =~ /:/) {
                   11531:                         $attrib_regexp =~ s/\:/|/g;
                   11532:                     }
                   11533:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11534:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11535:                         $count += $numchg;
1.1075.2.35  raeburn  11536:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  11537:                         delete($allfiles{$ref});
1.987     raeburn  11538:                     }
                   11539:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11540:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11541:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11542:                         $codebasecount ++;
                   11543:                     }
                   11544:                 }
                   11545:             }
1.1075.2.35  raeburn  11546:             my $skiprewrites;
1.987     raeburn  11547:             if ($count || $codebasecount) {
                   11548:                 my $saveresult;
1.1071    raeburn  11549:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11550:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11551:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11552:                     if ($url eq $container) {
                   11553:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11554:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11555:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11556:                                             $fname.'</span>').'</p>';
1.987     raeburn  11557:                     } else {
                   11558:                          $output = '<p class="LC_error">'.
                   11559:                                    &mt('Error: update failed for: [_1].',
                   11560:                                    '<span class="LC_filename">'.
                   11561:                                    $container.'</span>').'</p>';
                   11562:                     }
1.1075.2.35  raeburn  11563:                     if ($context eq 'syllabus') {
                   11564:                         unless ($saveresult eq 'ok') {
                   11565:                             $skiprewrites = 1;
                   11566:                         }
                   11567:                     }
1.987     raeburn  11568:                 } else {
                   11569:                     if (open(my $fh,">$container")) {
                   11570:                         print $fh $content;
                   11571:                         close($fh);
                   11572:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11573:                                   $count,'<span class="LC_filename">'.
                   11574:                                   $container.'</span>').'</p>';
1.661     raeburn  11575:                     } else {
1.987     raeburn  11576:                          $output = '<p class="LC_error">'.
                   11577:                                    &mt('Error: could not update [_1].',
                   11578:                                    '<span class="LC_filename">'.
                   11579:                                    $container.'</span>').'</p>';
1.661     raeburn  11580:                     }
                   11581:                 }
                   11582:             }
1.1075.2.35  raeburn  11583:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11584:                 my ($actionurl,$state);
                   11585:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11586:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11587:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11588:                                               \%codebase,
                   11589:                                               {'context' => 'rewrites',
                   11590:                                                'ignore_remote_references' => 1,});
                   11591:                 if (ref($mapping) eq 'HASH') {
                   11592:                     my $rewrites = 0;
                   11593:                     foreach my $key (keys(%{$mapping})) {
                   11594:                         next if ($key =~ m{^https?://});
                   11595:                         my $ref = $mapping->{$key};
                   11596:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11597:                         my $attrib;
                   11598:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11599:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11600:                         }
                   11601:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11602:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11603:                             $rewrites += $numchg;
                   11604:                         }
                   11605:                     }
                   11606:                     if ($rewrites) {
                   11607:                         my $saveresult;
                   11608:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11609:                         if ($url eq $container) {
                   11610:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11611:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11612:                                             $count,'<span class="LC_filename">'.
                   11613:                                             $fname.'</span>').'</p>';
                   11614:                         } else {
                   11615:                             $output .= '<p class="LC_error">'.
                   11616:                                        &mt('Error: could not update links in [_1].',
                   11617:                                        '<span class="LC_filename">'.
                   11618:                                        $container.'</span>').'</p>';
                   11619: 
                   11620:                         }
                   11621:                     }
                   11622:                 }
                   11623:             }
1.987     raeburn  11624:         } else {
                   11625:             &logthis('Failed to parse '.$container.
                   11626:                      ' to modify references: '.$parse_result);
1.661     raeburn  11627:         }
                   11628:     }
1.1071    raeburn  11629:     if (wantarray) {
                   11630:         return ($output,$count,$codebasecount);
                   11631:     } else {
                   11632:         return $output;
                   11633:     }
1.661     raeburn  11634: }
                   11635: 
                   11636: sub check_for_existing {
                   11637:     my ($path,$fname,$element) = @_;
                   11638:     my ($state,$msg);
                   11639:     if (-d $path.'/'.$fname) {
                   11640:         $state = 'exists';
                   11641:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11642:     } elsif (-e $path.'/'.$fname) {
                   11643:         $state = 'exists';
                   11644:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11645:     }
                   11646:     if ($state eq 'exists') {
                   11647:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11648:     }
                   11649:     return ($state,$msg);
                   11650: }
                   11651: 
                   11652: sub check_for_upload {
                   11653:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11654:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11655:     my $filesize = length($env{'form.'.$element});
                   11656:     if (!$filesize) {
                   11657:         my $msg = '<span class="LC_error">'.
                   11658:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11659:                       '<span class="LC_filename">'.$fname.'</span>',
                   11660:                       $filesize).'<br />'.
1.1007    raeburn  11661:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11662:                   '</span>';
                   11663:         return ('zero_bytes',$msg);
                   11664:     }
                   11665:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11666:     my $getpropath = 1;
1.1021    raeburn  11667:     my ($dirlistref,$listerror) =
                   11668:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11669:     my $found_file = 0;
                   11670:     my $locked_file = 0;
1.991     raeburn  11671:     my @lockers;
                   11672:     my $navmap;
                   11673:     if ($env{'request.course.id'}) {
                   11674:         $navmap = Apache::lonnavmaps::navmap->new();
                   11675:     }
1.1021    raeburn  11676:     if (ref($dirlistref) eq 'ARRAY') {
                   11677:         foreach my $line (@{$dirlistref}) {
                   11678:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11679:             if ($file_name eq $fname){
                   11680:                 $file_name = $path.$file_name;
                   11681:                 if ($group ne '') {
                   11682:                     $file_name = $group.$file_name;
                   11683:                 }
                   11684:                 $found_file = 1;
                   11685:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11686:                     foreach my $lock (@lockers) {
                   11687:                         if (ref($lock) eq 'ARRAY') {
                   11688:                             my ($symb,$crsid) = @{$lock};
                   11689:                             if ($crsid eq $env{'request.course.id'}) {
                   11690:                                 if (ref($navmap)) {
                   11691:                                     my $res = $navmap->getBySymb($symb);
                   11692:                                     foreach my $part (@{$res->parts()}) { 
                   11693:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11694:                                         unless (($slot_status == $res->RESERVED) ||
                   11695:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11696:                                             $locked_file = 1;
                   11697:                                         }
1.991     raeburn  11698:                                     }
1.1021    raeburn  11699:                                 } else {
                   11700:                                     $locked_file = 1;
1.991     raeburn  11701:                                 }
                   11702:                             } else {
                   11703:                                 $locked_file = 1;
                   11704:                             }
                   11705:                         }
1.1021    raeburn  11706:                    }
                   11707:                 } else {
                   11708:                     my @info = split(/\&/,$rest);
                   11709:                     my $currsize = $info[6]/1000;
                   11710:                     if ($currsize < $filesize) {
                   11711:                         my $extra = $filesize - $currsize;
                   11712:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  11713:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11714:                                       &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded if existing (smaller) file with same name (size = [_3] kilobytes) is replaced.',
1.1075.2.69  raeburn  11715:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11716:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11717:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11718:                             return ('will_exceed_quota',$msg);
                   11719:                         }
1.984     raeburn  11720:                     }
                   11721:                 }
1.661     raeburn  11722:             }
                   11723:         }
                   11724:     }
                   11725:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  11726:         my $msg = '<p class="LC_warning">'.
                   11727:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   11728:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11729:         return ('will_exceed_quota',$msg);
                   11730:     } elsif ($found_file) {
                   11731:         if ($locked_file) {
1.1075.2.69  raeburn  11732:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11733:             $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
1.1075.2.69  raeburn  11734:             $msg .= '</p>';
1.661     raeburn  11735:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11736:             return ('file_locked',$msg);
                   11737:         } else {
1.1075.2.69  raeburn  11738:             my $msg = '<p class="LC_error">';
1.984     raeburn  11739:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1075.2.69  raeburn  11740:             $msg .= '</p>';
1.984     raeburn  11741:             return ('existingfile',$msg);
1.661     raeburn  11742:         }
                   11743:     }
                   11744: }
                   11745: 
1.987     raeburn  11746: sub check_for_traversal {
                   11747:     my ($path,$url,$toplevel) = @_;
                   11748:     my @parts=split(/\//,$path);
                   11749:     my $cleanpath;
                   11750:     my $fullpath = $url;
                   11751:     for (my $i=0;$i<@parts;$i++) {
                   11752:         next if ($parts[$i] eq '.');
                   11753:         if ($parts[$i] eq '..') {
                   11754:             $fullpath =~ s{([^/]+/)$}{};
                   11755:         } else {
                   11756:             $fullpath .= $parts[$i].'/';
                   11757:         }
                   11758:     }
                   11759:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11760:         $cleanpath = $1;
                   11761:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11762:         my $curr_toprel = $1;
                   11763:         my @parts = split(/\//,$curr_toprel);
                   11764:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11765:         my @urlparts = split(/\//,$url_toprel);
                   11766:         my $doubledots;
                   11767:         my $startdiff = -1;
                   11768:         for (my $i=0; $i<@urlparts; $i++) {
                   11769:             if ($startdiff == -1) {
                   11770:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11771:                     $startdiff = $i;
                   11772:                     $doubledots .= '../';
                   11773:                 }
                   11774:             } else {
                   11775:                 $doubledots .= '../';
                   11776:             }
                   11777:         }
                   11778:         if ($startdiff > -1) {
                   11779:             $cleanpath = $doubledots;
                   11780:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11781:                 $cleanpath .= $parts[$i].'/';
                   11782:             }
                   11783:         }
                   11784:     }
                   11785:     $cleanpath =~ s{(/)$}{};
                   11786:     return $cleanpath;
                   11787: }
1.31      albertel 11788: 
1.1053    raeburn  11789: sub is_archive_file {
                   11790:     my ($mimetype) = @_;
                   11791:     if (($mimetype eq 'application/octet-stream') ||
                   11792:         ($mimetype eq 'application/x-stuffit') ||
                   11793:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11794:         return 1;
                   11795:     }
                   11796:     return;
                   11797: }
                   11798: 
                   11799: sub decompress_form {
1.1065    raeburn  11800:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11801:     my %lt = &Apache::lonlocal::texthash (
                   11802:         this => 'This file is an archive file.',
1.1067    raeburn  11803:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11804:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11805:         youm => 'You may wish to extract its contents.',
                   11806:         extr => 'Extract contents',
1.1067    raeburn  11807:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11808:         proa => 'Process automatically?',
1.1053    raeburn  11809:         yes  => 'Yes',
                   11810:         no   => 'No',
1.1067    raeburn  11811:         fold => 'Title for folder containing movie',
                   11812:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11813:     );
1.1065    raeburn  11814:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11815:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11816:     my $info = &list_archive_contents($fileloc,\@paths);
                   11817:     if (@paths) {
                   11818:         foreach my $path (@paths) {
                   11819:             $path =~ s{^/}{};
1.1067    raeburn  11820:             if ($path =~ m{^([^/]+)/$}) {
                   11821:                 $topdir = $1;
                   11822:             }
1.1065    raeburn  11823:             if ($path =~ m{^([^/]+)/}) {
                   11824:                 $toplevel{$1} = $path;
                   11825:             } else {
                   11826:                 $toplevel{$path} = $path;
                   11827:             }
                   11828:         }
                   11829:     }
1.1067    raeburn  11830:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  11831:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11832:                         "$topdir/media/",
                   11833:                         "$topdir/media/$topdir.mp4",
                   11834:                         "$topdir/media/FirstFrame.png",
                   11835:                         "$topdir/media/player.swf",
                   11836:                         "$topdir/media/swfobject.js",
                   11837:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  11838:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  11839:                          "$topdir/$topdir.mp4",
                   11840:                          "$topdir/$topdir\_config.xml",
                   11841:                          "$topdir/$topdir\_controller.swf",
                   11842:                          "$topdir/$topdir\_embed.css",
                   11843:                          "$topdir/$topdir\_First_Frame.png",
                   11844:                          "$topdir/$topdir\_player.html",
                   11845:                          "$topdir/$topdir\_Thumbnails.png",
                   11846:                          "$topdir/playerProductInstall.swf",
                   11847:                          "$topdir/scripts/",
                   11848:                          "$topdir/scripts/config_xml.js",
                   11849:                          "$topdir/scripts/handlebars.js",
                   11850:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11851:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11852:                          "$topdir/scripts/modernizr.js",
                   11853:                          "$topdir/scripts/player-min.js",
                   11854:                          "$topdir/scripts/swfobject.js",
                   11855:                          "$topdir/skins/",
                   11856:                          "$topdir/skins/configuration_express.xml",
                   11857:                          "$topdir/skins/express_show/",
                   11858:                          "$topdir/skins/express_show/player-min.css",
                   11859:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  11860:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11861:                          "$topdir/$topdir.mp4",
                   11862:                          "$topdir/$topdir\_config.xml",
                   11863:                          "$topdir/$topdir\_controller.swf",
                   11864:                          "$topdir/$topdir\_embed.css",
                   11865:                          "$topdir/$topdir\_First_Frame.png",
                   11866:                          "$topdir/$topdir\_player.html",
                   11867:                          "$topdir/$topdir\_Thumbnails.png",
                   11868:                          "$topdir/playerProductInstall.swf",
                   11869:                          "$topdir/scripts/",
                   11870:                          "$topdir/scripts/config_xml.js",
                   11871:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11872:                          "$topdir/skins/",
                   11873:                          "$topdir/skins/configuration_express.xml",
                   11874:                          "$topdir/skins/express_show/",
                   11875:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11876:                          "$topdir/skins/express_show/spritesheet.png",
                   11877:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  11878:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11879:         if (@diffs == 0) {
1.1075.2.59  raeburn  11880:             $is_camtasia = 6;
                   11881:         } else {
1.1075.2.81  raeburn  11882:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  11883:             if (@diffs == 0) {
                   11884:                 $is_camtasia = 8;
1.1075.2.81  raeburn  11885:             } else {
                   11886:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11887:                 if (@diffs == 0) {
                   11888:                     $is_camtasia = 8;
                   11889:                 }
1.1075.2.59  raeburn  11890:             }
1.1067    raeburn  11891:         }
                   11892:     }
                   11893:     my $output;
                   11894:     if ($is_camtasia) {
                   11895:         $output = <<"ENDCAM";
                   11896: <script type="text/javascript" language="Javascript">
                   11897: // <![CDATA[
                   11898: 
                   11899: function camtasiaToggle() {
                   11900:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11901:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  11902:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11903:                 document.getElementById('camtasia_titles').style.display='block';
                   11904:             } else {
                   11905:                 document.getElementById('camtasia_titles').style.display='none';
                   11906:             }
                   11907:         }
                   11908:     }
                   11909:     return;
                   11910: }
                   11911: 
                   11912: // ]]>
                   11913: </script>
                   11914: <p>$lt{'camt'}</p>
                   11915: ENDCAM
1.1065    raeburn  11916:     } else {
1.1067    raeburn  11917:         $output = '<p>'.$lt{'this'};
                   11918:         if ($info eq '') {
                   11919:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11920:         } else {
                   11921:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11922:                        '<div><pre>'.$info.'</pre></div>';
                   11923:         }
1.1065    raeburn  11924:     }
1.1067    raeburn  11925:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11926:     my $duplicates;
                   11927:     my $num = 0;
                   11928:     if (ref($dirlist) eq 'ARRAY') {
                   11929:         foreach my $item (@{$dirlist}) {
                   11930:             if (ref($item) eq 'ARRAY') {
                   11931:                 if (exists($toplevel{$item->[0]})) {
                   11932:                     $duplicates .= 
                   11933:                         &start_data_table_row().
                   11934:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11935:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11936:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11937:                         'value="1" />'.&mt('Yes').'</label>'.
                   11938:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11939:                         '<td>'.$item->[0].'</td>';
                   11940:                     if ($item->[2]) {
                   11941:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11942:                     } else {
                   11943:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11944:                     }
                   11945:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11946:                                    '<td>'.
                   11947:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11948:                                    '</td>'.
                   11949:                                    &end_data_table_row();
                   11950:                     $num ++;
                   11951:                 }
                   11952:             }
                   11953:         }
                   11954:     }
                   11955:     my $itemcount;
                   11956:     if (@paths > 0) {
                   11957:         $itemcount = scalar(@paths);
                   11958:     } else {
                   11959:         $itemcount = 1;
                   11960:     }
1.1067    raeburn  11961:     if ($is_camtasia) {
                   11962:         $output .= $lt{'auto'}.'<br />'.
                   11963:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  11964:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11965:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11966:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11967:                    $lt{'no'}.'</label></span><br />'.
                   11968:                    '<div id="camtasia_titles" style="display:block">'.
                   11969:                    &Apache::lonhtmlcommon::start_pick_box().
                   11970:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11971:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11972:                    &Apache::lonhtmlcommon::row_closure().
                   11973:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11974:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11975:                    &Apache::lonhtmlcommon::row_closure(1).
                   11976:                    &Apache::lonhtmlcommon::end_pick_box().
                   11977:                    '</div>';
                   11978:     }
1.1065    raeburn  11979:     $output .= 
                   11980:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11981:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11982:         "\n";
1.1065    raeburn  11983:     if ($duplicates ne '') {
                   11984:         $output .= '<p><span class="LC_warning">'.
                   11985:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11986:                    &start_data_table().
                   11987:                    &start_data_table_header_row().
                   11988:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11989:                    '<th>'.&mt('Name').'</th>'.
                   11990:                    '<th>'.&mt('Type').'</th>'.
                   11991:                    '<th>'.&mt('Size').'</th>'.
                   11992:                    '<th>'.&mt('Last modified').'</th>'.
                   11993:                    &end_data_table_header_row().
                   11994:                    $duplicates.
                   11995:                    &end_data_table().
                   11996:                    '</p>';
                   11997:     }
1.1067    raeburn  11998:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11999:     if (ref($hiddenelements) eq 'HASH') {
                   12000:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12001:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12002:         }
                   12003:     }
                   12004:     $output .= <<"END";
1.1067    raeburn  12005: <br />
1.1053    raeburn  12006: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12007: </form>
                   12008: $noextract
                   12009: END
                   12010:     return $output;
                   12011: }
                   12012: 
1.1065    raeburn  12013: sub decompression_utility {
                   12014:     my ($program) = @_;
                   12015:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12016:     my $location;
                   12017:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12018:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12019:                          '/usr/sbin/') {
                   12020:             if (-x $dir.$program) {
                   12021:                 $location = $dir.$program;
                   12022:                 last;
                   12023:             }
                   12024:         }
                   12025:     }
                   12026:     return $location;
                   12027: }
                   12028: 
                   12029: sub list_archive_contents {
                   12030:     my ($file,$pathsref) = @_;
                   12031:     my (@cmd,$output);
                   12032:     my $needsregexp;
                   12033:     if ($file =~ /\.zip$/) {
                   12034:         @cmd = (&decompression_utility('unzip'),"-l");
                   12035:         $needsregexp = 1;
                   12036:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12037:              ($file =~ /\.tgz$/)) {
                   12038:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12039:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12040:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12041:     } elsif ($file =~ m|\.tar$|) {
                   12042:         @cmd = (&decompression_utility('tar'),"-tf");
                   12043:     }
                   12044:     if (@cmd) {
                   12045:         undef($!);
                   12046:         undef($@);
                   12047:         if (open(my $fh,"-|", @cmd, $file)) {
                   12048:             while (my $line = <$fh>) {
                   12049:                 $output .= $line;
                   12050:                 chomp($line);
                   12051:                 my $item;
                   12052:                 if ($needsregexp) {
                   12053:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12054:                 } else {
                   12055:                     $item = $line;
                   12056:                 }
                   12057:                 if ($item ne '') {
                   12058:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12059:                         push(@{$pathsref},$item);
                   12060:                     } 
                   12061:                 }
                   12062:             }
                   12063:             close($fh);
                   12064:         }
                   12065:     }
                   12066:     return $output;
                   12067: }
                   12068: 
1.1053    raeburn  12069: sub decompress_uploaded_file {
                   12070:     my ($file,$dir) = @_;
                   12071:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12072:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12073:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12074:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12075:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12076:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12077:     my $decompressed = $env{'cgi.decompressed'};
                   12078:     &Apache::lonnet::delenv('cgi.file');
                   12079:     &Apache::lonnet::delenv('cgi.dir');
                   12080:     &Apache::lonnet::delenv('cgi.decompressed');
                   12081:     return ($decompressed,$result);
                   12082: }
                   12083: 
1.1055    raeburn  12084: sub process_decompression {
                   12085:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   12086:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  12087:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  12088:         $error = &mt('Filename not a supported archive file type.').
                   12089:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12090:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12091:     } else {
                   12092:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12093:         if ($docuhome eq 'no_host') {
                   12094:             $error = &mt('Could not determine home server for course.');
                   12095:         } else {
                   12096:             my @ids=&Apache::lonnet::current_machine_ids();
                   12097:             my $currdir = "$dir_root/$destination";
                   12098:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12099:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12100:                        "$dir_root/$destination";
                   12101:             } else {
                   12102:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12103:                        "$dir_root/$docudom/$docuname/$destination";
                   12104:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12105:                     $error = &mt('Archive file not found.');
                   12106:                 }
                   12107:             }
1.1065    raeburn  12108:             my (@to_overwrite,@to_skip);
                   12109:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12110:                 my $total = $env{'form.archive_overwrite_total'};
                   12111:                 for (my $i=0; $i<$total; $i++) {
                   12112:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12113:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12114:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12115:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12116:                     }
                   12117:                 }
                   12118:             }
                   12119:             my $numskip = scalar(@to_skip);
                   12120:             if (($numskip > 0) && 
                   12121:                 ($numskip == $env{'form.archive_itemcount'})) {
                   12122:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12123:             } elsif ($dir eq '') {
1.1055    raeburn  12124:                 $error = &mt('Directory containing archive file unavailable.');
                   12125:             } elsif (!$error) {
1.1065    raeburn  12126:                 my ($decompressed,$display);
                   12127:                 if ($numskip > 0) {
                   12128:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12129:                     mkdir("$dir/$tempdir",0755);
                   12130:                     system("mv $dir/$file $dir/$tempdir/$file");
                   12131:                     ($decompressed,$display) = 
                   12132:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   12133:                     foreach my $item (@to_skip) {
                   12134:                         if (($item ne '') && ($item !~ /\.\./)) {
                   12135:                             if (-f "$dir/$tempdir/$item") { 
                   12136:                                 unlink("$dir/$tempdir/$item");
                   12137:                             } elsif (-d "$dir/$tempdir/$item") {
                   12138:                                 system("rm -rf $dir/$tempdir/$item");
                   12139:                             }
                   12140:                         }
                   12141:                     }
                   12142:                     system("mv $dir/$tempdir/* $dir");
                   12143:                     rmdir("$dir/$tempdir");   
                   12144:                 } else {
                   12145:                     ($decompressed,$display) = 
                   12146:                         &decompress_uploaded_file($file,$dir);
                   12147:                 }
1.1055    raeburn  12148:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12149:                     $output = '<p class="LC_info">'.
                   12150:                               &mt('Files extracted successfully from archive.').
                   12151:                               '</p>'."\n";
1.1055    raeburn  12152:                     my ($warning,$result,@contents);
                   12153:                     my ($newdirlistref,$newlisterror) =
                   12154:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12155:                                                  $docuname,1);
                   12156:                     my (%is_dir,%changes,@newitems);
                   12157:                     my $dirptr = 16384;
1.1065    raeburn  12158:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12159:                         foreach my $dir_line (@{$newdirlistref}) {
                   12160:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  12161:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   12162:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  12163:                                 push(@newitems,$item);
                   12164:                                 if ($dirptr&$testdir) {
                   12165:                                     $is_dir{$item} = 1;
                   12166:                                 }
                   12167:                                 $changes{$item} = 1;
                   12168:                             }
                   12169:                         }
                   12170:                     }
                   12171:                     if (keys(%changes) > 0) {
                   12172:                         foreach my $item (sort(@newitems)) {
                   12173:                             if ($changes{$item}) {
                   12174:                                 push(@contents,$item);
                   12175:                             }
                   12176:                         }
                   12177:                     }
                   12178:                     if (@contents > 0) {
1.1067    raeburn  12179:                         my $wantform;
                   12180:                         unless ($env{'form.autoextract_camtasia'}) {
                   12181:                             $wantform = 1;
                   12182:                         }
1.1056    raeburn  12183:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12184:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12185:                                                                 $currdir,\%is_dir,
                   12186:                                                                 \%children,\%parent,
1.1056    raeburn  12187:                                                                 \@contents,\%dirorder,
                   12188:                                                                 \%titles,$wantform);
1.1055    raeburn  12189:                         if ($datatable ne '') {
                   12190:                             $output .= &archive_options_form('decompressed',$datatable,
                   12191:                                                              $count,$hiddenelem);
1.1065    raeburn  12192:                             my $startcount = 6;
1.1055    raeburn  12193:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12194:                                                            \%titles,\%children);
1.1055    raeburn  12195:                         }
1.1067    raeburn  12196:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  12197:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12198:                             my %displayed;
                   12199:                             my $total = 1;
                   12200:                             $env{'form.archive_directory'} = [];
                   12201:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12202:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12203:                                 $path =~ s{/$}{};
                   12204:                                 my $item;
                   12205:                                 if ($path ne '') {
                   12206:                                     $item = "$path/$titles{$i}";
                   12207:                                 } else {
                   12208:                                     $item = $titles{$i};
                   12209:                                 }
                   12210:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12211:                                 if ($item eq $contents[0]) {
                   12212:                                     push(@{$env{'form.archive_directory'}},$i);
                   12213:                                     $env{'form.archive_'.$i} = 'display';
                   12214:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12215:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  12216:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12217:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  12218:                                     $env{'form.archive_'.$i} = 'display';
                   12219:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12220:                                     $displayed{'web'} = $i;
                   12221:                                 } else {
1.1075.2.59  raeburn  12222:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12223:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12224:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12225:                                         push(@{$env{'form.archive_directory'}},$i);
                   12226:                                     }
                   12227:                                     $env{'form.archive_'.$i} = 'dependency';
                   12228:                                 }
                   12229:                                 $total ++;
                   12230:                             }
                   12231:                             for (my $i=1; $i<$total; $i++) {
                   12232:                                 next if ($i == $displayed{'web'});
                   12233:                                 next if ($i == $displayed{'folder'});
                   12234:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12235:                             }
                   12236:                             $env{'form.phase'} = 'decompress_cleanup';
                   12237:                             $env{'form.archivedelete'} = 1;
                   12238:                             $env{'form.archive_count'} = $total-1;
                   12239:                             $output .=
                   12240:                                 &process_extracted_files('coursedocs',$docudom,
                   12241:                                                          $docuname,$destination,
                   12242:                                                          $dir_root,$hiddenelem);
                   12243:                         }
1.1055    raeburn  12244:                     } else {
                   12245:                         $warning = &mt('No new items extracted from archive file.');
                   12246:                     }
                   12247:                 } else {
                   12248:                     $output = $display;
                   12249:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12250:                 }
                   12251:             }
                   12252:         }
                   12253:     }
                   12254:     if ($error) {
                   12255:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12256:                    $error.'</p>'."\n";
                   12257:     }
                   12258:     if ($warning) {
                   12259:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12260:     }
                   12261:     return $output;
                   12262: }
                   12263: 
                   12264: sub get_extracted {
1.1056    raeburn  12265:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12266:         $titles,$wantform) = @_;
1.1055    raeburn  12267:     my $count = 0;
                   12268:     my $depth = 0;
                   12269:     my $datatable;
1.1056    raeburn  12270:     my @hierarchy;
1.1055    raeburn  12271:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12272:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12273:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12274:     foreach my $item (@{$contents}) {
                   12275:         $count ++;
1.1056    raeburn  12276:         @{$dirorder->{$count}} = @hierarchy;
                   12277:         $titles->{$count} = $item;
1.1055    raeburn  12278:         &archive_hierarchy($depth,$count,$parent,$children);
                   12279:         if ($wantform) {
                   12280:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12281:                                        $currdir,$depth,$count);
                   12282:         }
                   12283:         if ($is_dir->{$item}) {
                   12284:             $depth ++;
1.1056    raeburn  12285:             push(@hierarchy,$count);
                   12286:             $parent->{$depth} = $count;
1.1055    raeburn  12287:             $datatable .=
                   12288:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12289:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12290:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12291:             $depth --;
1.1056    raeburn  12292:             pop(@hierarchy);
1.1055    raeburn  12293:         }
                   12294:     }
                   12295:     return ($count,$datatable);
                   12296: }
                   12297: 
                   12298: sub recurse_extracted_archive {
1.1056    raeburn  12299:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12300:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12301:     my $result='';
1.1056    raeburn  12302:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12303:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12304:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12305:         return $result;
                   12306:     }
                   12307:     my $dirptr = 16384;
                   12308:     my ($newdirlistref,$newlisterror) =
                   12309:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12310:     if (ref($newdirlistref) eq 'ARRAY') {
                   12311:         foreach my $dir_line (@{$newdirlistref}) {
                   12312:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12313:             unless ($item =~ /^\.+$/) {
                   12314:                 $$count ++;
1.1056    raeburn  12315:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12316:                 $titles->{$$count} = $item;
1.1055    raeburn  12317:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12318: 
1.1055    raeburn  12319:                 my $is_dir;
                   12320:                 if ($dirptr&$testdir) {
                   12321:                     $is_dir = 1;
                   12322:                 }
                   12323:                 if ($wantform) {
                   12324:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12325:                 }
                   12326:                 if ($is_dir) {
                   12327:                     $$depth ++;
1.1056    raeburn  12328:                     push(@{$hierarchy},$$count);
                   12329:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12330:                     $result .=
                   12331:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12332:                                                    $docuname,$depth,$count,
1.1056    raeburn  12333:                                                    $hierarchy,$dirorder,$children,
                   12334:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12335:                     $$depth --;
1.1056    raeburn  12336:                     pop(@{$hierarchy});
1.1055    raeburn  12337:                 }
                   12338:             }
                   12339:         }
                   12340:     }
                   12341:     return $result;
                   12342: }
                   12343: 
                   12344: sub archive_hierarchy {
                   12345:     my ($depth,$count,$parent,$children) =@_;
                   12346:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12347:         if (exists($parent->{$depth})) {
                   12348:              $children->{$parent->{$depth}} .= $count.':';
                   12349:         }
                   12350:     }
                   12351:     return;
                   12352: }
                   12353: 
                   12354: sub archive_row {
                   12355:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12356:     my ($name) = ($item =~ m{([^/]+)$});
                   12357:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12358:                                        'display'    => 'Add as file',
1.1055    raeburn  12359:                                        'dependency' => 'Include as dependency',
                   12360:                                        'discard'    => 'Discard',
                   12361:                                       );
                   12362:     if ($is_dir) {
1.1059    raeburn  12363:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12364:     }
1.1056    raeburn  12365:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12366:     my $offset = 0;
1.1055    raeburn  12367:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12368:         $offset ++;
1.1065    raeburn  12369:         if ($action ne 'display') {
                   12370:             $offset ++;
                   12371:         }  
1.1055    raeburn  12372:         $output .= '<td><span class="LC_nobreak">'.
                   12373:                    '<label><input type="radio" name="archive_'.$count.
                   12374:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12375:         my $text = $choices{$action};
                   12376:         if ($is_dir) {
                   12377:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12378:             if ($action eq 'display') {
1.1059    raeburn  12379:                 $text = &mt('Add as folder');
1.1055    raeburn  12380:             }
1.1056    raeburn  12381:         } else {
                   12382:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12383: 
                   12384:         }
                   12385:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12386:         if ($action eq 'dependency') {
                   12387:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12388:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12389:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12390:                        '<option value=""></option>'."\n".
                   12391:                        '</select>'."\n".
                   12392:                        '</div>';
1.1059    raeburn  12393:         } elsif ($action eq 'display') {
                   12394:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12395:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12396:                        '</div>';
1.1055    raeburn  12397:         }
1.1056    raeburn  12398:         $output .= '</td>';
1.1055    raeburn  12399:     }
                   12400:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12401:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12402:     for (my $i=0; $i<$depth; $i++) {
                   12403:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12404:     }
                   12405:     if ($is_dir) {
                   12406:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12407:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12408:     } else {
                   12409:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12410:     }
                   12411:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12412:                &end_data_table_row();
                   12413:     return $output;
                   12414: }
                   12415: 
                   12416: sub archive_options_form {
1.1065    raeburn  12417:     my ($form,$display,$count,$hiddenelem) = @_;
                   12418:     my %lt = &Apache::lonlocal::texthash(
                   12419:                perm => 'Permanently remove archive file?',
                   12420:                hows => 'How should each extracted item be incorporated in the course?',
                   12421:                cont => 'Content actions for all',
                   12422:                addf => 'Add as folder/file',
                   12423:                incd => 'Include as dependency for a displayed file',
                   12424:                disc => 'Discard',
                   12425:                no   => 'No',
                   12426:                yes  => 'Yes',
                   12427:                save => 'Save',
                   12428:     );
                   12429:     my $output = <<"END";
                   12430: <form name="$form" method="post" action="">
                   12431: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12432: <label>
                   12433:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12434: </label>
                   12435: &nbsp;
                   12436: <label>
                   12437:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12438: </span>
                   12439: </p>
                   12440: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12441: <br />$lt{'hows'}
                   12442: <div class="LC_columnSection">
                   12443:   <fieldset>
                   12444:     <legend>$lt{'cont'}</legend>
                   12445:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12446:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12447:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12448:   </fieldset>
                   12449: </div>
                   12450: END
                   12451:     return $output.
1.1055    raeburn  12452:            &start_data_table()."\n".
1.1065    raeburn  12453:            $display."\n".
1.1055    raeburn  12454:            &end_data_table()."\n".
                   12455:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12456:            $hiddenelem.
1.1065    raeburn  12457:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12458:            '</form>';
                   12459: }
                   12460: 
                   12461: sub archive_javascript {
1.1056    raeburn  12462:     my ($startcount,$numitems,$titles,$children) = @_;
                   12463:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12464:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12465:     my $scripttag = <<START;
                   12466: <script type="text/javascript">
                   12467: // <![CDATA[
                   12468: 
                   12469: function checkAll(form,prefix) {
                   12470:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12471:     for (var i=0; i < form.elements.length; i++) {
                   12472:         var id = form.elements[i].id;
                   12473:         if ((id != '') && (id != undefined)) {
                   12474:             if (idstr.test(id)) {
                   12475:                 if (form.elements[i].type == 'radio') {
                   12476:                     form.elements[i].checked = true;
1.1056    raeburn  12477:                     var nostart = i-$startcount;
1.1059    raeburn  12478:                     var offset = nostart%7;
                   12479:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12480:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12481:                 }
                   12482:             }
                   12483:         }
                   12484:     }
                   12485: }
                   12486: 
                   12487: function propagateCheck(form,count) {
                   12488:     if (count > 0) {
1.1059    raeburn  12489:         var startelement = $startcount + ((count-1) * 7);
                   12490:         for (var j=1; j<6; j++) {
                   12491:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12492:                 var item = startelement + j; 
                   12493:                 if (form.elements[item].type == 'radio') {
                   12494:                     if (form.elements[item].checked) {
                   12495:                         containerCheck(form,count,j);
                   12496:                         break;
                   12497:                     }
1.1055    raeburn  12498:                 }
                   12499:             }
                   12500:         }
                   12501:     }
                   12502: }
                   12503: 
                   12504: numitems = $numitems
1.1056    raeburn  12505: var titles = new Array(numitems);
                   12506: var parents = new Array(numitems);
1.1055    raeburn  12507: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12508:     parents[i] = new Array;
1.1055    raeburn  12509: }
1.1059    raeburn  12510: var maintitle = '$maintitle';
1.1055    raeburn  12511: 
                   12512: START
                   12513: 
1.1056    raeburn  12514:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12515:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12516:         for (my $i=0; $i<@contents; $i ++) {
                   12517:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12518:         }
                   12519:     }
                   12520: 
1.1056    raeburn  12521:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12522:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12523:     }
                   12524: 
1.1055    raeburn  12525:     $scripttag .= <<END;
                   12526: 
                   12527: function containerCheck(form,count,offset) {
                   12528:     if (count > 0) {
1.1056    raeburn  12529:         dependencyCheck(form,count,offset);
1.1059    raeburn  12530:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12531:         form.elements[item].checked = true;
                   12532:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12533:             if (parents[count].length > 0) {
                   12534:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12535:                     containerCheck(form,parents[count][j],offset);
                   12536:                 }
                   12537:             }
                   12538:         }
                   12539:     }
                   12540: }
                   12541: 
                   12542: function dependencyCheck(form,count,offset) {
                   12543:     if (count > 0) {
1.1059    raeburn  12544:         var chosen = (offset+$startcount)+7*(count-1);
                   12545:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12546:         var currtype = form.elements[depitem].type;
                   12547:         if (form.elements[chosen].value == 'dependency') {
                   12548:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12549:             form.elements[depitem].options.length = 0;
                   12550:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  12551:             for (var i=1; i<=numitems; i++) {
                   12552:                 if (i == count) {
                   12553:                     continue;
                   12554:                 }
1.1059    raeburn  12555:                 var startelement = $startcount + (i-1) * 7;
                   12556:                 for (var j=1; j<6; j++) {
                   12557:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12558:                         var item = startelement + j;
                   12559:                         if (form.elements[item].type == 'radio') {
                   12560:                             if (form.elements[item].checked) {
                   12561:                                 if (form.elements[item].value == 'display') {
                   12562:                                     var n = form.elements[depitem].options.length;
                   12563:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12564:                                 }
                   12565:                             }
                   12566:                         }
                   12567:                     }
                   12568:                 }
                   12569:             }
                   12570:         } else {
                   12571:             document.getElementById('arc_depon_'+count).style.display='none';
                   12572:             form.elements[depitem].options.length = 0;
                   12573:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12574:         }
1.1059    raeburn  12575:         titleCheck(form,count,offset);
1.1056    raeburn  12576:     }
                   12577: }
                   12578: 
                   12579: function propagateSelect(form,count,offset) {
                   12580:     if (count > 0) {
1.1065    raeburn  12581:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12582:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12583:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12584:             if (parents[count].length > 0) {
                   12585:                 for (var j=0; j<parents[count].length; j++) {
                   12586:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12587:                 }
                   12588:             }
                   12589:         }
                   12590:     }
                   12591: }
1.1056    raeburn  12592: 
                   12593: function containerSelect(form,count,offset,picked) {
                   12594:     if (count > 0) {
1.1065    raeburn  12595:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12596:         if (form.elements[item].type == 'radio') {
                   12597:             if (form.elements[item].value == 'dependency') {
                   12598:                 if (form.elements[item+1].type == 'select-one') {
                   12599:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12600:                         if (form.elements[item+1].options[i].value == picked) {
                   12601:                             form.elements[item+1].selectedIndex = i;
                   12602:                             break;
                   12603:                         }
                   12604:                     }
                   12605:                 }
                   12606:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12607:                     if (parents[count].length > 0) {
                   12608:                         for (var j=0; j<parents[count].length; j++) {
                   12609:                             containerSelect(form,parents[count][j],offset,picked);
                   12610:                         }
                   12611:                     }
                   12612:                 }
                   12613:             }
                   12614:         }
                   12615:     }
                   12616: }
                   12617: 
1.1059    raeburn  12618: function titleCheck(form,count,offset) {
                   12619:     if (count > 0) {
                   12620:         var chosen = (offset+$startcount)+7*(count-1);
                   12621:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12622:         var currtype = form.elements[depitem].type;
                   12623:         if (form.elements[chosen].value == 'display') {
                   12624:             document.getElementById('arc_title_'+count).style.display='block';
                   12625:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12626:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12627:             }
                   12628:         } else {
                   12629:             document.getElementById('arc_title_'+count).style.display='none';
                   12630:             if (currtype == 'text') { 
                   12631:                 document.getElementById('archive_title_'+count).value='';
                   12632:             }
                   12633:         }
                   12634:     }
                   12635:     return;
                   12636: }
                   12637: 
1.1055    raeburn  12638: // ]]>
                   12639: </script>
                   12640: END
                   12641:     return $scripttag;
                   12642: }
                   12643: 
                   12644: sub process_extracted_files {
1.1067    raeburn  12645:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12646:     my $numitems = $env{'form.archive_count'};
                   12647:     return unless ($numitems);
                   12648:     my @ids=&Apache::lonnet::current_machine_ids();
                   12649:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12650:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12651:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12652:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12653:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12654:         $pathtocheck = "$dir_root/$destination";
                   12655:         $dir = $dir_root;
                   12656:         $ishome = 1;
                   12657:     } else {
                   12658:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12659:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   12660:         $dir = "$dir_root/$docudom/$docuname";    
                   12661:     }
                   12662:     my $currdir = "$dir_root/$destination";
                   12663:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12664:     if ($env{'form.folderpath'}) {
                   12665:         my @items = split('&',$env{'form.folderpath'});
                   12666:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  12667:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12668:             $containers{'0'}='page';
                   12669:         } else {
                   12670:             $containers{'0'}='sequence';
                   12671:         }
1.1055    raeburn  12672:     }
                   12673:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12674:     if ($numitems) {
                   12675:         for (my $i=1; $i<=$numitems; $i++) {
                   12676:             my $path = $env{'form.archive_content_'.$i};
                   12677:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12678:                 my $item = $1;
                   12679:                 $toplevelitems{$item} = $i;
                   12680:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12681:                     $is_dir{$item} = 1;
                   12682:                 }
                   12683:             }
                   12684:         }
                   12685:     }
1.1067    raeburn  12686:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12687:     if (keys(%toplevelitems) > 0) {
                   12688:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12689:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12690:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12691:     }
1.1066    raeburn  12692:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12693:     if ($numitems) {
                   12694:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  12695:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12696:             my $path = $env{'form.archive_content_'.$i};
                   12697:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12698:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12699:                     if ($prefix ne '' && $path ne '') {
                   12700:                         if (-e $prefix.$path) {
1.1066    raeburn  12701:                             if ((@archdirs > 0) && 
                   12702:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12703:                                 $todeletedir{$prefix.$path} = 1;
                   12704:                             } else {
                   12705:                                 $todelete{$prefix.$path} = 1;
                   12706:                             }
1.1055    raeburn  12707:                         }
                   12708:                     }
                   12709:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12710:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12711:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12712:                     $docstitle = $env{'form.archive_title_'.$i};
                   12713:                     if ($docstitle eq '') {
                   12714:                         $docstitle = $title;
                   12715:                     }
1.1055    raeburn  12716:                     $outer = 0;
1.1056    raeburn  12717:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12718:                         if (@{$dirorder{$i}} > 0) {
                   12719:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12720:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12721:                                     $outer = $item;
                   12722:                                     last;
                   12723:                                 }
                   12724:                             }
                   12725:                         }
                   12726:                     }
                   12727:                     my ($errtext,$fatal) = 
                   12728:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12729:                                                '/'.$folders{$outer}.'.'.
                   12730:                                                $containers{$outer});
                   12731:                     next if ($fatal);
                   12732:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12733:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12734:                             $mapinner{$i} = time;
1.1055    raeburn  12735:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12736:                             $containers{$i} = 'sequence';
                   12737:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12738:                                       $folders{$i}.'.'.$containers{$i};
                   12739:                             my $newidx = &LONCAPA::map::getresidx();
                   12740:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12741:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12742:                             push(@LONCAPA::map::order,$newidx);
                   12743:                             my ($outtext,$errtext) =
                   12744:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12745:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12746:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12747:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12748:                             unless ($errtext) {
                   12749:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   12750:                             }
1.1055    raeburn  12751:                         }
                   12752:                     } else {
                   12753:                         if ($context eq 'coursedocs') {
                   12754:                             my $newidx=&LONCAPA::map::getresidx();
                   12755:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12756:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12757:                                       $title;
                   12758:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12759:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   12760:                             }
                   12761:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12762:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12763:                             }
                   12764:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12765:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  12766:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  12767:                                 unless ($ishome) {
                   12768:                                     my $fetch = "$newdest{$i}/$title";
                   12769:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12770:                                     $prompttofetch{$fetch} = 1;
                   12771:                                 }
1.1055    raeburn  12772:                             }
                   12773:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12774:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12775:                             push(@LONCAPA::map::order, $newidx);
                   12776:                             my ($outtext,$errtext)=
                   12777:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12778:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12779:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  12780:                             unless ($errtext) {
                   12781:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12782:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   12783:                                 }
                   12784:                             }
1.1055    raeburn  12785:                         }
                   12786:                     }
1.1075.2.11  raeburn  12787:                 }
                   12788:             } else {
                   12789:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
                   12790:             }
                   12791:         }
                   12792:         for (my $i=1; $i<=$numitems; $i++) {
                   12793:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12794:             my $path = $env{'form.archive_content_'.$i};
                   12795:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12796:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12797:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12798:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12799:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12800:                         my ($itemidx,$fullpath,$relpath);
                   12801:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12802:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12803:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  12804:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12805:                                     $itemidx = $j;
1.1056    raeburn  12806:                                 }
                   12807:                             }
1.1075.2.11  raeburn  12808:                         }
                   12809:                         if ($itemidx eq '') {
                   12810:                             $itemidx =  0;
                   12811:                         }
                   12812:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12813:                             if ($mapinner{$referrer{$i}}) {
                   12814:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12815:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12816:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12817:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12818:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12819:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12820:                                             if (!-e $fullpath) {
                   12821:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12822:                                             }
                   12823:                                         }
1.1075.2.11  raeburn  12824:                                     } else {
                   12825:                                         last;
1.1056    raeburn  12826:                                     }
1.1075.2.11  raeburn  12827:                                 }
                   12828:                             }
                   12829:                         } elsif ($newdest{$referrer{$i}}) {
                   12830:                             $fullpath = $newdest{$referrer{$i}};
                   12831:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12832:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12833:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12834:                                     last;
                   12835:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12836:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12837:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12838:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12839:                                         if (!-e $fullpath) {
                   12840:                                             mkdir($fullpath,0755);
1.1056    raeburn  12841:                                         }
                   12842:                                     }
1.1075.2.11  raeburn  12843:                                 } else {
                   12844:                                     last;
1.1056    raeburn  12845:                                 }
1.1075.2.11  raeburn  12846:                             }
                   12847:                         }
                   12848:                         if ($fullpath ne '') {
                   12849:                             if (-e "$prefix$path") {
                   12850:                                 system("mv $prefix$path $fullpath/$title");
                   12851:                             }
                   12852:                             if (-e "$fullpath/$title") {
                   12853:                                 my $showpath;
                   12854:                                 if ($relpath ne '') {
                   12855:                                     $showpath = "$relpath/$title";
                   12856:                                 } else {
                   12857:                                     $showpath = "/$title";
1.1056    raeburn  12858:                                 }
1.1075.2.11  raeburn  12859:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12860:                             }
                   12861:                             unless ($ishome) {
                   12862:                                 my $fetch = "$fullpath/$title";
                   12863:                                 $fetch =~ s/^\Q$prefix$dir\E//;
                   12864:                                 $prompttofetch{$fetch} = 1;
1.1055    raeburn  12865:                             }
                   12866:                         }
                   12867:                     }
1.1075.2.11  raeburn  12868:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12869:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12870:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12871:                 }
                   12872:             } else {
1.1075.2.11  raeburn  12873:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
1.1055    raeburn  12874:             }
                   12875:         }
                   12876:         if (keys(%todelete)) {
                   12877:             foreach my $key (keys(%todelete)) {
                   12878:                 unlink($key);
1.1066    raeburn  12879:             }
                   12880:         }
                   12881:         if (keys(%todeletedir)) {
                   12882:             foreach my $key (keys(%todeletedir)) {
                   12883:                 rmdir($key);
                   12884:             }
                   12885:         }
                   12886:         foreach my $dir (sort(keys(%is_dir))) {
                   12887:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12888:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12889:             }
                   12890:         }
1.1067    raeburn  12891:         if ($result ne '') {
                   12892:             $output .= '<ul>'."\n".
                   12893:                        $result."\n".
                   12894:                        '</ul>';
                   12895:         }
                   12896:         unless ($ishome) {
                   12897:             my $replicationfail;
                   12898:             foreach my $item (keys(%prompttofetch)) {
                   12899:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12900:                 unless ($fetchresult eq 'ok') {
                   12901:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12902:                 }
                   12903:             }
                   12904:             if ($replicationfail) {
                   12905:                 $output .= '<p class="LC_error">'.
                   12906:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12907:                            $replicationfail.
                   12908:                            '</ul></p>';
                   12909:             }
                   12910:         }
1.1055    raeburn  12911:     } else {
                   12912:         $warning = &mt('No items found in archive.');
                   12913:     }
                   12914:     if ($error) {
                   12915:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12916:                    $error.'</p>'."\n";
                   12917:     }
                   12918:     if ($warning) {
                   12919:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12920:     }
                   12921:     return $output;
                   12922: }
                   12923: 
1.1066    raeburn  12924: sub cleanup_empty_dirs {
                   12925:     my ($path) = @_;
                   12926:     if (($path ne '') && (-d $path)) {
                   12927:         if (opendir(my $dirh,$path)) {
                   12928:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12929:             my $numitems = 0;
                   12930:             foreach my $item (@dircontents) {
                   12931:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  12932:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12933:                     if (-e "$path/$item") {
                   12934:                         $numitems ++;
                   12935:                     }
                   12936:                 } else {
                   12937:                     $numitems ++;
                   12938:                 }
                   12939:             }
                   12940:             if ($numitems == 0) {
                   12941:                 rmdir($path);
                   12942:             }
                   12943:             closedir($dirh);
                   12944:         }
                   12945:     }
                   12946:     return;
                   12947: }
                   12948: 
1.41      ng       12949: =pod
1.45      matthew  12950: 
1.1075.2.56  raeburn  12951: =item * &get_folder_hierarchy()
1.1068    raeburn  12952: 
                   12953: Provides hierarchy of names of folders/sub-folders containing the current
                   12954: item,
                   12955: 
                   12956: Inputs: 3
                   12957:      - $navmap - navmaps object
                   12958: 
                   12959:      - $map - url for map (either the trigger itself, or map containing
                   12960:                            the resource, which is the trigger).
                   12961: 
                   12962:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12963: 
                   12964: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12965: 
                   12966: =cut
                   12967: 
                   12968: sub get_folder_hierarchy {
                   12969:     my ($navmap,$map,$showitem) = @_;
                   12970:     my @pathitems;
                   12971:     if (ref($navmap)) {
                   12972:         my $mapres = $navmap->getResourceByUrl($map);
                   12973:         if (ref($mapres)) {
                   12974:             my $pcslist = $mapres->map_hierarchy();
                   12975:             if ($pcslist ne '') {
                   12976:                 my @pcs = split(/,/,$pcslist);
                   12977:                 foreach my $pc (@pcs) {
                   12978:                     if ($pc == 1) {
1.1075.2.38  raeburn  12979:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12980:                     } else {
                   12981:                         my $res = $navmap->getByMapPc($pc);
                   12982:                         if (ref($res)) {
                   12983:                             my $title = $res->compTitle();
                   12984:                             $title =~ s/\W+/_/g;
                   12985:                             if ($title ne '') {
                   12986:                                 push(@pathitems,$title);
                   12987:                             }
                   12988:                         }
                   12989:                     }
                   12990:                 }
                   12991:             }
1.1071    raeburn  12992:             if ($showitem) {
                   12993:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  12994:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12995:                 } else {
                   12996:                     my $maptitle = $mapres->compTitle();
                   12997:                     $maptitle =~ s/\W+/_/g;
                   12998:                     if ($maptitle ne '') {
                   12999:                         push(@pathitems,$maptitle);
                   13000:                     }
1.1068    raeburn  13001:                 }
                   13002:             }
                   13003:         }
                   13004:     }
                   13005:     return @pathitems;
                   13006: }
                   13007: 
                   13008: =pod
                   13009: 
1.1015    raeburn  13010: =item * &get_turnedin_filepath()
                   13011: 
                   13012: Determines path in a user's portfolio file for storage of files uploaded
                   13013: to a specific essayresponse or dropbox item.
                   13014: 
                   13015: Inputs: 3 required + 1 optional.
                   13016: $symb is symb for resource, $uname and $udom are for current user (required).
                   13017: $caller is optional (can be "submission", if routine is called when storing
                   13018: an upoaded file when "Submit Answer" button was pressed).
                   13019: 
                   13020: Returns array containing $path and $multiresp. 
                   13021: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13022: than one file upload item.  Callers of routine should append partid as a 
                   13023: subdirectory to $path in cases where $multiresp is 1.
                   13024: 
                   13025: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13026: 
                   13027: =cut
                   13028: 
                   13029: sub get_turnedin_filepath {
                   13030:     my ($symb,$uname,$udom,$caller) = @_;
                   13031:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13032:     my $turnindir;
                   13033:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13034:     $turnindir = $userhash{'turnindir'};
                   13035:     my ($path,$multiresp);
                   13036:     if ($turnindir eq '') {
                   13037:         if ($caller eq 'submission') {
                   13038:             $turnindir = &mt('turned in');
                   13039:             $turnindir =~ s/\W+/_/g;
                   13040:             my %newhash = (
                   13041:                             'turnindir' => $turnindir,
                   13042:                           );
                   13043:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13044:         }
                   13045:     }
                   13046:     if ($turnindir ne '') {
                   13047:         $path = '/'.$turnindir.'/';
                   13048:         my ($multipart,$turnin,@pathitems);
                   13049:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13050:         if (defined($navmap)) {
                   13051:             my $mapres = $navmap->getResourceByUrl($map);
                   13052:             if (ref($mapres)) {
                   13053:                 my $pcslist = $mapres->map_hierarchy();
                   13054:                 if ($pcslist ne '') {
                   13055:                     foreach my $pc (split(/,/,$pcslist)) {
                   13056:                         my $res = $navmap->getByMapPc($pc);
                   13057:                         if (ref($res)) {
                   13058:                             my $title = $res->compTitle();
                   13059:                             $title =~ s/\W+/_/g;
                   13060:                             if ($title ne '') {
1.1075.2.48  raeburn  13061:                                 if (($pc > 1) && (length($title) > 12)) {
                   13062:                                     $title = substr($title,0,12);
                   13063:                                 }
1.1015    raeburn  13064:                                 push(@pathitems,$title);
                   13065:                             }
                   13066:                         }
                   13067:                     }
                   13068:                 }
                   13069:                 my $maptitle = $mapres->compTitle();
                   13070:                 $maptitle =~ s/\W+/_/g;
                   13071:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  13072:                     if (length($maptitle) > 12) {
                   13073:                         $maptitle = substr($maptitle,0,12);
                   13074:                     }
1.1015    raeburn  13075:                     push(@pathitems,$maptitle);
                   13076:                 }
                   13077:                 unless ($env{'request.state'} eq 'construct') {
                   13078:                     my $res = $navmap->getBySymb($symb);
                   13079:                     if (ref($res)) {
                   13080:                         my $partlist = $res->parts();
                   13081:                         my $totaluploads = 0;
                   13082:                         if (ref($partlist) eq 'ARRAY') {
                   13083:                             foreach my $part (@{$partlist}) {
                   13084:                                 my @types = $res->responseType($part);
                   13085:                                 my @ids = $res->responseIds($part);
                   13086:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13087:                                     if ($types[$i] eq 'essay') {
                   13088:                                         my $partid = $part.'_'.$ids[$i];
                   13089:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13090:                                             $totaluploads ++;
                   13091:                                         }
                   13092:                                     }
                   13093:                                 }
                   13094:                             }
                   13095:                             if ($totaluploads > 1) {
                   13096:                                 $multiresp = 1;
                   13097:                             }
                   13098:                         }
                   13099:                     }
                   13100:                 }
                   13101:             } else {
                   13102:                 return;
                   13103:             }
                   13104:         } else {
                   13105:             return;
                   13106:         }
                   13107:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13108:         $restitle =~ s/\W+/_/g;
                   13109:         if ($restitle eq '') {
                   13110:             $restitle = ($resurl =~ m{/[^/]+$});
                   13111:             if ($restitle eq '') {
                   13112:                 $restitle = time;
                   13113:             }
                   13114:         }
1.1075.2.48  raeburn  13115:         if (length($restitle) > 12) {
                   13116:             $restitle = substr($restitle,0,12);
                   13117:         }
1.1015    raeburn  13118:         push(@pathitems,$restitle);
                   13119:         $path .= join('/',@pathitems);
                   13120:     }
                   13121:     return ($path,$multiresp);
                   13122: }
                   13123: 
                   13124: =pod
                   13125: 
1.464     albertel 13126: =back
1.41      ng       13127: 
1.112     bowersj2 13128: =head1 CSV Upload/Handling functions
1.38      albertel 13129: 
1.41      ng       13130: =over 4
                   13131: 
1.648     raeburn  13132: =item * &upfile_store($r)
1.41      ng       13133: 
                   13134: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13135: needs $env{'form.upfile'}
1.41      ng       13136: returns $datatoken to be put into hidden field
                   13137: 
                   13138: =cut
1.31      albertel 13139: 
                   13140: sub upfile_store {
                   13141:     my $r=shift;
1.258     albertel 13142:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13143:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13144:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13145:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13146: 
1.258     albertel 13147:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   13148: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 13149:     {
1.158     raeburn  13150:         my $datafile = $r->dir_config('lonDaemons').
                   13151:                            '/tmp/'.$datatoken.'.tmp';
                   13152:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 13153:             print $fh $env{'form.upfile'};
1.158     raeburn  13154:             close($fh);
                   13155:         }
1.31      albertel 13156:     }
                   13157:     return $datatoken;
                   13158: }
                   13159: 
1.56      matthew  13160: =pod
                   13161: 
1.648     raeburn  13162: =item * &load_tmp_file($r)
1.41      ng       13163: 
                   13164: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 13165: needs $env{'form.datatoken'},
                   13166: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13167: 
                   13168: =cut
1.31      albertel 13169: 
                   13170: sub load_tmp_file {
                   13171:     my $r=shift;
                   13172:     my @studentdata=();
                   13173:     {
1.158     raeburn  13174:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 13175:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  13176:         if ( open(my $fh,"<$studentfile") ) {
                   13177:             @studentdata=<$fh>;
                   13178:             close($fh);
                   13179:         }
1.31      albertel 13180:     }
1.258     albertel 13181:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13182: }
                   13183: 
1.56      matthew  13184: =pod
                   13185: 
1.648     raeburn  13186: =item * &upfile_record_sep()
1.41      ng       13187: 
                   13188: Separate uploaded file into records
                   13189: returns array of records,
1.258     albertel 13190: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13191: 
                   13192: =cut
1.31      albertel 13193: 
                   13194: sub upfile_record_sep {
1.258     albertel 13195:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13196:     } else {
1.248     albertel 13197: 	my @records;
1.258     albertel 13198: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13199: 	    if ($line=~/^\s*$/) { next; }
                   13200: 	    push(@records,$line);
                   13201: 	}
                   13202: 	return @records;
1.31      albertel 13203:     }
                   13204: }
                   13205: 
1.56      matthew  13206: =pod
                   13207: 
1.648     raeburn  13208: =item * &record_sep($record)
1.41      ng       13209: 
1.258     albertel 13210: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13211: 
                   13212: =cut
                   13213: 
1.263     www      13214: sub takeleft {
                   13215:     my $index=shift;
                   13216:     return substr('0000'.$index,-4,4);
                   13217: }
                   13218: 
1.31      albertel 13219: sub record_sep {
                   13220:     my $record=shift;
                   13221:     my %components=();
1.258     albertel 13222:     if ($env{'form.upfiletype'} eq 'xml') {
                   13223:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13224:         my $i=0;
1.356     albertel 13225:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13226:             $field=~s/^(\"|\')//;
                   13227:             $field=~s/(\"|\')$//;
1.263     www      13228:             $components{&takeleft($i)}=$field;
1.31      albertel 13229:             $i++;
                   13230:         }
1.258     albertel 13231:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13232:         my $i=0;
1.356     albertel 13233:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13234:             $field=~s/^(\"|\')//;
                   13235:             $field=~s/(\"|\')$//;
1.263     www      13236:             $components{&takeleft($i)}=$field;
1.31      albertel 13237:             $i++;
                   13238:         }
                   13239:     } else {
1.561     www      13240:         my $separator=',';
1.480     banghart 13241:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13242:             $separator=';';
1.480     banghart 13243:         }
1.31      albertel 13244:         my $i=0;
1.561     www      13245: # the character we are looking for to indicate the end of a quote or a record 
                   13246:         my $looking_for=$separator;
                   13247: # do not add the characters to the fields
                   13248:         my $ignore=0;
                   13249: # we just encountered a separator (or the beginning of the record)
                   13250:         my $just_found_separator=1;
                   13251: # store the field we are working on here
                   13252:         my $field='';
                   13253: # work our way through all characters in record
                   13254:         foreach my $character ($record=~/(.)/g) {
                   13255:             if ($character eq $looking_for) {
                   13256:                if ($character ne $separator) {
                   13257: # Found the end of a quote, again looking for separator
                   13258:                   $looking_for=$separator;
                   13259:                   $ignore=1;
                   13260:                } else {
                   13261: # Found a separator, store away what we got
                   13262:                   $components{&takeleft($i)}=$field;
                   13263: 	          $i++;
                   13264:                   $just_found_separator=1;
                   13265:                   $ignore=0;
                   13266:                   $field='';
                   13267:                }
                   13268:                next;
                   13269:             }
                   13270: # single or double quotation marks after a separator indicate beginning of a quote
                   13271: # we are now looking for the end of the quote and need to ignore separators
                   13272:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13273:                $looking_for=$character;
                   13274:                next;
                   13275:             }
                   13276: # ignore would be true after we reached the end of a quote
                   13277:             if ($ignore) { next; }
                   13278:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13279:             $field.=$character;
                   13280:             $just_found_separator=0; 
1.31      albertel 13281:         }
1.561     www      13282: # catch the very last entry, since we never encountered the separator
                   13283:         $components{&takeleft($i)}=$field;
1.31      albertel 13284:     }
                   13285:     return %components;
                   13286: }
                   13287: 
1.144     matthew  13288: ######################################################
                   13289: ######################################################
                   13290: 
1.56      matthew  13291: =pod
                   13292: 
1.648     raeburn  13293: =item * &upfile_select_html()
1.41      ng       13294: 
1.144     matthew  13295: Return HTML code to select a file from the users machine and specify 
                   13296: the file type.
1.41      ng       13297: 
                   13298: =cut
                   13299: 
1.144     matthew  13300: ######################################################
                   13301: ######################################################
1.31      albertel 13302: sub upfile_select_html {
1.144     matthew  13303:     my %Types = (
                   13304:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13305:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13306:                  space => &mt('Space separated'),
                   13307:                  tab   => &mt('Tabulator separated'),
                   13308: #                 xml   => &mt('HTML/XML'),
                   13309:                  );
                   13310:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13311:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13312:     foreach my $type (sort(keys(%Types))) {
                   13313:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13314:     }
                   13315:     $Str .= "</select>\n";
                   13316:     return $Str;
1.31      albertel 13317: }
                   13318: 
1.301     albertel 13319: sub get_samples {
                   13320:     my ($records,$toget) = @_;
                   13321:     my @samples=({});
                   13322:     my $got=0;
                   13323:     foreach my $rec (@$records) {
                   13324: 	my %temp = &record_sep($rec);
                   13325: 	if (! grep(/\S/, values(%temp))) { next; }
                   13326: 	if (%temp) {
                   13327: 	    $samples[$got]=\%temp;
                   13328: 	    $got++;
                   13329: 	    if ($got == $toget) { last; }
                   13330: 	}
                   13331:     }
                   13332:     return \@samples;
                   13333: }
                   13334: 
1.144     matthew  13335: ######################################################
                   13336: ######################################################
                   13337: 
1.56      matthew  13338: =pod
                   13339: 
1.648     raeburn  13340: =item * &csv_print_samples($r,$records)
1.41      ng       13341: 
                   13342: Prints a table of sample values from each column uploaded $r is an
                   13343: Apache Request ref, $records is an arrayref from
                   13344: &Apache::loncommon::upfile_record_sep
                   13345: 
                   13346: =cut
                   13347: 
1.144     matthew  13348: ######################################################
                   13349: ######################################################
1.31      albertel 13350: sub csv_print_samples {
                   13351:     my ($r,$records) = @_;
1.662     bisitz   13352:     my $samples = &get_samples($records,5);
1.301     albertel 13353: 
1.594     raeburn  13354:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13355:               &start_data_table_header_row());
1.356     albertel 13356:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13357:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13358:     $r->print(&end_data_table_header_row());
1.301     albertel 13359:     foreach my $hash (@$samples) {
1.594     raeburn  13360: 	$r->print(&start_data_table_row());
1.356     albertel 13361: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13362: 	    $r->print('<td>');
1.356     albertel 13363: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13364: 	    $r->print('</td>');
                   13365: 	}
1.594     raeburn  13366: 	$r->print(&end_data_table_row());
1.31      albertel 13367:     }
1.594     raeburn  13368:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13369: }
                   13370: 
1.144     matthew  13371: ######################################################
                   13372: ######################################################
                   13373: 
1.56      matthew  13374: =pod
                   13375: 
1.648     raeburn  13376: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13377: 
                   13378: Prints a table to create associations between values and table columns.
1.144     matthew  13379: 
1.41      ng       13380: $r is an Apache Request ref,
                   13381: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13382: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13383: 
                   13384: =cut
                   13385: 
1.144     matthew  13386: ######################################################
                   13387: ######################################################
1.31      albertel 13388: sub csv_print_select_table {
                   13389:     my ($r,$records,$d) = @_;
1.301     albertel 13390:     my $i=0;
                   13391:     my $samples = &get_samples($records,1);
1.144     matthew  13392:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13393: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13394:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13395:               '<th>'.&mt('Column').'</th>'.
                   13396:               &end_data_table_header_row()."\n");
1.356     albertel 13397:     foreach my $array_ref (@$d) {
                   13398: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13399: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13400: 
1.875     bisitz   13401: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13402: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13403: 	$r->print('<option value="none"></option>');
1.356     albertel 13404: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13405: 	    $r->print('<option value="'.$sample.'"'.
                   13406:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13407:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13408: 	}
1.594     raeburn  13409: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13410: 	$i++;
                   13411:     }
1.594     raeburn  13412:     $r->print(&end_data_table());
1.31      albertel 13413:     $i--;
                   13414:     return $i;
                   13415: }
1.56      matthew  13416: 
1.144     matthew  13417: ######################################################
                   13418: ######################################################
                   13419: 
1.56      matthew  13420: =pod
1.31      albertel 13421: 
1.648     raeburn  13422: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13423: 
                   13424: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13425: 
                   13426: $r is an Apache Request ref,
                   13427: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13428: $d is an array of 2 element arrays (internal name, displayed name)
                   13429: 
                   13430: =cut
                   13431: 
1.144     matthew  13432: ######################################################
                   13433: ######################################################
1.31      albertel 13434: sub csv_samples_select_table {
                   13435:     my ($r,$records,$d) = @_;
                   13436:     my $i=0;
1.144     matthew  13437:     #
1.662     bisitz   13438:     my $max_samples = 5;
                   13439:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13440:     $r->print(&start_data_table().
                   13441:               &start_data_table_header_row().'<th>'.
                   13442:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13443:               &end_data_table_header_row());
1.301     albertel 13444: 
                   13445:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13446: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13447: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13448: 	foreach my $option (@$d) {
                   13449: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13450: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13451:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13452:                       $display.'</option>');
1.31      albertel 13453: 	}
                   13454: 	$r->print('</select></td><td>');
1.662     bisitz   13455: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13456: 	    if (defined($samples->[$line]{$key})) { 
                   13457: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13458: 	    }
                   13459: 	}
1.594     raeburn  13460: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13461: 	$i++;
                   13462:     }
1.594     raeburn  13463:     $r->print(&end_data_table());
1.31      albertel 13464:     $i--;
                   13465:     return($i);
1.115     matthew  13466: }
                   13467: 
1.144     matthew  13468: ######################################################
                   13469: ######################################################
                   13470: 
1.115     matthew  13471: =pod
                   13472: 
1.648     raeburn  13473: =item * &clean_excel_name($name)
1.115     matthew  13474: 
                   13475: Returns a replacement for $name which does not contain any illegal characters.
                   13476: 
                   13477: =cut
                   13478: 
1.144     matthew  13479: ######################################################
                   13480: ######################################################
1.115     matthew  13481: sub clean_excel_name {
                   13482:     my ($name) = @_;
                   13483:     $name =~ s/[:\*\?\/\\]//g;
                   13484:     if (length($name) > 31) {
                   13485:         $name = substr($name,0,31);
                   13486:     }
                   13487:     return $name;
1.25      albertel 13488: }
1.84      albertel 13489: 
1.85      albertel 13490: =pod
                   13491: 
1.648     raeburn  13492: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13493: 
                   13494: Returns either 1 or undef
                   13495: 
                   13496: 1 if the part is to be hidden, undef if it is to be shown
                   13497: 
                   13498: Arguments are:
                   13499: 
                   13500: $id the id of the part to be checked
                   13501: $symb, optional the symb of the resource to check
                   13502: $udom, optional the domain of the user to check for
                   13503: $uname, optional the username of the user to check for
                   13504: 
                   13505: =cut
1.84      albertel 13506: 
                   13507: sub check_if_partid_hidden {
                   13508:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13509:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13510: 					 $symb,$udom,$uname);
1.141     albertel 13511:     my $truth=1;
                   13512:     #if the string starts with !, then the list is the list to show not hide
                   13513:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13514:     my @hiddenlist=split(/,/,$hiddenparts);
                   13515:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13516: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13517:     }
1.141     albertel 13518:     return !$truth;
1.84      albertel 13519: }
1.127     matthew  13520: 
1.138     matthew  13521: 
                   13522: ############################################################
                   13523: ############################################################
                   13524: 
                   13525: =pod
                   13526: 
1.157     matthew  13527: =back 
                   13528: 
1.138     matthew  13529: =head1 cgi-bin script and graphing routines
                   13530: 
1.157     matthew  13531: =over 4
                   13532: 
1.648     raeburn  13533: =item * &get_cgi_id()
1.138     matthew  13534: 
                   13535: Inputs: none
                   13536: 
                   13537: Returns an id which can be used to pass environment variables
                   13538: to various cgi-bin scripts.  These environment variables will
                   13539: be removed from the users environment after a given time by
                   13540: the routine &Apache::lonnet::transfer_profile_to_env.
                   13541: 
                   13542: =cut
                   13543: 
                   13544: ############################################################
                   13545: ############################################################
1.152     albertel 13546: my $uniq=0;
1.136     matthew  13547: sub get_cgi_id {
1.154     albertel 13548:     $uniq=($uniq+1)%100000;
1.280     albertel 13549:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13550: }
                   13551: 
1.127     matthew  13552: ############################################################
                   13553: ############################################################
                   13554: 
                   13555: =pod
                   13556: 
1.648     raeburn  13557: =item * &DrawBarGraph()
1.127     matthew  13558: 
1.138     matthew  13559: Facilitates the plotting of data in a (stacked) bar graph.
                   13560: Puts plot definition data into the users environment in order for 
                   13561: graph.png to plot it.  Returns an <img> tag for the plot.
                   13562: The bars on the plot are labeled '1','2',...,'n'.
                   13563: 
                   13564: Inputs:
                   13565: 
                   13566: =over 4
                   13567: 
                   13568: =item $Title: string, the title of the plot
                   13569: 
                   13570: =item $xlabel: string, text describing the X-axis of the plot
                   13571: 
                   13572: =item $ylabel: string, text describing the Y-axis of the plot
                   13573: 
                   13574: =item $Max: scalar, the maximum Y value to use in the plot
                   13575: If $Max is < any data point, the graph will not be rendered.
                   13576: 
1.140     matthew  13577: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13578: they are plotted.  If undefined, default values will be used.
                   13579: 
1.178     matthew  13580: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13581: 
1.138     matthew  13582: =item @Values: An array of array references.  Each array reference holds data
                   13583: to be plotted in a stacked bar chart.
                   13584: 
1.239     matthew  13585: =item If the final element of @Values is a hash reference the key/value
                   13586: pairs will be added to the graph definition.
                   13587: 
1.138     matthew  13588: =back
                   13589: 
                   13590: Returns:
                   13591: 
                   13592: An <img> tag which references graph.png and the appropriate identifying
                   13593: information for the plot.
                   13594: 
1.127     matthew  13595: =cut
                   13596: 
                   13597: ############################################################
                   13598: ############################################################
1.134     matthew  13599: sub DrawBarGraph {
1.178     matthew  13600:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13601:     #
                   13602:     if (! defined($colors)) {
                   13603:         $colors = ['#33ff00', 
                   13604:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13605:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13606:                   ]; 
                   13607:     }
1.228     matthew  13608:     my $extra_settings = {};
                   13609:     if (ref($Values[-1]) eq 'HASH') {
                   13610:         $extra_settings = pop(@Values);
                   13611:     }
1.127     matthew  13612:     #
1.136     matthew  13613:     my $identifier = &get_cgi_id();
                   13614:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13615:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13616:         return '';
                   13617:     }
1.225     matthew  13618:     #
                   13619:     my @Labels;
                   13620:     if (defined($labels)) {
                   13621:         @Labels = @$labels;
                   13622:     } else {
                   13623:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  13624:             push(@Labels,$i+1);
1.225     matthew  13625:         }
                   13626:     }
                   13627:     #
1.129     matthew  13628:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13629:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13630:     my %ValuesHash;
                   13631:     my $NumSets=1;
                   13632:     foreach my $array (@Values) {
                   13633:         next if (! ref($array));
1.136     matthew  13634:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13635:             join(',',@$array);
1.129     matthew  13636:     }
1.127     matthew  13637:     #
1.136     matthew  13638:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13639:     if ($NumBars < 3) {
                   13640:         $width = 120+$NumBars*32;
1.220     matthew  13641:         $xskip = 1;
1.225     matthew  13642:         $bar_width = 30;
                   13643:     } elsif ($NumBars < 5) {
                   13644:         $width = 120+$NumBars*20;
                   13645:         $xskip = 1;
                   13646:         $bar_width = 20;
1.220     matthew  13647:     } elsif ($NumBars < 10) {
1.136     matthew  13648:         $width = 120+$NumBars*15;
                   13649:         $xskip = 1;
                   13650:         $bar_width = 15;
                   13651:     } elsif ($NumBars <= 25) {
                   13652:         $width = 120+$NumBars*11;
                   13653:         $xskip = 5;
                   13654:         $bar_width = 8;
                   13655:     } elsif ($NumBars <= 50) {
                   13656:         $width = 120+$NumBars*8;
                   13657:         $xskip = 5;
                   13658:         $bar_width = 4;
                   13659:     } else {
                   13660:         $width = 120+$NumBars*8;
                   13661:         $xskip = 5;
                   13662:         $bar_width = 4;
                   13663:     }
                   13664:     #
1.137     matthew  13665:     $Max = 1 if ($Max < 1);
                   13666:     if ( int($Max) < $Max ) {
                   13667:         $Max++;
                   13668:         $Max = int($Max);
                   13669:     }
1.127     matthew  13670:     $Title  = '' if (! defined($Title));
                   13671:     $xlabel = '' if (! defined($xlabel));
                   13672:     $ylabel = '' if (! defined($ylabel));
1.369     www      13673:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13674:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13675:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13676:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13677:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13678:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13679:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13680:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13681:     $ValuesHash{$id.'.height'}   = $height;
                   13682:     $ValuesHash{$id.'.width'}    = $width;
                   13683:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13684:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13685:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13686:     #
1.228     matthew  13687:     # Deal with other parameters
                   13688:     while (my ($key,$value) = each(%$extra_settings)) {
                   13689:         $ValuesHash{$id.'.'.$key} = $value;
                   13690:     }
                   13691:     #
1.646     raeburn  13692:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13693:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13694: }
                   13695: 
                   13696: ############################################################
                   13697: ############################################################
                   13698: 
                   13699: =pod
                   13700: 
1.648     raeburn  13701: =item * &DrawXYGraph()
1.137     matthew  13702: 
1.138     matthew  13703: Facilitates the plotting of data in an XY graph.
                   13704: Puts plot definition data into the users environment in order for 
                   13705: graph.png to plot it.  Returns an <img> tag for the plot.
                   13706: 
                   13707: Inputs:
                   13708: 
                   13709: =over 4
                   13710: 
                   13711: =item $Title: string, the title of the plot
                   13712: 
                   13713: =item $xlabel: string, text describing the X-axis of the plot
                   13714: 
                   13715: =item $ylabel: string, text describing the Y-axis of the plot
                   13716: 
                   13717: =item $Max: scalar, the maximum Y value to use in the plot
                   13718: If $Max is < any data point, the graph will not be rendered.
                   13719: 
                   13720: =item $colors: Array ref containing the hex color codes for the data to be 
                   13721: plotted in.  If undefined, default values will be used.
                   13722: 
                   13723: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13724: 
                   13725: =item $Ydata: Array ref containing Array refs.  
1.185     www      13726: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13727: 
                   13728: =item %Values: hash indicating or overriding any default values which are 
                   13729: passed to graph.png.  
                   13730: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13731: 
                   13732: =back
                   13733: 
                   13734: Returns:
                   13735: 
                   13736: An <img> tag which references graph.png and the appropriate identifying
                   13737: information for the plot.
                   13738: 
1.137     matthew  13739: =cut
                   13740: 
                   13741: ############################################################
                   13742: ############################################################
                   13743: sub DrawXYGraph {
                   13744:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13745:     #
                   13746:     # Create the identifier for the graph
                   13747:     my $identifier = &get_cgi_id();
                   13748:     my $id = 'cgi.'.$identifier;
                   13749:     #
                   13750:     $Title  = '' if (! defined($Title));
                   13751:     $xlabel = '' if (! defined($xlabel));
                   13752:     $ylabel = '' if (! defined($ylabel));
                   13753:     my %ValuesHash = 
                   13754:         (
1.369     www      13755:          $id.'.title'  => &escape($Title),
                   13756:          $id.'.xlabel' => &escape($xlabel),
                   13757:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13758:          $id.'.y_max_value'=> $Max,
                   13759:          $id.'.labels'     => join(',',@$Xlabels),
                   13760:          $id.'.PlotType'   => 'XY',
                   13761:          );
                   13762:     #
                   13763:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13764:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13765:     }
                   13766:     #
                   13767:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13768:         return '';
                   13769:     }
                   13770:     my $NumSets=1;
1.138     matthew  13771:     foreach my $array (@{$Ydata}){
1.137     matthew  13772:         next if (! ref($array));
                   13773:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13774:     }
1.138     matthew  13775:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13776:     #
                   13777:     # Deal with other parameters
                   13778:     while (my ($key,$value) = each(%Values)) {
                   13779:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13780:     }
                   13781:     #
1.646     raeburn  13782:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13783:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13784: }
                   13785: 
                   13786: ############################################################
                   13787: ############################################################
                   13788: 
                   13789: =pod
                   13790: 
1.648     raeburn  13791: =item * &DrawXYYGraph()
1.138     matthew  13792: 
                   13793: Facilitates the plotting of data in an XY graph with two Y axes.
                   13794: Puts plot definition data into the users environment in order for 
                   13795: graph.png to plot it.  Returns an <img> tag for the plot.
                   13796: 
                   13797: Inputs:
                   13798: 
                   13799: =over 4
                   13800: 
                   13801: =item $Title: string, the title of the plot
                   13802: 
                   13803: =item $xlabel: string, text describing the X-axis of the plot
                   13804: 
                   13805: =item $ylabel: string, text describing the Y-axis of the plot
                   13806: 
                   13807: =item $colors: Array ref containing the hex color codes for the data to be 
                   13808: plotted in.  If undefined, default values will be used.
                   13809: 
                   13810: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13811: 
                   13812: =item $Ydata1: The first data set
                   13813: 
                   13814: =item $Min1: The minimum value of the left Y-axis
                   13815: 
                   13816: =item $Max1: The maximum value of the left Y-axis
                   13817: 
                   13818: =item $Ydata2: The second data set
                   13819: 
                   13820: =item $Min2: The minimum value of the right Y-axis
                   13821: 
                   13822: =item $Max2: The maximum value of the left Y-axis
                   13823: 
                   13824: =item %Values: hash indicating or overriding any default values which are 
                   13825: passed to graph.png.  
                   13826: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13827: 
                   13828: =back
                   13829: 
                   13830: Returns:
                   13831: 
                   13832: An <img> tag which references graph.png and the appropriate identifying
                   13833: information for the plot.
1.136     matthew  13834: 
                   13835: =cut
                   13836: 
                   13837: ############################################################
                   13838: ############################################################
1.137     matthew  13839: sub DrawXYYGraph {
                   13840:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13841:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13842:     #
                   13843:     # Create the identifier for the graph
                   13844:     my $identifier = &get_cgi_id();
                   13845:     my $id = 'cgi.'.$identifier;
                   13846:     #
                   13847:     $Title  = '' if (! defined($Title));
                   13848:     $xlabel = '' if (! defined($xlabel));
                   13849:     $ylabel = '' if (! defined($ylabel));
                   13850:     my %ValuesHash = 
                   13851:         (
1.369     www      13852:          $id.'.title'  => &escape($Title),
                   13853:          $id.'.xlabel' => &escape($xlabel),
                   13854:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13855:          $id.'.labels' => join(',',@$Xlabels),
                   13856:          $id.'.PlotType' => 'XY',
                   13857:          $id.'.NumSets' => 2,
1.137     matthew  13858:          $id.'.two_axes' => 1,
                   13859:          $id.'.y1_max_value' => $Max1,
                   13860:          $id.'.y1_min_value' => $Min1,
                   13861:          $id.'.y2_max_value' => $Max2,
                   13862:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13863:          );
                   13864:     #
1.137     matthew  13865:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13866:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13867:     }
                   13868:     #
                   13869:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13870:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13871:         return '';
                   13872:     }
                   13873:     my $NumSets=1;
1.137     matthew  13874:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13875:         next if (! ref($array));
                   13876:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13877:     }
                   13878:     #
                   13879:     # Deal with other parameters
                   13880:     while (my ($key,$value) = each(%Values)) {
                   13881:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13882:     }
                   13883:     #
1.646     raeburn  13884:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13885:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13886: }
                   13887: 
                   13888: ############################################################
                   13889: ############################################################
                   13890: 
                   13891: =pod
                   13892: 
1.157     matthew  13893: =back 
                   13894: 
1.139     matthew  13895: =head1 Statistics helper routines?  
                   13896: 
                   13897: Bad place for them but what the hell.
                   13898: 
1.157     matthew  13899: =over 4
                   13900: 
1.648     raeburn  13901: =item * &chartlink()
1.139     matthew  13902: 
                   13903: Returns a link to the chart for a specific student.  
                   13904: 
                   13905: Inputs:
                   13906: 
                   13907: =over 4
                   13908: 
                   13909: =item $linktext: The text of the link
                   13910: 
                   13911: =item $sname: The students username
                   13912: 
                   13913: =item $sdomain: The students domain
                   13914: 
                   13915: =back
                   13916: 
1.157     matthew  13917: =back
                   13918: 
1.139     matthew  13919: =cut
                   13920: 
                   13921: ############################################################
                   13922: ############################################################
                   13923: sub chartlink {
                   13924:     my ($linktext, $sname, $sdomain) = @_;
                   13925:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13926:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13927:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13928:        '">'.$linktext.'</a>';
1.153     matthew  13929: }
                   13930: 
                   13931: #######################################################
                   13932: #######################################################
                   13933: 
                   13934: =pod
                   13935: 
                   13936: =head1 Course Environment Routines
1.157     matthew  13937: 
                   13938: =over 4
1.153     matthew  13939: 
1.648     raeburn  13940: =item * &restore_course_settings()
1.153     matthew  13941: 
1.648     raeburn  13942: =item * &store_course_settings()
1.153     matthew  13943: 
                   13944: Restores/Store indicated form parameters from the course environment.
                   13945: Will not overwrite existing values of the form parameters.
                   13946: 
                   13947: Inputs: 
                   13948: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13949: 
                   13950: a hash ref describing the data to be stored.  For example:
                   13951:    
                   13952: %Save_Parameters = ('Status' => 'scalar',
                   13953:     'chartoutputmode' => 'scalar',
                   13954:     'chartoutputdata' => 'scalar',
                   13955:     'Section' => 'array',
1.373     raeburn  13956:     'Group' => 'array',
1.153     matthew  13957:     'StudentData' => 'array',
                   13958:     'Maps' => 'array');
                   13959: 
                   13960: Returns: both routines return nothing
                   13961: 
1.631     raeburn  13962: =back
                   13963: 
1.153     matthew  13964: =cut
                   13965: 
                   13966: #######################################################
                   13967: #######################################################
                   13968: sub store_course_settings {
1.496     albertel 13969:     return &store_settings($env{'request.course.id'},@_);
                   13970: }
                   13971: 
                   13972: sub store_settings {
1.153     matthew  13973:     # save to the environment
                   13974:     # appenv the same items, just to be safe
1.300     albertel 13975:     my $udom  = $env{'user.domain'};
                   13976:     my $uname = $env{'user.name'};
1.496     albertel 13977:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13978:     my %SaveHash;
                   13979:     my %AppHash;
                   13980:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13981:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13982:         my $envname = 'environment.'.$basename;
1.258     albertel 13983:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13984:             # Save this value away
                   13985:             if ($type eq 'scalar' &&
1.258     albertel 13986:                 (! exists($env{$envname}) || 
                   13987:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13988:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13989:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13990:             } elsif ($type eq 'array') {
                   13991:                 my $stored_form;
1.258     albertel 13992:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13993:                     $stored_form = join(',',
                   13994:                                         map {
1.369     www      13995:                                             &escape($_);
1.258     albertel 13996:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13997:                 } else {
                   13998:                     $stored_form = 
1.369     www      13999:                         &escape($env{'form.'.$setting});
1.153     matthew  14000:                 }
                   14001:                 # Determine if the array contents are the same.
1.258     albertel 14002:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14003:                     $SaveHash{$basename} = $stored_form;
                   14004:                     $AppHash{$envname}   = $stored_form;
                   14005:                 }
                   14006:             }
                   14007:         }
                   14008:     }
                   14009:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14010:                                           $udom,$uname);
1.153     matthew  14011:     if ($put_result !~ /^(ok|delayed)/) {
                   14012:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14013:                                  'got error:'.$put_result);
                   14014:     }
                   14015:     # Make sure these settings stick around in this session, too
1.646     raeburn  14016:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14017:     return;
                   14018: }
                   14019: 
                   14020: sub restore_course_settings {
1.499     albertel 14021:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14022: }
                   14023: 
                   14024: sub restore_settings {
                   14025:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14026:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14027:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14028:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14029:             '.'.$setting;
1.258     albertel 14030:         if (exists($env{$envname})) {
1.153     matthew  14031:             if ($type eq 'scalar') {
1.258     albertel 14032:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14033:             } elsif ($type eq 'array') {
1.258     albertel 14034:                 $env{'form.'.$setting} = [ 
1.153     matthew  14035:                                            map { 
1.369     www      14036:                                                &unescape($_); 
1.258     albertel 14037:                                            } split(',',$env{$envname})
1.153     matthew  14038:                                            ];
                   14039:             }
                   14040:         }
                   14041:     }
1.127     matthew  14042: }
                   14043: 
1.618     raeburn  14044: #######################################################
                   14045: #######################################################
                   14046: 
                   14047: =pod
                   14048: 
                   14049: =head1 Domain E-mail Routines  
                   14050: 
                   14051: =over 4
                   14052: 
1.648     raeburn  14053: =item * &build_recipient_list()
1.618     raeburn  14054: 
1.1075.2.44  raeburn  14055: Build recipient lists for following types of e-mail:
1.766     raeburn  14056: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  14057: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14058: module change checking, student/employee ID conflict checks, as
                   14059: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14060: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14061: 
                   14062: Inputs:
1.1075.2.44  raeburn  14063: defmail (scalar - email address of default recipient),
                   14064: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14065: requestsmail, updatesmail, or idconflictsmail).
                   14066: 
1.619     raeburn  14067: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  14068: 
                   14069: origmail (scalar - email address of recipient from loncapa.conf,
                   14070: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  14071: 
1.655     raeburn  14072: Returns: comma separated list of addresses to which to send e-mail.
                   14073: 
                   14074: =back
1.618     raeburn  14075: 
                   14076: =cut
                   14077: 
                   14078: ############################################################
                   14079: ############################################################
                   14080: sub build_recipient_list {
1.619     raeburn  14081:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  14082:     my @recipients;
1.1075.2.122  raeburn  14083:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14084:     my %domconfig =
1.1075.2.122  raeburn  14085:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14086:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14087:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14088:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14089:                 my @contacts = ('adminemail','supportemail');
                   14090:                 foreach my $item (@contacts) {
                   14091:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14092:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14093:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14094:                             push(@recipients,$addr);
                   14095:                         }
1.619     raeburn  14096:                     }
1.1075.2.122  raeburn  14097:                 }
                   14098:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14099:                 if ($mailing eq 'helpdeskmail') {
                   14100:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14101:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14102:                         my @ok_bccs;
                   14103:                         foreach my $bcc (@bccs) {
                   14104:                             $bcc =~ s/^\s+//g;
                   14105:                             $bcc =~ s/\s+$//g;
                   14106:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14107:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14108:                                     push(@ok_bccs,$bcc);
                   14109:                                 }
                   14110:                             }
                   14111:                         }
                   14112:                         if (@ok_bccs > 0) {
                   14113:                             $allbcc = join(', ',@ok_bccs);
                   14114:                         }
                   14115:                     }
                   14116:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14117:                 }
                   14118:             }
1.766     raeburn  14119:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14120:             $lastresort = $origmail;
1.618     raeburn  14121:         }
1.619     raeburn  14122:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14123:         $lastresort = $origmail;
                   14124:     }
                   14125: 
                   14126:     if (($mailing eq 'helpdesk') && ($lastresort ne '')) {
                   14127:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14128:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14129:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14130:             my %what = (
                   14131:                           perlvar => 1,
                   14132:                        );
                   14133:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14134:             if ($primary) {
                   14135:                 my $gotaddr;
                   14136:                 my ($result,$returnhash) =
                   14137:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14138:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14139:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14140:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14141:                         $gotaddr = 1;
                   14142:                     }
                   14143:                 }
                   14144:                 unless ($gotaddr) {
                   14145:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14146:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14147:                     unless ($uintdom eq $intdom) {
                   14148:                         my %domconfig =
                   14149:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14150:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14151:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14152:                                 my @contacts = ('adminemail','supportemail');
                   14153:                                 foreach my $item (@contacts) {
                   14154:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14155:                                         my $addr = $domconfig{'contacts'}{$item};
                   14156:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14157:                                             push(@recipients,$addr);
                   14158:                                         }
                   14159:                                     }
                   14160:                                 }
                   14161:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14162:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14163:                                 }
                   14164:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14165:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14166:                                     my @ok_bccs;
                   14167:                                     foreach my $bcc (@bccs) {
                   14168:                                         $bcc =~ s/^\s+//g;
                   14169:                                         $bcc =~ s/\s+$//g;
                   14170:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14171:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14172:                                                 push(@ok_bccs,$bcc);
                   14173:                                             }
                   14174:                                         }
                   14175:                                     }
                   14176:                                     if (@ok_bccs > 0) {
                   14177:                                         $allbcc = join(', ',@ok_bccs);
                   14178:                                     }
                   14179:                                 }
                   14180:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14181:                             }
                   14182:                         }
                   14183:                     }
                   14184:                 }
                   14185:             }
                   14186:         }
1.618     raeburn  14187:     }
1.688     raeburn  14188:     if (defined($defmail)) {
                   14189:         if ($defmail ne '') {
                   14190:             push(@recipients,$defmail);
                   14191:         }
1.618     raeburn  14192:     }
                   14193:     if ($otheremails) {
1.619     raeburn  14194:         my @others;
                   14195:         if ($otheremails =~ /,/) {
                   14196:             @others = split(/,/,$otheremails);
1.618     raeburn  14197:         } else {
1.619     raeburn  14198:             push(@others,$otheremails);
                   14199:         }
                   14200:         foreach my $addr (@others) {
                   14201:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14202:                 push(@recipients,$addr);
                   14203:             }
1.618     raeburn  14204:         }
                   14205:     }
1.1075.2.122  raeburn  14206:     if ($mailing eq 'helpdesk') {
                   14207:         if ((!@recipients) && ($lastresort ne '')) {
                   14208:             push(@recipients,$lastresort);
                   14209:         }
                   14210:     } elsif ($lastresort ne '') {
                   14211:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14212:             push(@recipients,$lastresort);
                   14213:         }
                   14214:     }
                   14215:     my $recipientlist = join(',',@recipients);
                   14216:     if (wantarray) {
                   14217:         return ($recipientlist,$allbcc,$addtext);
                   14218:     } else {
                   14219:         return $recipientlist;
                   14220:     }
1.618     raeburn  14221: }
                   14222: 
1.127     matthew  14223: ############################################################
                   14224: ############################################################
1.154     albertel 14225: 
1.655     raeburn  14226: =pod
                   14227: 
                   14228: =head1 Course Catalog Routines
                   14229: 
                   14230: =over 4
                   14231: 
                   14232: =item * &gather_categories()
                   14233: 
                   14234: Converts category definitions - keys of categories hash stored in  
                   14235: coursecategories in configuration.db on the primary library server in a 
                   14236: domain - to an array.  Also generates javascript and idx hash used to 
                   14237: generate Domain Coordinator interface for editing Course Categories.
                   14238: 
                   14239: Inputs:
1.663     raeburn  14240: 
1.655     raeburn  14241: categories (reference to hash of category definitions).
1.663     raeburn  14242: 
1.655     raeburn  14243: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14244:       categories and subcategories).
1.663     raeburn  14245: 
1.655     raeburn  14246: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14247:       editing Course Categories).
1.663     raeburn  14248: 
1.655     raeburn  14249: jsarray (reference to array of categories used to create Javascript arrays for
                   14250:          Domain Coordinator interface for editing Course Categories).
                   14251: 
                   14252: Returns: nothing
                   14253: 
                   14254: Side effects: populates cats, idx and jsarray. 
                   14255: 
                   14256: =cut
                   14257: 
                   14258: sub gather_categories {
                   14259:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14260:     my %counters;
                   14261:     my $num = 0;
                   14262:     foreach my $item (keys(%{$categories})) {
                   14263:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14264:         if ($container eq '' && $depth == 0) {
                   14265:             $cats->[$depth][$categories->{$item}] = $cat;
                   14266:         } else {
                   14267:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14268:         }
                   14269:         my ($escitem,$tail) = split(/:/,$item,2);
                   14270:         if ($counters{$tail} eq '') {
                   14271:             $counters{$tail} = $num;
                   14272:             $num ++;
                   14273:         }
                   14274:         if (ref($idx) eq 'HASH') {
                   14275:             $idx->{$item} = $counters{$tail};
                   14276:         }
                   14277:         if (ref($jsarray) eq 'ARRAY') {
                   14278:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14279:         }
                   14280:     }
                   14281:     return;
                   14282: }
                   14283: 
                   14284: =pod
                   14285: 
                   14286: =item * &extract_categories()
                   14287: 
                   14288: Used to generate breadcrumb trails for course categories.
                   14289: 
                   14290: Inputs:
1.663     raeburn  14291: 
1.655     raeburn  14292: categories (reference to hash of category definitions).
1.663     raeburn  14293: 
1.655     raeburn  14294: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14295:       categories and subcategories).
1.663     raeburn  14296: 
1.655     raeburn  14297: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14298: 
1.655     raeburn  14299: allitems (reference to hash - key is category key 
                   14300:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14301: 
1.655     raeburn  14302: idx (reference to hash of counters used in Domain Coordinator interface for
                   14303:       editing Course Categories).
1.663     raeburn  14304: 
1.655     raeburn  14305: jsarray (reference to array of categories used to create Javascript arrays for
                   14306:          Domain Coordinator interface for editing Course Categories).
                   14307: 
1.665     raeburn  14308: subcats (reference to hash of arrays containing all subcategories within each 
                   14309:          category, -recursive)
                   14310: 
1.655     raeburn  14311: Returns: nothing
                   14312: 
                   14313: Side effects: populates trails and allitems hash references.
                   14314: 
                   14315: =cut
                   14316: 
                   14317: sub extract_categories {
1.665     raeburn  14318:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  14319:     if (ref($categories) eq 'HASH') {
                   14320:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14321:         if (ref($cats->[0]) eq 'ARRAY') {
                   14322:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14323:                 my $name = $cats->[0][$i];
                   14324:                 my $item = &escape($name).'::0';
                   14325:                 my $trailstr;
                   14326:                 if ($name eq 'instcode') {
                   14327:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14328:                 } elsif ($name eq 'communities') {
                   14329:                     $trailstr = &mt('Communities');
1.655     raeburn  14330:                 } else {
                   14331:                     $trailstr = $name;
                   14332:                 }
                   14333:                 if ($allitems->{$item} eq '') {
                   14334:                     push(@{$trails},$trailstr);
                   14335:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14336:                 }
                   14337:                 my @parents = ($name);
                   14338:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14339:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14340:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14341:                         if (ref($subcats) eq 'HASH') {
                   14342:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14343:                         }
                   14344:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   14345:                     }
                   14346:                 } else {
                   14347:                     if (ref($subcats) eq 'HASH') {
                   14348:                         $subcats->{$item} = [];
1.655     raeburn  14349:                     }
                   14350:                 }
                   14351:             }
                   14352:         }
                   14353:     }
                   14354:     return;
                   14355: }
                   14356: 
                   14357: =pod
                   14358: 
1.1075.2.56  raeburn  14359: =item * &recurse_categories()
1.655     raeburn  14360: 
                   14361: Recursively used to generate breadcrumb trails for course categories.
                   14362: 
                   14363: Inputs:
1.663     raeburn  14364: 
1.655     raeburn  14365: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14366:       categories and subcategories).
1.663     raeburn  14367: 
1.655     raeburn  14368: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14369: 
                   14370: category (current course category, for which breadcrumb trail is being generated).
                   14371: 
                   14372: trails (reference to array of breadcrumb trails for each category).
                   14373: 
1.655     raeburn  14374: allitems (reference to hash - key is category key
                   14375:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14376: 
1.655     raeburn  14377: parents (array containing containers directories for current category, 
                   14378:          back to top level). 
                   14379: 
                   14380: Returns: nothing
                   14381: 
                   14382: Side effects: populates trails and allitems hash references
                   14383: 
                   14384: =cut
                   14385: 
                   14386: sub recurse_categories {
1.665     raeburn  14387:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  14388:     my $shallower = $depth - 1;
                   14389:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14390:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14391:             my $name = $cats->[$depth]{$category}[$k];
                   14392:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14393:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14394:             if ($allitems->{$item} eq '') {
                   14395:                 push(@{$trails},$trailstr);
                   14396:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14397:             }
                   14398:             my $deeper = $depth+1;
                   14399:             push(@{$parents},$category);
1.665     raeburn  14400:             if (ref($subcats) eq 'HASH') {
                   14401:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14402:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14403:                     my $higher;
                   14404:                     if ($j > 0) {
                   14405:                         $higher = &escape($parents->[$j]).':'.
                   14406:                                   &escape($parents->[$j-1]).':'.$j;
                   14407:                     } else {
                   14408:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14409:                     }
                   14410:                     push(@{$subcats->{$higher}},$subcat);
                   14411:                 }
                   14412:             }
                   14413:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14414:                                 $subcats);
1.655     raeburn  14415:             pop(@{$parents});
                   14416:         }
                   14417:     } else {
                   14418:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14419:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14420:         if ($allitems->{$item} eq '') {
                   14421:             push(@{$trails},$trailstr);
                   14422:             $allitems->{$item} = scalar(@{$trails})-1;
                   14423:         }
                   14424:     }
                   14425:     return;
                   14426: }
                   14427: 
1.663     raeburn  14428: =pod
                   14429: 
1.1075.2.56  raeburn  14430: =item * &assign_categories_table()
1.663     raeburn  14431: 
                   14432: Create a datatable for display of hierarchical categories in a domain,
                   14433: with checkboxes to allow a course to be categorized. 
                   14434: 
                   14435: Inputs:
                   14436: 
                   14437: cathash - reference to hash of categories defined for the domain (from
                   14438:           configuration.db)
                   14439: 
                   14440: currcat - scalar with an & separated list of categories assigned to a course. 
                   14441: 
1.919     raeburn  14442: type    - scalar contains course type (Course or Community).
                   14443: 
1.1075.2.117  raeburn  14444: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14445:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14446: 
1.663     raeburn  14447: Returns: $output (markup to be displayed) 
                   14448: 
                   14449: =cut
                   14450: 
                   14451: sub assign_categories_table {
1.1075.2.117  raeburn  14452:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  14453:     my $output;
                   14454:     if (ref($cathash) eq 'HASH') {
                   14455:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   14456:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   14457:         $maxdepth = scalar(@cats);
                   14458:         if (@cats > 0) {
                   14459:             my $itemcount = 0;
                   14460:             if (ref($cats[0]) eq 'ARRAY') {
                   14461:                 my @currcategories;
                   14462:                 if ($currcat ne '') {
                   14463:                     @currcategories = split('&',$currcat);
                   14464:                 }
1.919     raeburn  14465:                 my $table;
1.663     raeburn  14466:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14467:                     my $parent = $cats[0][$i];
1.919     raeburn  14468:                     next if ($parent eq 'instcode');
                   14469:                     if ($type eq 'Community') {
                   14470:                         next unless ($parent eq 'communities');
                   14471:                     } else {
                   14472:                         next if ($parent eq 'communities');
                   14473:                     }
1.663     raeburn  14474:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14475:                     my $item = &escape($parent).'::0';
                   14476:                     my $checked = '';
                   14477:                     if (@currcategories > 0) {
                   14478:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14479:                             $checked = ' checked="checked"';
1.663     raeburn  14480:                         }
                   14481:                     }
1.919     raeburn  14482:                     my $parent_title = $parent;
                   14483:                     if ($parent eq 'communities') {
                   14484:                         $parent_title = &mt('Communities');
                   14485:                     }
                   14486:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14487:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14488:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  14489:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14490:                     my $depth = 1;
                   14491:                     push(@path,$parent);
1.1075.2.117  raeburn  14492:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  14493:                     pop(@path);
1.919     raeburn  14494:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14495:                     $itemcount ++;
                   14496:                 }
1.919     raeburn  14497:                 if ($itemcount) {
                   14498:                     $output = &Apache::loncommon::start_data_table().
                   14499:                               $table.
                   14500:                               &Apache::loncommon::end_data_table();
                   14501:                 }
1.663     raeburn  14502:             }
                   14503:         }
                   14504:     }
                   14505:     return $output;
                   14506: }
                   14507: 
                   14508: =pod
                   14509: 
1.1075.2.56  raeburn  14510: =item * &assign_category_rows()
1.663     raeburn  14511: 
                   14512: Create a datatable row for display of nested categories in a domain,
                   14513: with checkboxes to allow a course to be categorized,called recursively.
                   14514: 
                   14515: Inputs:
                   14516: 
                   14517: itemcount - track row number for alternating colors
                   14518: 
                   14519: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14520:       categories and subcategories.
                   14521: 
                   14522: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14523: 
                   14524: parent - parent of current category item
                   14525: 
                   14526: path - Array containing all categories back up through the hierarchy from the
                   14527:        current category to the top level.
                   14528: 
                   14529: currcategories - reference to array of current categories assigned to the course
                   14530: 
1.1075.2.117  raeburn  14531: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14532:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14533: 
1.663     raeburn  14534: Returns: $output (markup to be displayed).
                   14535: 
                   14536: =cut
                   14537: 
                   14538: sub assign_category_rows {
1.1075.2.117  raeburn  14539:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  14540:     my ($text,$name,$item,$chgstr);
                   14541:     if (ref($cats) eq 'ARRAY') {
                   14542:         my $maxdepth = scalar(@{$cats});
                   14543:         if (ref($cats->[$depth]) eq 'HASH') {
                   14544:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14545:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14546:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  14547:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14548:                 for (my $j=0; $j<$numchildren; $j++) {
                   14549:                     $name = $cats->[$depth]{$parent}[$j];
                   14550:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14551:                     my $deeper = $depth+1;
                   14552:                     my $checked = '';
                   14553:                     if (ref($currcategories) eq 'ARRAY') {
                   14554:                         if (@{$currcategories} > 0) {
                   14555:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14556:                                 $checked = ' checked="checked"';
1.663     raeburn  14557:                             }
                   14558:                         }
                   14559:                     }
1.664     raeburn  14560:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14561:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14562:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  14563:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14564:                              '</td><td>';
1.663     raeburn  14565:                     if (ref($path) eq 'ARRAY') {
                   14566:                         push(@{$path},$name);
1.1075.2.117  raeburn  14567:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  14568:                         pop(@{$path});
                   14569:                     }
                   14570:                     $text .= '</td></tr>';
                   14571:                 }
                   14572:                 $text .= '</table></td>';
                   14573:             }
                   14574:         }
                   14575:     }
                   14576:     return $text;
                   14577: }
                   14578: 
1.1075.2.69  raeburn  14579: =pod
                   14580: 
                   14581: =back
                   14582: 
                   14583: =cut
                   14584: 
1.655     raeburn  14585: ############################################################
                   14586: ############################################################
                   14587: 
                   14588: 
1.443     albertel 14589: sub commit_customrole {
1.664     raeburn  14590:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14591:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14592:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14593:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14594:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14595:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14596:                  '</b><br />';
                   14597:     return $output;
                   14598: }
                   14599: 
                   14600: sub commit_standardrole {
1.1075.2.31  raeburn  14601:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14602:     my ($output,$logmsg,$linefeed);
                   14603:     if ($context eq 'auto') {
                   14604:         $linefeed = "\n";
                   14605:     } else {
                   14606:         $linefeed = "<br />\n";
                   14607:     }  
1.443     albertel 14608:     if ($three eq 'st') {
1.541     raeburn  14609:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  14610:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14611:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14612:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14613:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14614:         } else {
1.541     raeburn  14615:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14616:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14617:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14618:             if ($context eq 'auto') {
                   14619:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14620:             } else {
                   14621:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14622:                &mt('Add to classlist').': <b>ok</b>';
                   14623:             }
                   14624:             $output .= $linefeed;
1.443     albertel 14625:         }
                   14626:     } else {
                   14627:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14628:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14629:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14630:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14631:         if ($context eq 'auto') {
                   14632:             $output .= $result.$linefeed;
                   14633:         } else {
                   14634:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14635:         }
1.443     albertel 14636:     }
                   14637:     return $output;
                   14638: }
                   14639: 
                   14640: sub commit_studentrole {
1.1075.2.31  raeburn  14641:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14642:         $credits) = @_;
1.626     raeburn  14643:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14644:     if ($context eq 'auto') {
                   14645:         $linefeed = "\n";
                   14646:     } else {
                   14647:         $linefeed = '<br />'."\n";
                   14648:     }
1.443     albertel 14649:     if (defined($one) && defined($two)) {
                   14650:         my $cid=$one.'_'.$two;
                   14651:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14652:         my $secchange = 0;
                   14653:         my $expire_role_result;
                   14654:         my $modify_section_result;
1.628     raeburn  14655:         if ($oldsec ne '-1') { 
                   14656:             if ($oldsec ne $sec) {
1.443     albertel 14657:                 $secchange = 1;
1.628     raeburn  14658:                 my $now = time;
1.443     albertel 14659:                 my $uurl='/'.$cid;
                   14660:                 $uurl=~s/\_/\//g;
                   14661:                 if ($oldsec) {
                   14662:                     $uurl.='/'.$oldsec;
                   14663:                 }
1.626     raeburn  14664:                 $oldsecurl = $uurl;
1.628     raeburn  14665:                 $expire_role_result = 
1.652     raeburn  14666:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14667:                 if ($env{'request.course.sec'} ne '') { 
                   14668:                     if ($expire_role_result eq 'refused') {
                   14669:                         my @roles = ('st');
                   14670:                         my @statuses = ('previous');
                   14671:                         my @roledoms = ($one);
                   14672:                         my $withsec = 1;
                   14673:                         my %roleshash = 
                   14674:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14675:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14676:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14677:                             my ($oldstart,$oldend) = 
                   14678:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14679:                             if ($oldend > 0 && $oldend <= $now) {
                   14680:                                 $expire_role_result = 'ok';
                   14681:                             }
                   14682:                         }
                   14683:                     }
                   14684:                 }
1.443     albertel 14685:                 $result = $expire_role_result;
                   14686:             }
                   14687:         }
                   14688:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  14689:             $modify_section_result = 
                   14690:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14691:                                                            undef,undef,undef,$sec,
                   14692:                                                            $end,$start,'','',$cid,
                   14693:                                                            '',$context,$credits);
1.443     albertel 14694:             if ($modify_section_result =~ /^ok/) {
                   14695:                 if ($secchange == 1) {
1.628     raeburn  14696:                     if ($sec eq '') {
                   14697:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   14698:                     } else {
                   14699:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14700:                     }
1.443     albertel 14701:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14702:                     if ($sec eq '') {
                   14703:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14704:                     } else {
                   14705:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14706:                     }
1.443     albertel 14707:                 } else {
1.628     raeburn  14708:                     if ($sec eq '') {
                   14709:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14710:                     } else {
                   14711:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14712:                     }
1.443     albertel 14713:                 }
                   14714:             } else {
1.628     raeburn  14715:                 if ($secchange) {       
                   14716:                     $$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;
                   14717:                 } else {
                   14718:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14719:                 }
1.443     albertel 14720:             }
                   14721:             $result = $modify_section_result;
                   14722:         } elsif ($secchange == 1) {
1.628     raeburn  14723:             if ($oldsec eq '') {
1.1075.2.20  raeburn  14724:                 $$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  14725:             } else {
                   14726:                 $$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;
                   14727:             }
1.626     raeburn  14728:             if ($expire_role_result eq 'refused') {
                   14729:                 my $newsecurl = '/'.$cid;
                   14730:                 $newsecurl =~ s/\_/\//g;
                   14731:                 if ($sec ne '') {
                   14732:                     $newsecurl.='/'.$sec;
                   14733:                 }
                   14734:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14735:                     if ($sec eq '') {
                   14736:                         $$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;
                   14737:                     } else {
                   14738:                         $$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;
                   14739:                     }
                   14740:                 }
                   14741:             }
1.443     albertel 14742:         }
                   14743:     } else {
1.626     raeburn  14744:         $$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 14745:         $result = "error: incomplete course id\n";
                   14746:     }
                   14747:     return $result;
                   14748: }
                   14749: 
1.1075.2.25  raeburn  14750: sub show_role_extent {
                   14751:     my ($scope,$context,$role) = @_;
                   14752:     $scope =~ s{^/}{};
                   14753:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14754:     push(@courseroles,'co');
                   14755:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14756:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14757:         $scope =~ s{/}{_};
                   14758:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14759:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14760:         my ($audom,$auname) = split(/\//,$scope);
                   14761:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14762:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14763:     } else {
                   14764:         $scope =~ s{/$}{};
                   14765:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14766:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14767:     }
                   14768: }
                   14769: 
1.443     albertel 14770: ############################################################
                   14771: ############################################################
                   14772: 
1.566     albertel 14773: sub check_clone {
1.578     raeburn  14774:     my ($args,$linefeed) = @_;
1.566     albertel 14775:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14776:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14777:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14778:     my $clonemsg;
                   14779:     my $can_clone = 0;
1.944     raeburn  14780:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14781:     if ($lctype ne 'community') {
                   14782:         $lctype = 'course';
                   14783:     }
1.566     albertel 14784:     if ($clonehome eq 'no_host') {
1.944     raeburn  14785:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14786:             $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'});
                   14787:         } else {
                   14788:             $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'});
                   14789:         }     
1.566     albertel 14790:     } else {
                   14791: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14792:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14793:             if ($clonedesc{'type'} ne 'Community') {
                   14794:                  $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'});
                   14795:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14796:             }
                   14797:         }
1.1075.2.119  raeburn  14798: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  14799:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14800: 	    $can_clone = 1;
                   14801: 	} else {
1.1075.2.95  raeburn  14802: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 14803: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  14804:             if ($clonehash{'cloners'} eq '') {
                   14805:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   14806:                 if ($domdefs{'canclone'}) {
                   14807:                     unless ($domdefs{'canclone'} eq 'none') {
                   14808:                         if ($domdefs{'canclone'} eq 'domain') {
                   14809:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   14810:                                 $can_clone = 1;
                   14811:                             }
                   14812:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   14813:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   14814:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   14815:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   14816:                                 $can_clone = 1;
                   14817:                             }
                   14818:                         }
                   14819:                     }
1.908     raeburn  14820:                 }
1.1075.2.95  raeburn  14821:             } else {
                   14822: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   14823:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  14824:                     $can_clone = 1;
1.1075.2.95  raeburn  14825:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  14826:                     $can_clone = 1;
1.1075.2.96  raeburn  14827:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14828:                     $can_clone = 1;
1.1075.2.95  raeburn  14829:                 }
                   14830:                 unless ($can_clone) {
1.1075.2.96  raeburn  14831:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   14832:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  14833:                         my (%gotdomdefaults,%gotcodedefaults);
                   14834:                         foreach my $cloner (@cloners) {
                   14835:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   14836:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   14837:                                 my (%codedefaults,@code_order);
                   14838:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   14839:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   14840:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   14841:                                     }
                   14842:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   14843:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   14844:                                     }
                   14845:                                 } else {
                   14846:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   14847:                                                                             \%codedefaults,
                   14848:                                                                             \@code_order);
                   14849:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   14850:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   14851:                                 }
                   14852:                                 if (@code_order > 0) {
                   14853:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   14854:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   14855:                                                                                 $args->{'crscode'})) {
                   14856:                                         $can_clone = 1;
                   14857:                                         last;
                   14858:                                     }
                   14859:                                 }
                   14860:                             }
                   14861:                         }
                   14862:                     }
1.1075.2.96  raeburn  14863:                 }
                   14864:             }
                   14865:             unless ($can_clone) {
                   14866:                 my $ccrole = 'cc';
                   14867:                 if ($args->{'crstype'} eq 'Community') {
                   14868:                     $ccrole = 'co';
                   14869:                 }
                   14870:                 my %roleshash =
                   14871:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14872:                                                   $args->{'ccdomain'},
                   14873:                                                   'userroles',['active'],[$ccrole],
                   14874:                                                   [$args->{'clonedomain'}]);
                   14875:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   14876:                     $can_clone = 1;
                   14877:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   14878:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   14879:                     $can_clone = 1;
1.1075.2.95  raeburn  14880:                 }
                   14881:             }
                   14882:             unless ($can_clone) {
                   14883:                 if ($args->{'crstype'} eq 'Community') {
                   14884:                     $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'});
                   14885:                 } else {
                   14886:                     $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
1.578     raeburn  14887: 	        }
1.566     albertel 14888: 	    }
1.578     raeburn  14889:         }
1.566     albertel 14890:     }
                   14891:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14892: }
                   14893: 
1.444     albertel 14894: sub construct_course {
1.1075.2.119  raeburn  14895:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   14896:         $cnum,$category,$coderef) = @_;
1.444     albertel 14897:     my $outcome;
1.541     raeburn  14898:     my $linefeed =  '<br />'."\n";
                   14899:     if ($context eq 'auto') {
                   14900:         $linefeed = "\n";
                   14901:     }
1.566     albertel 14902: 
                   14903: #
                   14904: # Are we cloning?
                   14905: #
                   14906:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14907:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14908: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14909: 	if ($context ne 'auto') {
1.578     raeburn  14910:             if ($clonemsg ne '') {
                   14911: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14912:             }
1.566     albertel 14913: 	}
                   14914: 	$outcome .= $clonemsg.$linefeed;
                   14915: 
                   14916:         if (!$can_clone) {
                   14917: 	    return (0,$outcome);
                   14918: 	}
                   14919:     }
                   14920: 
1.444     albertel 14921: #
                   14922: # Open course
                   14923: #
                   14924:     my $crstype = lc($args->{'crstype'});
                   14925:     my %cenv=();
                   14926:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14927:                                              $args->{'cdescr'},
                   14928:                                              $args->{'curl'},
                   14929:                                              $args->{'course_home'},
                   14930:                                              $args->{'nonstandard'},
                   14931:                                              $args->{'crscode'},
                   14932:                                              $args->{'ccuname'}.':'.
                   14933:                                              $args->{'ccdomain'},
1.882     raeburn  14934:                                              $args->{'crstype'},
1.885     raeburn  14935:                                              $cnum,$context,$category);
1.444     albertel 14936: 
                   14937:     # Note: The testing routines depend on this being output; see 
                   14938:     # Utils::Course. This needs to at least be output as a comment
                   14939:     # if anyone ever decides to not show this, and Utils::Course::new
                   14940:     # will need to be suitably modified.
1.541     raeburn  14941:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  14942:     if ($$courseid =~ /^error:/) {
                   14943:         return (0,$outcome);
                   14944:     }
                   14945: 
1.444     albertel 14946: #
                   14947: # Check if created correctly
                   14948: #
1.479     albertel 14949:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14950:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14951:     if ($crsuhome eq 'no_host') {
                   14952:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14953:         return (0,$outcome);
                   14954:     }
1.541     raeburn  14955:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14956: 
1.444     albertel 14957: #
1.566     albertel 14958: # Do the cloning
                   14959: #   
                   14960:     if ($can_clone && $cloneid) {
                   14961: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   14962: 	if ($context ne 'auto') {
                   14963: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   14964: 	}
                   14965: 	$outcome .= $clonemsg.$linefeed;
                   14966: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 14967: # Copy all files
1.637     www      14968: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 14969: # Restore URL
1.566     albertel 14970: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 14971: # Restore title
1.566     albertel 14972: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  14973: # Restore creation date, creator and creation context.
                   14974:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   14975:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   14976:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 14977: # Mark as cloned
1.566     albertel 14978: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      14979: # Need to clone grading mode
                   14980:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   14981:         $cenv{'grading'}=$newenv{'grading'};
                   14982: # Do not clone these environment entries
                   14983:         &Apache::lonnet::del('environment',
                   14984:                   ['default_enrollment_start_date',
                   14985:                    'default_enrollment_end_date',
                   14986:                    'question.email',
                   14987:                    'policy.email',
                   14988:                    'comment.email',
                   14989:                    'pch.users.denied',
1.725     raeburn  14990:                    'plc.users.denied',
                   14991:                    'hidefromcat',
1.1075.2.36  raeburn  14992:                    'checkforpriv',
1.1075.2.59  raeburn  14993:                    'categories',
                   14994:                    'internal.uniquecode'],
1.638     www      14995:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  14996:         if ($args->{'textbook'}) {
                   14997:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14998:         }
1.444     albertel 14999:     }
1.566     albertel 15000: 
1.444     albertel 15001: #
                   15002: # Set environment (will override cloned, if existing)
                   15003: #
                   15004:     my @sections = ();
                   15005:     my @xlists = ();
                   15006:     if ($args->{'crstype'}) {
                   15007:         $cenv{'type'}=$args->{'crstype'};
                   15008:     }
                   15009:     if ($args->{'crsid'}) {
                   15010:         $cenv{'courseid'}=$args->{'crsid'};
                   15011:     }
                   15012:     if ($args->{'crscode'}) {
                   15013:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15014:     }
                   15015:     if ($args->{'crsquota'} ne '') {
                   15016:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15017:     } else {
                   15018:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15019:     }
                   15020:     if ($args->{'ccuname'}) {
                   15021:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15022:                                         ':'.$args->{'ccdomain'};
                   15023:     } else {
                   15024:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15025:     }
1.1075.2.31  raeburn  15026:     if ($args->{'defaultcredits'}) {
                   15027:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15028:     }
1.444     albertel 15029:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15030:     if ($args->{'crssections'}) {
                   15031:         $cenv{'internal.sectionnums'} = '';
                   15032:         if ($args->{'crssections'} =~ m/,/) {
                   15033:             @sections = split/,/,$args->{'crssections'};
                   15034:         } else {
                   15035:             $sections[0] = $args->{'crssections'};
                   15036:         }
                   15037:         if (@sections > 0) {
                   15038:             foreach my $item (@sections) {
                   15039:                 my ($sec,$gp) = split/:/,$item;
                   15040:                 my $class = $args->{'crscode'}.$sec;
                   15041:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15042:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15043:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15044:                     push(@badclasses,$class);
1.444     albertel 15045:                 }
                   15046:             }
                   15047:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15048:         }
                   15049:     }
                   15050: # do not hide course coordinator from staff listing, 
                   15051: # even if privileged
                   15052:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  15053: # add course coordinator's domain to domains to check for privileged users
                   15054: # if different to course domain
                   15055:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15056:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15057:     }
1.444     albertel 15058: # add crosslistings
                   15059:     if ($args->{'crsxlist'}) {
                   15060:         $cenv{'internal.crosslistings'}='';
                   15061:         if ($args->{'crsxlist'} =~ m/,/) {
                   15062:             @xlists = split/,/,$args->{'crsxlist'};
                   15063:         } else {
                   15064:             $xlists[0] = $args->{'crsxlist'};
                   15065:         }
                   15066:         if (@xlists > 0) {
                   15067:             foreach my $item (@xlists) {
                   15068:                 my ($xl,$gp) = split/:/,$item;
                   15069:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15070:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15071:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15072:                     push(@badclasses,$xl);
1.444     albertel 15073:                 }
                   15074:             }
                   15075:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15076:         }
                   15077:     }
                   15078:     if ($args->{'autoadds'}) {
                   15079:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15080:     }
                   15081:     if ($args->{'autodrops'}) {
                   15082:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15083:     }
                   15084: # check for notification of enrollment changes
                   15085:     my @notified = ();
                   15086:     if ($args->{'notify_owner'}) {
                   15087:         if ($args->{'ccuname'} ne '') {
                   15088:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15089:         }
                   15090:     }
                   15091:     if ($args->{'notify_dc'}) {
                   15092:         if ($uname ne '') { 
1.630     raeburn  15093:             push(@notified,$uname.':'.$udom);
1.444     albertel 15094:         }
                   15095:     }
                   15096:     if (@notified > 0) {
                   15097:         my $notifylist;
                   15098:         if (@notified > 1) {
                   15099:             $notifylist = join(',',@notified);
                   15100:         } else {
                   15101:             $notifylist = $notified[0];
                   15102:         }
                   15103:         $cenv{'internal.notifylist'} = $notifylist;
                   15104:     }
                   15105:     if (@badclasses > 0) {
                   15106:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  15107:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15108:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15109:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15110:         );
1.1075.2.119  raeburn  15111:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15112:                            &mt('That is because the user identified as the course owner ([_1]) does not have rights to access enrollment in these classes, as determined by the policies of your institution on access to official classlists',$cenv{'internal.courseowner'}).$linefeed.$lt{'itis'};
1.541     raeburn  15113:         if ($context eq 'auto') {
                   15114:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  15115:         } else {
1.566     albertel 15116:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  15117:         }
                   15118:         foreach my $item (@badclasses) {
1.541     raeburn  15119:             if ($context eq 'auto') {
1.1075.2.119  raeburn  15120:                 $outcome .= " - $item\n";
1.541     raeburn  15121:             } else {
1.1075.2.119  raeburn  15122:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15123:             }
1.1075.2.119  raeburn  15124:         }
                   15125:         if ($context eq 'auto') {
                   15126:             $outcome .= $linefeed;
                   15127:         } else {
                   15128:             $outcome .= "</ul><br /><br /></div>\n";
                   15129:         }
1.444     albertel 15130:     }
                   15131:     if ($args->{'no_end_date'}) {
                   15132:         $args->{'endaccess'} = 0;
                   15133:     }
                   15134:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15135:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15136:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15137:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15138:     if ($args->{'showphotos'}) {
                   15139:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15140:     }
                   15141:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15142:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15143:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15144:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15145:             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'); 
                   15146:             if ($context eq 'auto') {
                   15147:                 $outcome .= $krb_msg;
                   15148:             } else {
1.566     albertel 15149:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15150:             }
                   15151:             $outcome .= $linefeed;
1.444     albertel 15152:         }
                   15153:     }
                   15154:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15155:        if ($args->{'setpolicy'}) {
                   15156:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15157:        }
                   15158:        if ($args->{'setcontent'}) {
                   15159:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15160:        }
1.1075.2.110  raeburn  15161:        if ($args->{'setcomment'}) {
                   15162:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15163:        }
1.444     albertel 15164:     }
                   15165:     if ($args->{'reshome'}) {
                   15166: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15167: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15168:     }
                   15169: #
                   15170: # course has keyed access
                   15171: #
                   15172:     if ($args->{'setkeys'}) {
                   15173:        $cenv{'keyaccess'}='yes';
                   15174:     }
                   15175: # if specified, key authority is not course, but user
                   15176: # only active if keyaccess is yes
                   15177:     if ($args->{'keyauth'}) {
1.487     albertel 15178: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15179: 	$user = &LONCAPA::clean_username($user);
                   15180: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15181: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15182: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15183: 	}
                   15184:     }
                   15185: 
1.1075.2.59  raeburn  15186: #
                   15187: #  generate and store uniquecode (available to course requester), if course should have one.
                   15188: #
                   15189:     if ($args->{'uniquecode'}) {
                   15190:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15191:         if ($code) {
                   15192:             $cenv{'internal.uniquecode'} = $code;
                   15193:             my %crsinfo =
                   15194:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15195:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15196:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15197:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15198:             }
                   15199:             if (ref($coderef)) {
                   15200:                 $$coderef = $code;
                   15201:             }
                   15202:         }
                   15203:     }
                   15204: 
1.444     albertel 15205:     if ($args->{'disresdis'}) {
                   15206:         $cenv{'pch.roles.denied'}='st';
                   15207:     }
                   15208:     if ($args->{'disablechat'}) {
                   15209:         $cenv{'plc.roles.denied'}='st';
                   15210:     }
                   15211: 
                   15212:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15213:     # course
                   15214:     $cenv{'course.helper.not.run'} = 1;
                   15215:     #
                   15216:     # Use new Randomseed
                   15217:     #
                   15218:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15219:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15220:     #
                   15221:     # The encryption code and receipt prefix for this course
                   15222:     #
                   15223:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15224:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15225:     #
                   15226:     # By default, use standard grading
                   15227:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15228: 
1.541     raeburn  15229:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15230:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15231: #
                   15232: # Open all assignments
                   15233: #
                   15234:     if ($args->{'openall'}) {
                   15235:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   15236:        my %storecontent = ($storeunder         => time,
                   15237:                            $storeunder.'.type' => 'date_start');
                   15238:        
                   15239:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  15240:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15241:    }
                   15242: #
                   15243: # Set first page
                   15244: #
                   15245:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15246: 	    || ($cloneid)) {
1.445     albertel 15247: 	use LONCAPA::map;
1.444     albertel 15248: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15249: 
                   15250: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15251:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15252: 
1.444     albertel 15253:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15254:         my $title; my $url;
                   15255:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15256: 	    $title=&mt('Syllabus');
1.444     albertel 15257:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15258:         } else {
1.963     raeburn  15259:             $title=&mt('Table of Contents');
1.444     albertel 15260:             $url='/adm/navmaps';
                   15261:         }
1.445     albertel 15262: 
                   15263:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15264: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15265: 
                   15266: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15267:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15268:     }
1.566     albertel 15269: 
                   15270:     return (1,$outcome);
1.444     albertel 15271: }
                   15272: 
1.1075.2.59  raeburn  15273: sub make_unique_code {
                   15274:     my ($cdom,$cnum) = @_;
                   15275:     # get lock on uniquecodes db
                   15276:     my $lockhash = {
                   15277:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15278:                                                   ':'.$env{'user.domain'},
                   15279:                    };
                   15280:     my $tries = 0;
                   15281:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15282:     my ($code,$error);
                   15283: 
                   15284:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15285:         $tries ++;
                   15286:         sleep 1;
                   15287:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15288:     }
                   15289:     if ($gotlock eq 'ok') {
                   15290:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15291:         my $gotcode;
                   15292:         my $attempts = 0;
                   15293:         while ((!$gotcode) && ($attempts < 100)) {
                   15294:             $code = &generate_code();
                   15295:             if (!exists($currcodes{$code})) {
                   15296:                 $gotcode = 1;
                   15297:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15298:                     $error = 'nostore';
                   15299:                 }
                   15300:             }
                   15301:             $attempts ++;
                   15302:         }
                   15303:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15304:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15305:     } else {
                   15306:         $error = 'nolock';
                   15307:     }
                   15308:     return ($code,$error);
                   15309: }
                   15310: 
                   15311: sub generate_code {
                   15312:     my $code;
                   15313:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15314:     for (my $i=0; $i<6; $i++) {
                   15315:         my $lettnum = int (rand 2);
                   15316:         my $item = '';
                   15317:         if ($lettnum) {
                   15318:             $item = $letts[int( rand(18) )];
                   15319:         } else {
                   15320:             $item = 1+int( rand(8) );
                   15321:         }
                   15322:         $code .= $item;
                   15323:     }
                   15324:     return $code;
                   15325: }
                   15326: 
1.444     albertel 15327: ############################################################
                   15328: ############################################################
                   15329: 
1.953     droeschl 15330: #SD
                   15331: # only Community and Course, or anything else?
1.378     raeburn  15332: sub course_type {
                   15333:     my ($cid) = @_;
                   15334:     if (!defined($cid)) {
                   15335:         $cid = $env{'request.course.id'};
                   15336:     }
1.404     albertel 15337:     if (defined($env{'course.'.$cid.'.type'})) {
                   15338:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15339:     } else {
                   15340:         return 'Course';
1.377     raeburn  15341:     }
                   15342: }
1.156     albertel 15343: 
1.406     raeburn  15344: sub group_term {
                   15345:     my $crstype = &course_type();
                   15346:     my %names = (
                   15347:                   'Course' => 'group',
1.865     raeburn  15348:                   'Community' => 'group',
1.406     raeburn  15349:                 );
                   15350:     return $names{$crstype};
                   15351: }
                   15352: 
1.902     raeburn  15353: sub course_types {
1.1075.2.59  raeburn  15354:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  15355:     my %typename = (
                   15356:                          official   => 'Official course',
                   15357:                          unofficial => 'Unofficial course',
                   15358:                          community  => 'Community',
1.1075.2.59  raeburn  15359:                          textbook   => 'Textbook course',
1.902     raeburn  15360:                    );
                   15361:     return (\@types,\%typename);
                   15362: }
                   15363: 
1.156     albertel 15364: sub icon {
                   15365:     my ($file)=@_;
1.505     albertel 15366:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15367:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15368:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15369:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15370: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15371: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15372: 	            $curfext.".gif") {
                   15373: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15374: 		$curfext.".gif";
                   15375: 	}
                   15376:     }
1.249     albertel 15377:     return &lonhttpdurl($iconname);
1.154     albertel 15378: } 
1.84      albertel 15379: 
1.575     albertel 15380: sub lonhttpdurl {
1.692     www      15381: #
                   15382: # Had been used for "small fry" static images on separate port 8080.
                   15383: # Modify here if lightweight http functionality desired again.
                   15384: # Currently eliminated due to increasing firewall issues.
                   15385: #
1.575     albertel 15386:     my ($url)=@_;
1.692     www      15387:     return $url;
1.215     albertel 15388: }
                   15389: 
1.213     albertel 15390: sub connection_aborted {
                   15391:     my ($r)=@_;
                   15392:     $r->print(" ");$r->rflush();
                   15393:     my $c = $r->connection;
                   15394:     return $c->aborted();
                   15395: }
                   15396: 
1.221     foxr     15397: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15398: #    strings as 'strings'.
                   15399: sub escape_single {
1.221     foxr     15400:     my ($input) = @_;
1.223     albertel 15401:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15402:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15403:     return $input;
                   15404: }
1.223     albertel 15405: 
1.222     foxr     15406: #  Same as escape_single, but escape's "'s  This 
                   15407: #  can be used for  "strings"
                   15408: sub escape_double {
                   15409:     my ($input) = @_;
                   15410:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15411:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15412:     return $input;
                   15413: }
1.223     albertel 15414:  
1.222     foxr     15415: #   Escapes the last element of a full URL.
                   15416: sub escape_url {
                   15417:     my ($url)   = @_;
1.238     raeburn  15418:     my @urlslices = split(/\//, $url,-1);
1.369     www      15419:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  15420:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15421: }
1.462     albertel 15422: 
1.820     raeburn  15423: sub compare_arrays {
                   15424:     my ($arrayref1,$arrayref2) = @_;
                   15425:     my (@difference,%count);
                   15426:     @difference = ();
                   15427:     %count = ();
                   15428:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15429:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15430:         foreach my $element (keys(%count)) {
                   15431:             if ($count{$element} == 1) {
                   15432:                 push(@difference,$element);
                   15433:             }
                   15434:         }
                   15435:     }
                   15436:     return @difference;
                   15437: }
                   15438: 
1.817     bisitz   15439: # -------------------------------------------------------- Initialize user login
1.462     albertel 15440: sub init_user_environment {
1.463     albertel 15441:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15442:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15443: 
                   15444:     my $public=($username eq 'public' && $domain eq 'public');
                   15445: 
                   15446: # See if old ID present, if so, remove
                   15447: 
1.1062    raeburn  15448:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15449:     my $now=time;
                   15450: 
                   15451:     if ($public) {
                   15452: 	my $max_public=100;
                   15453: 	my $oldest;
                   15454: 	my $oldest_time=0;
                   15455: 	for(my $next=1;$next<=$max_public;$next++) {
                   15456: 	    if (-e $lonids."/publicuser_$next.id") {
                   15457: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15458: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15459: 		    $oldest_time=$mtime;
                   15460: 		    $oldest=$next;
                   15461: 		}
                   15462: 	    } else {
                   15463: 		$cookie="publicuser_$next";
                   15464: 		last;
                   15465: 	    }
                   15466: 	}
                   15467: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15468:     } else {
1.463     albertel 15469: 	# if this isn't a robot, kill any existing non-robot sessions
                   15470: 	if (!$args->{'robot'}) {
                   15471: 	    opendir(DIR,$lonids);
                   15472: 	    while ($filename=readdir(DIR)) {
                   15473: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   15474: 		    unlink($lonids.'/'.$filename);
                   15475: 		}
1.462     albertel 15476: 	    }
1.463     albertel 15477: 	    closedir(DIR);
1.1075.2.84  raeburn  15478: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15479:             my $namespace = 'nohist_courseeditor';
                   15480:             my $lockingkey = 'paste'."\0".'locked_num';
                   15481:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15482:                                                 $domain,$username);
                   15483:             if (exists($lockhash{$lockingkey})) {
                   15484:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15485:                 unless ($delresult eq 'ok') {
                   15486:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15487:                 }
                   15488:             }
1.462     albertel 15489: 	}
                   15490: # Give them a new cookie
1.463     albertel 15491: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15492: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15493: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15494:     
                   15495: # Initialize roles
                   15496: 
1.1062    raeburn  15497: 	($userroles,$firstaccenv,$timerintenv) = 
                   15498:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15499:     }
                   15500: # ------------------------------------ Check browser type and MathML capability
                   15501: 
1.1075.2.77  raeburn  15502:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15503:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15504: 
                   15505: # ------------------------------------------------------------- Get environment
                   15506: 
                   15507:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15508:     my ($tmp) = keys(%userenv);
                   15509:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15510:     } else {
                   15511: 	undef(%userenv);
                   15512:     }
                   15513:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15514: 	$form->{'interface'}=$userenv{'interface'};
                   15515:     }
                   15516:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15517: 
                   15518: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15519:     foreach my $option ('interface','localpath','localres') {
                   15520:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15521:     }
                   15522: # --------------------------------------------------------- Write first profile
                   15523: 
                   15524:     {
                   15525: 	my %initial_env = 
                   15526: 	    ("user.name"          => $username,
                   15527: 	     "user.domain"        => $domain,
                   15528: 	     "user.home"          => $authhost,
                   15529: 	     "browser.type"       => $clientbrowser,
                   15530: 	     "browser.version"    => $clientversion,
                   15531: 	     "browser.mathml"     => $clientmathml,
                   15532: 	     "browser.unicode"    => $clientunicode,
                   15533: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  15534:              "browser.mobile"     => $clientmobile,
                   15535:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  15536:              "browser.osversion"  => $clientosversion,
1.462     albertel 15537: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15538: 	     "request.course.fn"  => '',
                   15539: 	     "request.course.uri" => '',
                   15540: 	     "request.course.sec" => '',
                   15541: 	     "request.role"       => 'cm',
                   15542: 	     "request.role.adv"   => $env{'user.adv'},
                   15543: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15544: 
                   15545:         if ($form->{'localpath'}) {
                   15546: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15547: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15548:         }
                   15549: 	
                   15550: 	if ($form->{'interface'}) {
                   15551: 	    $form->{'interface'}=~s/\W//gs;
                   15552: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15553: 	    $env{'browser.interface'}=$form->{'interface'};
                   15554: 	}
                   15555: 
1.1075.2.54  raeburn  15556:         if ($form->{'iptoken'}) {
                   15557:             my $lonhost = $r->dir_config('lonHostID');
                   15558:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15559:             $env{'user.noloadbalance'} = $lonhost;
                   15560:         }
                   15561: 
1.1075.2.120  raeburn  15562:         if ($form->{'noloadbalance'}) {
                   15563:             my @hosts = &Apache::lonnet::current_machine_ids();
                   15564:             my $hosthere = $form->{'noloadbalance'};
                   15565:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   15566:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   15567:                 $env{'user.noloadbalance'} = $hosthere;
                   15568:             }
                   15569:         }
                   15570: 
1.1016    raeburn  15571:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  15572:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   15573:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  15574: 
1.1075.2.125  raeburn  15575:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   15576:                 $userenv{'availabletools.'.$tool} = 
                   15577:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15578:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   15579:             }
1.724     raeburn  15580: 
1.1075.2.125  raeburn  15581:             foreach my $crstype ('official','unofficial','community','textbook') {
                   15582:                 $userenv{'canrequest.'.$crstype} =
                   15583:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   15584:                                                       'reload','requestcourses',
                   15585:                                                       \%userenv,\%domdef,\%is_adv);
                   15586:             }
1.765     raeburn  15587: 
1.1075.2.125  raeburn  15588:             $userenv{'canrequest.author'} =
                   15589:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15590:                                                   'reload','requestauthor',
                   15591:                                                   \%userenv,\%domdef,\%is_adv);
                   15592:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15593:                                                  $domain,$username);
                   15594:             my $reqstatus = $reqauthor{'author_status'};
                   15595:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   15596:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   15597:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15598:                                                       $reqauthor{'author'}{'timestamp'};
                   15599:                 }
1.1075.2.14  raeburn  15600:             }
                   15601:         }
                   15602: 
1.462     albertel 15603: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15604: 
1.462     albertel 15605: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15606: 		 &GDBM_WRCREAT(),0640)) {
                   15607: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15608: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15609: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15610:             if (ref($firstaccenv) eq 'HASH') {
                   15611:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15612:             }
                   15613:             if (ref($timerintenv) eq 'HASH') {
                   15614:                 &_add_to_env(\%disk_env,$timerintenv);
                   15615:             }
1.463     albertel 15616: 	    if (ref($args->{'extra_env'})) {
                   15617: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15618: 	    }
1.462     albertel 15619: 	    untie(%disk_env);
                   15620: 	} else {
1.705     tempelho 15621: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15622: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15623: 	    return 'error: '.$!;
                   15624: 	}
                   15625:     }
                   15626:     $env{'request.role'}='cm';
                   15627:     $env{'request.role.adv'}=$env{'user.adv'};
                   15628:     $env{'browser.type'}=$clientbrowser;
                   15629: 
                   15630:     return $cookie;
                   15631: 
                   15632: }
                   15633: 
                   15634: sub _add_to_env {
                   15635:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15636:     if (ref($env_data) eq 'HASH') {
                   15637:         while (my ($key,$value) = each(%$env_data)) {
                   15638: 	    $idf->{$prefix.$key} = $value;
                   15639: 	    $env{$prefix.$key}   = $value;
                   15640:         }
1.462     albertel 15641:     }
                   15642: }
                   15643: 
1.685     tempelho 15644: # --- Get the symbolic name of a problem and the url
                   15645: sub get_symb {
                   15646:     my ($request,$silent) = @_;
1.726     raeburn  15647:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15648:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15649:     if ($symb eq '') {
                   15650:         if (!$silent) {
1.1071    raeburn  15651:             if (ref($request)) { 
                   15652:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15653:             }
1.685     tempelho 15654:             return ();
                   15655:         }
                   15656:     }
                   15657:     &Apache::lonenc::check_decrypt(\$symb);
                   15658:     return ($symb);
                   15659: }
                   15660: 
                   15661: # --------------------------------------------------------------Get annotation
                   15662: 
                   15663: sub get_annotation {
                   15664:     my ($symb,$enc) = @_;
                   15665: 
                   15666:     my $key = $symb;
                   15667:     if (!$enc) {
                   15668:         $key =
                   15669:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15670:     }
                   15671:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   15672:     return $annotation{$key};
                   15673: }
                   15674: 
                   15675: sub clean_symb {
1.731     raeburn  15676:     my ($symb,$delete_enc) = @_;
1.685     tempelho 15677: 
                   15678:     &Apache::lonenc::check_decrypt(\$symb);
                   15679:     my $enc = $env{'request.enc'};
1.731     raeburn  15680:     if ($delete_enc) {
1.730     raeburn  15681:         delete($env{'request.enc'});
                   15682:     }
1.685     tempelho 15683: 
                   15684:     return ($symb,$enc);
                   15685: }
1.462     albertel 15686: 
1.1075.2.69  raeburn  15687: ############################################################
                   15688: ############################################################
                   15689: 
                   15690: =pod
                   15691: 
                   15692: =head1 Routines for building display used to search for courses
                   15693: 
                   15694: 
                   15695: =over 4
                   15696: 
                   15697: =item * &build_filters()
                   15698: 
                   15699: Create markup for a table used to set filters to use when selecting
                   15700: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   15701: and quotacheck.pl
                   15702: 
                   15703: 
                   15704: Inputs:
                   15705: 
                   15706: filterlist - anonymous array of fields to include as potential filters
                   15707: 
                   15708: crstype - course type
                   15709: 
                   15710: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   15711:               to pop-open a course selector (will contain "extra element").
                   15712: 
                   15713: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   15714: 
                   15715: filter - anonymous hash of criteria and their values
                   15716: 
                   15717: action - form action
                   15718: 
                   15719: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   15720: 
                   15721: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   15722: 
                   15723: cloneruname - username of owner of new course who wants to clone
                   15724: 
                   15725: clonerudom - domain of owner of new course who wants to clone
                   15726: 
                   15727: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   15728: 
                   15729: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   15730: 
                   15731: codedom - domain
                   15732: 
                   15733: formname - value of form element named "form".
                   15734: 
                   15735: fixeddom - domain, if fixed.
                   15736: 
                   15737: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   15738: 
                   15739: cnameelement - name of form element in form on opener page which will receive title of selected course
                   15740: 
                   15741: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   15742: 
                   15743: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   15744: 
                   15745: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   15746: 
                   15747: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   15748: 
                   15749: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   15750: 
                   15751: 
                   15752: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   15753: 
                   15754: 
                   15755: Side Effects: None
                   15756: 
                   15757: =cut
                   15758: 
                   15759: # ---------------------------------------------- search for courses based on last activity etc.
                   15760: 
                   15761: sub build_filters {
                   15762:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   15763:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   15764:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   15765:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   15766:         $clonetext,$clonewarning) = @_;
                   15767:     my ($list,$jscript);
                   15768:     my $onchange = 'javascript:updateFilters(this)';
                   15769:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   15770:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   15771:         $typeselectform,$instcodetitle);
                   15772:     if ($formname eq '') {
                   15773:         $formname = $caller;
                   15774:     }
                   15775:     foreach my $item (@{$filterlist}) {
                   15776:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15777:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15778:             if ($item eq 'domainfilter') {
                   15779:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15780:             } elsif ($item eq 'coursefilter') {
                   15781:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15782:             } elsif ($item eq 'ownerfilter') {
                   15783:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15784:             } elsif ($item eq 'ownerdomfilter') {
                   15785:                 $filter->{'ownerdomfilter'} =
                   15786:                     &LONCAPA::clean_domain($filter->{$item});
                   15787:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15788:                                                        'ownerdomfilter',1);
                   15789:             } elsif ($item eq 'personfilter') {
                   15790:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15791:             } elsif ($item eq 'persondomfilter') {
                   15792:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15793:                                                         'persondomfilter',1);
                   15794:             } else {
                   15795:                 $filter->{$item} =~ s/\W//g;
                   15796:             }
                   15797:             if (!$filter->{$item}) {
                   15798:                 $filter->{$item} = '';
                   15799:             }
                   15800:         }
                   15801:         if ($item eq 'domainfilter') {
                   15802:             my $allow_blank = 1;
                   15803:             if ($formname eq 'portform') {
                   15804:                 $allow_blank=0;
                   15805:             } elsif ($formname eq 'studentform') {
                   15806:                 $allow_blank=0;
                   15807:             }
                   15808:             if ($fixeddom) {
                   15809:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15810:                                     ' value="'.$codedom.'" />'.
                   15811:                                     &Apache::lonnet::domain($codedom,'description');
                   15812:             } else {
                   15813:                 $domainselectform = &select_dom_form($filter->{$item},
                   15814:                                                      'domainfilter',
                   15815:                                                       $allow_blank,'',$onchange);
                   15816:             }
                   15817:         } else {
                   15818:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15819:         }
                   15820:     }
                   15821: 
                   15822:     # last course activity filter and selection
                   15823:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15824: 
                   15825:     # course created filter and selection
                   15826:     if (exists($filter->{'createdfilter'})) {
                   15827:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15828:     }
                   15829: 
                   15830:     my %lt = &Apache::lonlocal::texthash(
                   15831:                 'cac' => "$crstype Activity",
                   15832:                 'ccr' => "$crstype Created",
                   15833:                 'cde' => "$crstype Title",
                   15834:                 'cdo' => "$crstype Domain",
                   15835:                 'ins' => 'Institutional Code',
                   15836:                 'inc' => 'Institutional Categorization',
                   15837:                 'cow' => "$crstype Owner/Co-owner",
                   15838:                 'cop' => "$crstype Personnel Includes",
                   15839:                 'cog' => 'Type',
                   15840:              );
                   15841: 
                   15842:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15843:         my $typeval = 'Course';
                   15844:         if ($crstype eq 'Community') {
                   15845:             $typeval = 'Community';
                   15846:         }
                   15847:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15848:     } else {
                   15849:         $typeselectform =  '<select name="type" size="1"';
                   15850:         if ($onchange) {
                   15851:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15852:         }
                   15853:         $typeselectform .= '>'."\n";
                   15854:         foreach my $posstype ('Course','Community') {
                   15855:             $typeselectform.='<option value="'.$posstype.'"'.
                   15856:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   15857:         }
                   15858:         $typeselectform.="</select>";
                   15859:     }
                   15860: 
                   15861:     my ($cloneableonlyform,$cloneabletitle);
                   15862:     if (exists($filter->{'cloneableonly'})) {
                   15863:         my $cloneableon = '';
                   15864:         my $cloneableoff = ' checked="checked"';
                   15865:         if ($filter->{'cloneableonly'}) {
                   15866:             $cloneableon = $cloneableoff;
                   15867:             $cloneableoff = '';
                   15868:         }
                   15869:         $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>';
                   15870:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  15871:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  15872:         } else {
                   15873:             $cloneabletitle = &mt('Cloneable by you');
                   15874:         }
                   15875:     }
                   15876:     my $officialjs;
                   15877:     if ($crstype eq 'Course') {
                   15878:         if (exists($filter->{'instcodefilter'})) {
                   15879: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15880: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15881:             if ($codedom) {
                   15882:                 $officialjs = 1;
                   15883:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15884:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15885:                                                                   $officialjs,$codetitlesref);
                   15886:                 if ($jscript) {
                   15887:                     $jscript = '<script type="text/javascript">'."\n".
                   15888:                                '// <![CDATA['."\n".
                   15889:                                $jscript."\n".
                   15890:                                '// ]]>'."\n".
                   15891:                                '</script>'."\n";
                   15892:                 }
                   15893:             }
                   15894:             if ($instcodeform eq '') {
                   15895:                 $instcodeform =
                   15896:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15897:                     $list->{'instcodefilter'}.'" />';
                   15898:                 $instcodetitle = $lt{'ins'};
                   15899:             } else {
                   15900:                 $instcodetitle = $lt{'inc'};
                   15901:             }
                   15902:             if ($fixeddom) {
                   15903:                 $instcodetitle .= '<br />('.$codedom.')';
                   15904:             }
                   15905:         }
                   15906:     }
                   15907:     my $output = qq|
                   15908: <form method="post" name="filterpicker" action="$action">
                   15909: <input type="hidden" name="form" value="$formname" />
                   15910: |;
                   15911:     if ($formname eq 'modifycourse') {
                   15912:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15913:                    '<input type="hidden" name="prevphase" value="'.
                   15914:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  15915:     } elsif ($formname eq 'quotacheck') {
                   15916:         $output .= qq|
                   15917: <input type="hidden" name="sortby" value="" />
                   15918: <input type="hidden" name="sortorder" value="" />
                   15919: |;
                   15920:     } else {
1.1075.2.69  raeburn  15921:         my $name_input;
                   15922:         if ($cnameelement ne '') {
                   15923:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15924:                           $cnameelement.'" />';
                   15925:         }
                   15926:         $output .= qq|
                   15927: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15928: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   15929: $name_input
                   15930: $roleelement
                   15931: $multelement
                   15932: $typeelement
                   15933: |;
                   15934:         if ($formname eq 'portform') {
                   15935:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15936:         }
                   15937:     }
                   15938:     if ($fixeddom) {
                   15939:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15940:     }
                   15941:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15942:     if ($sincefilterform) {
                   15943:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15944:                   .$sincefilterform
                   15945:                   .&Apache::lonhtmlcommon::row_closure();
                   15946:     }
                   15947:     if ($createdfilterform) {
                   15948:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15949:                   .$createdfilterform
                   15950:                   .&Apache::lonhtmlcommon::row_closure();
                   15951:     }
                   15952:     if ($domainselectform) {
                   15953:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15954:                   .$domainselectform
                   15955:                   .&Apache::lonhtmlcommon::row_closure();
                   15956:     }
                   15957:     if ($typeselectform) {
                   15958:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15959:             $output .= $typeselectform;
                   15960:         } else {
                   15961:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   15962:                       .$typeselectform
                   15963:                       .&Apache::lonhtmlcommon::row_closure();
                   15964:         }
                   15965:     }
                   15966:     if ($instcodeform) {
                   15967:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   15968:                   .$instcodeform
                   15969:                   .&Apache::lonhtmlcommon::row_closure();
                   15970:     }
                   15971:     if (exists($filter->{'ownerfilter'})) {
                   15972:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   15973:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15974:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   15975:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15976:                    $ownerdomselectform.'</td></tr></table>'.
                   15977:                    &Apache::lonhtmlcommon::row_closure();
                   15978:     }
                   15979:     if (exists($filter->{'personfilter'})) {
                   15980:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   15981:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15982:                    '<input type="text" name="personfilter" size="20" value="'.
                   15983:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15984:                    $persondomselectform.'</td></tr></table>'.
                   15985:                    &Apache::lonhtmlcommon::row_closure();
                   15986:     }
                   15987:     if (exists($filter->{'coursefilter'})) {
                   15988:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   15989:                   .'<input type="text" name="coursefilter" size="25" value="'
                   15990:                   .$list->{'coursefilter'}.'" />'
                   15991:                   .&Apache::lonhtmlcommon::row_closure();
                   15992:     }
                   15993:     if ($cloneableonlyform) {
                   15994:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   15995:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   15996:     }
                   15997:     if (exists($filter->{'descriptfilter'})) {
                   15998:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   15999:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16000:                   .$list->{'descriptfilter'}.'" />'
                   16001:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16002:     }
                   16003:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16004:                '<input type="hidden" name="updater" value="" />'."\n".
                   16005:                '<input type="submit" name="gosearch" value="'.
                   16006:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16007:     return $jscript.$clonewarning.$output;
                   16008: }
                   16009: 
                   16010: =pod
                   16011: 
                   16012: =item * &timebased_select_form()
                   16013: 
                   16014: Create markup for a dropdown list used to select a time-based
                   16015: filter e.g., Course Activity, Course Created, when searching for courses
                   16016: or communities
                   16017: 
                   16018: Inputs:
                   16019: 
                   16020: item - name of form element (sincefilter or createdfilter)
                   16021: 
                   16022: filter - anonymous hash of criteria and their values
                   16023: 
                   16024: Returns: HTML for a select box contained a blank, then six time selections,
                   16025:          with value set in incoming form variables currently selected.
                   16026: 
                   16027: Side Effects: None
                   16028: 
                   16029: =cut
                   16030: 
                   16031: sub timebased_select_form {
                   16032:     my ($item,$filter) = @_;
                   16033:     if (ref($filter) eq 'HASH') {
                   16034:         $filter->{$item} =~ s/[^\d-]//g;
                   16035:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16036:         return &select_form(
                   16037:                             $filter->{$item},
                   16038:                             $item,
                   16039:                             {      '-1' => '',
                   16040:                                 '86400' => &mt('today'),
                   16041:                                '604800' => &mt('last week'),
                   16042:                               '2592000' => &mt('last month'),
                   16043:                               '7776000' => &mt('last three months'),
                   16044:                              '15552000' => &mt('last six months'),
                   16045:                              '31104000' => &mt('last year'),
                   16046:                     'select_form_order' =>
                   16047:                            ['-1','86400','604800','2592000','7776000',
                   16048:                             '15552000','31104000']});
                   16049:     }
                   16050: }
                   16051: 
                   16052: =pod
                   16053: 
                   16054: =item * &js_changer()
                   16055: 
                   16056: Create script tag containing Javascript used to submit course search form
                   16057: when course type or domain is changed, and also to hide 'Searching ...' on
                   16058: page load completion for page showing search result.
                   16059: 
                   16060: Inputs: None
                   16061: 
                   16062: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   16063: 
                   16064: Side Effects: None
                   16065: 
                   16066: =cut
                   16067: 
                   16068: sub js_changer {
                   16069:     return <<ENDJS;
                   16070: <script type="text/javascript">
                   16071: // <![CDATA[
                   16072: function updateFilters(caller) {
                   16073:     if (typeof(caller) != "undefined") {
                   16074:         document.filterpicker.updater.value = caller.name;
                   16075:     }
                   16076:     document.filterpicker.submit();
                   16077: }
                   16078: 
                   16079: function hideSearching() {
                   16080:     if (document.getElementById('searching')) {
                   16081:         document.getElementById('searching').style.display = 'none';
                   16082:     }
                   16083:     return;
                   16084: }
                   16085: 
                   16086: // ]]>
                   16087: </script>
                   16088: 
                   16089: ENDJS
                   16090: }
                   16091: 
                   16092: =pod
                   16093: 
                   16094: =item * &search_courses()
                   16095: 
                   16096: Process selected filters form course search form and pass to lonnet::courseiddump
                   16097: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16098: 
                   16099: Inputs:
                   16100: 
                   16101: dom - domain being searched
                   16102: 
                   16103: type - course type ('Course' or 'Community' or '.' if any).
                   16104: 
                   16105: filter - anonymous hash of criteria and their values
                   16106: 
                   16107: numtitles - for institutional codes - number of categories
                   16108: 
                   16109: cloneruname - optional username of new course owner
                   16110: 
                   16111: clonerudom - optional domain of new course owner
                   16112: 
1.1075.2.95  raeburn  16113: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  16114:             (used when DC is using course creation form)
                   16115: 
                   16116: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16117: 
1.1075.2.95  raeburn  16118: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16119:            (and so can clone automatically)
                   16120: 
                   16121: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16122: 
                   16123: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   16124:               courses to clone
1.1075.2.69  raeburn  16125: 
                   16126: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16127: 
                   16128: 
                   16129: Side Effects: None
                   16130: 
                   16131: =cut
                   16132: 
                   16133: 
                   16134: sub search_courses {
1.1075.2.95  raeburn  16135:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16136:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  16137:     my (%courses,%showcourses,$cloner);
                   16138:     if (($filter->{'ownerfilter'} ne '') ||
                   16139:         ($filter->{'ownerdomfilter'} ne '')) {
                   16140:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16141:                                        $filter->{'ownerdomfilter'};
                   16142:     }
                   16143:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16144:         if (!$filter->{$item}) {
                   16145:             $filter->{$item}='.';
                   16146:         }
                   16147:     }
                   16148:     my $now = time;
                   16149:     my $timefilter =
                   16150:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16151:     my ($createdbefore,$createdafter);
                   16152:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16153:         $createdbefore = $now;
                   16154:         $createdafter = $now-$filter->{'createdfilter'};
                   16155:     }
                   16156:     my ($instcodefilter,$regexpok);
                   16157:     if ($numtitles) {
                   16158:         if ($env{'form.official'} eq 'on') {
                   16159:             $instcodefilter =
                   16160:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16161:             $regexpok = 1;
                   16162:         } elsif ($env{'form.official'} eq 'off') {
                   16163:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16164:             unless ($instcodefilter eq '') {
                   16165:                 $regexpok = -1;
                   16166:             }
                   16167:         }
                   16168:     } else {
                   16169:         $instcodefilter = $filter->{'instcodefilter'};
                   16170:     }
                   16171:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16172:     if ($type eq '') { $type = '.'; }
                   16173: 
                   16174:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16175:         $cloner = $cloneruname.':'.$clonerudom;
                   16176:     }
                   16177:     %courses = &Apache::lonnet::courseiddump($dom,
                   16178:                                              $filter->{'descriptfilter'},
                   16179:                                              $timefilter,
                   16180:                                              $instcodefilter,
                   16181:                                              $filter->{'combownerfilter'},
                   16182:                                              $filter->{'coursefilter'},
                   16183:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  16184:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  16185:                                              $filter->{'cloneableonly'},
                   16186:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  16187:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  16188:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16189:         my $ccrole;
                   16190:         if ($type eq 'Community') {
                   16191:             $ccrole = 'co';
                   16192:         } else {
                   16193:             $ccrole = 'cc';
                   16194:         }
                   16195:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16196:                                                      $filter->{'persondomfilter'},
                   16197:                                                      'userroles',undef,
                   16198:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16199:                                                      $dom);
                   16200:         foreach my $role (keys(%rolehash)) {
                   16201:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16202:             my $cid = $cdom.'_'.$cnum;
                   16203:             if (exists($courses{$cid})) {
                   16204:                 if (ref($courses{$cid}) eq 'HASH') {
                   16205:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16206:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  16207:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  16208:                         }
                   16209:                     } else {
                   16210:                         $courses{$cid}{roles} = [$courserole];
                   16211:                     }
                   16212:                     $showcourses{$cid} = $courses{$cid};
                   16213:                 }
                   16214:             }
                   16215:         }
                   16216:         %courses = %showcourses;
                   16217:     }
                   16218:     return %courses;
                   16219: }
                   16220: 
                   16221: =pod
                   16222: 
                   16223: =back
                   16224: 
1.1075.2.88  raeburn  16225: =head1 Routines for version requirements for current course.
                   16226: 
                   16227: =over 4
                   16228: 
                   16229: =item * &check_release_required()
                   16230: 
                   16231: Compares required LON-CAPA version with version on server, and
                   16232: if required version is newer looks for a server with the required version.
                   16233: 
                   16234: Looks first at servers in user's owen domain; if none suitable, looks at
                   16235: servers in course's domain are permitted to host sessions for user's domain.
                   16236: 
                   16237: Inputs:
                   16238: 
                   16239: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16240: 
                   16241: $courseid - Course ID of current course
                   16242: 
                   16243: $rolecode - User's current role in course (for switchserver query string).
                   16244: 
                   16245: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16246: 
                   16247: 
                   16248: Returns:
                   16249: 
                   16250: $switchserver - query string tp append to /adm/switchserver call (if
                   16251:                 current server's LON-CAPA version is too old.
                   16252: 
                   16253: $warning - Message is displayed if no suitable server could be found.
                   16254: 
                   16255: =cut
                   16256: 
                   16257: sub check_release_required {
                   16258:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16259:     my ($switchserver,$warning);
                   16260:     if ($required ne '') {
                   16261:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16262:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16263:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16264:             my $otherserver;
                   16265:             if (($major eq '' && $minor eq '') ||
                   16266:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16267:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16268:                 my $switchlcrev =
                   16269:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16270:                                                            $userdomserver);
                   16271:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16272:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16273:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16274:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16275:                     if ($cdom ne $env{'user.domain'}) {
                   16276:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16277:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16278:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16279:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16280:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16281:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16282:                         my $canhost =
                   16283:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16284:                                                               $coursedomserver,
                   16285:                                                               $remoterev,
                   16286:                                                               $udomdefaults{'remotesessions'},
                   16287:                                                               $defdomdefaults{'hostedsessions'});
                   16288: 
                   16289:                         if ($canhost) {
                   16290:                             $otherserver = $coursedomserver;
                   16291:                         } else {
                   16292:                             $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.");
                   16293:                         }
                   16294:                     } else {
                   16295:                         $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).");
                   16296:                     }
                   16297:                 } else {
                   16298:                     $otherserver = $userdomserver;
                   16299:                 }
                   16300:             }
                   16301:             if ($otherserver ne '') {
                   16302:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16303:             }
                   16304:         }
                   16305:     }
                   16306:     return ($switchserver,$warning);
                   16307: }
                   16308: 
                   16309: =pod
                   16310: 
                   16311: =item * &check_release_result()
                   16312: 
                   16313: Inputs:
                   16314: 
                   16315: $switchwarning - Warning message if no suitable server found to host session.
                   16316: 
                   16317: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16318:                 and current role.
                   16319: 
                   16320: Returns: HTML to display with information about requirement to switch server.
                   16321:          Either displaying warning with link to Roles/Courses screen or
                   16322:          display link to switchserver.
                   16323: 
1.1075.2.69  raeburn  16324: =cut
                   16325: 
1.1075.2.88  raeburn  16326: sub check_release_result {
                   16327:     my ($switchwarning,$switchserver) = @_;
                   16328:     my $output = &start_page('Selected course unavailable on this server').
                   16329:                  '<p class="LC_warning">';
                   16330:     if ($switchwarning) {
                   16331:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16332:         if (&show_course()) {
                   16333:             $output .= &mt('Display courses');
                   16334:         } else {
                   16335:             $output .= &mt('Display roles');
                   16336:         }
                   16337:         $output .= '</a>';
                   16338:     } elsif ($switchserver) {
                   16339:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16340:                    '<br />'.
                   16341:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16342:                    &mt('Switch Server').
                   16343:                    '</a>';
                   16344:     }
                   16345:     $output .= '</p>'.&end_page();
                   16346:     return $output;
                   16347: }
                   16348: 
                   16349: =pod
                   16350: 
                   16351: =item * &needs_coursereinit()
                   16352: 
                   16353: Determine if course contents stored for user's session needs to be
                   16354: refreshed, because content has changed since "Big Hash" last tied.
                   16355: 
                   16356: Check for change is made if time last checked is more than 10 minutes ago
                   16357: (by default).
                   16358: 
                   16359: Inputs:
                   16360: 
                   16361: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16362: 
                   16363: $interval (optional) - Time which may elapse (in s) between last check for content
                   16364:                        change in current course. (default: 600 s).
                   16365: 
                   16366: Returns: an array; first element is:
                   16367: 
                   16368: =over 4
                   16369: 
                   16370: 'switch' - if content updates mean user's session
                   16371:            needs to be switched to a server running a newer LON-CAPA version
                   16372: 
                   16373: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16374:            on current server hosting user's session
                   16375: 
                   16376: ''       - if no action required.
                   16377: 
                   16378: =back
                   16379: 
                   16380: If first item element is 'switch':
                   16381: 
                   16382: second item is $switchwarning - Warning message if no suitable server found to host session.
                   16383: 
                   16384: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16385:                               and current role.
                   16386: 
                   16387: otherwise: no other elements returned.
                   16388: 
                   16389: =back
                   16390: 
                   16391: =cut
                   16392: 
                   16393: sub needs_coursereinit {
                   16394:     my ($loncaparev,$interval) = @_;
                   16395:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16396:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16397:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16398:     my $now = time;
                   16399:     if ($interval eq '') {
                   16400:         $interval = 600;
                   16401:     }
                   16402:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16403:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16404:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16405:         if ($lastchange > $env{'request.course.tied'}) {
                   16406:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16407:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16408:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16409:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16410:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16411:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16412:                     my ($switchserver,$switchwarning) =
                   16413:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16414:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16415:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16416:                         return ('switch',$switchwarning,$switchserver);
                   16417:                     }
                   16418:                 }
                   16419:             }
                   16420:             return ('update');
                   16421:         }
                   16422:     }
                   16423:     return ();
                   16424: }
1.1075.2.69  raeburn  16425: 
1.1075.2.11  raeburn  16426: sub update_content_constraints {
                   16427:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16428:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16429:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16430:     my %checkresponsetypes;
                   16431:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   16432:         my ($item,$name,$value) = split(/:/,$key);
                   16433:         if ($item eq 'resourcetag') {
                   16434:             if ($name eq 'responsetype') {
                   16435:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16436:             }
                   16437:         }
                   16438:     }
                   16439:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16440:     if (defined($navmap)) {
                   16441:         my %allresponses;
                   16442:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16443:             my %responses = $res->responseTypes();
                   16444:             foreach my $key (keys(%responses)) {
                   16445:                 next unless(exists($checkresponsetypes{$key}));
                   16446:                 $allresponses{$key} += $responses{$key};
                   16447:             }
                   16448:         }
                   16449:         foreach my $key (keys(%allresponses)) {
                   16450:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16451:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16452:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16453:             }
                   16454:         }
                   16455:         undef($navmap);
                   16456:     }
                   16457:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16458:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16459:     }
                   16460:     return;
                   16461: }
                   16462: 
1.1075.2.27  raeburn  16463: sub allmaps_incourse {
                   16464:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16465:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16466:         $cid = $env{'request.course.id'};
                   16467:         $cdom = $env{'course.'.$cid.'.domain'};
                   16468:         $cnum = $env{'course.'.$cid.'.num'};
                   16469:         $chome = $env{'course.'.$cid.'.home'};
                   16470:     }
                   16471:     my %allmaps = ();
                   16472:     my $lastchange =
                   16473:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16474:     if ($lastchange > $env{'request.course.tied'}) {
                   16475:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16476:         unless ($ferr) {
                   16477:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16478:         }
                   16479:     }
                   16480:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16481:     if (defined($navmap)) {
                   16482:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16483:             $allmaps{$res->src()} = 1;
                   16484:         }
                   16485:     }
                   16486:     return \%allmaps;
                   16487: }
                   16488: 
1.1075.2.11  raeburn  16489: sub parse_supplemental_title {
                   16490:     my ($title) = @_;
                   16491: 
                   16492:     my ($foldertitle,$renametitle);
                   16493:     if ($title =~ /&amp;&amp;&amp;/) {
                   16494:         $title = &HTML::Entites::decode($title);
                   16495:     }
                   16496:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16497:         $renametitle=$4;
                   16498:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16499:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16500:         my $name =  &plainname($uname,$udom);
                   16501:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16502:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16503:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16504:             $name.': <br />'.$foldertitle;
                   16505:     }
                   16506:     if (wantarray) {
                   16507:         return ($title,$foldertitle,$renametitle);
                   16508:     }
                   16509:     return $title;
                   16510: }
                   16511: 
1.1075.2.43  raeburn  16512: sub recurse_supplemental {
                   16513:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16514:     if ($suppmap) {
                   16515:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16516:         if ($fatal) {
                   16517:             $errors ++;
                   16518:         } else {
                   16519:             if ($#LONCAPA::map::resources > 0) {
                   16520:                 foreach my $res (@LONCAPA::map::resources) {
                   16521:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16522:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  16523:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16524:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  16525:                         } else {
                   16526:                             $numfiles ++;
                   16527:                         }
                   16528:                     }
                   16529:                 }
                   16530:             }
                   16531:         }
                   16532:     }
                   16533:     return ($numfiles,$errors);
                   16534: }
                   16535: 
1.1075.2.18  raeburn  16536: sub symb_to_docspath {
1.1075.2.119  raeburn  16537:     my ($symb,$navmapref) = @_;
                   16538:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  16539:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16540:     if ($resurl=~/\.(sequence|page)$/) {
                   16541:         $mapurl=$resurl;
                   16542:     } elsif ($resurl eq 'adm/navmaps') {
                   16543:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16544:     }
                   16545:     my $mapresobj;
1.1075.2.119  raeburn  16546:     unless (ref($$navmapref)) {
                   16547:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   16548:     }
                   16549:     if (ref($$navmapref)) {
                   16550:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  16551:     }
                   16552:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16553:     my $type=$2;
                   16554:     my $path;
                   16555:     if (ref($mapresobj)) {
                   16556:         my $pcslist = $mapresobj->map_hierarchy();
                   16557:         if ($pcslist ne '') {
                   16558:             foreach my $pc (split(/,/,$pcslist)) {
                   16559:                 next if ($pc <= 1);
1.1075.2.119  raeburn  16560:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  16561:                 if (ref($res)) {
                   16562:                     my $thisurl = $res->src();
                   16563:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16564:                     my $thistitle = $res->title();
                   16565:                     $path .= '&'.
                   16566:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  16567:                              &escape($thistitle).
1.1075.2.18  raeburn  16568:                              ':'.$res->randompick().
                   16569:                              ':'.$res->randomout().
                   16570:                              ':'.$res->encrypted().
                   16571:                              ':'.$res->randomorder().
                   16572:                              ':'.$res->is_page();
                   16573:                 }
                   16574:             }
                   16575:         }
                   16576:         $path =~ s/^\&//;
                   16577:         my $maptitle = $mapresobj->title();
                   16578:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16579:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16580:         }
                   16581:         $path .= (($path ne '')? '&' : '').
                   16582:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16583:                  &escape($maptitle).
1.1075.2.18  raeburn  16584:                  ':'.$mapresobj->randompick().
                   16585:                  ':'.$mapresobj->randomout().
                   16586:                  ':'.$mapresobj->encrypted().
                   16587:                  ':'.$mapresobj->randomorder().
                   16588:                  ':'.$mapresobj->is_page();
                   16589:     } else {
                   16590:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16591:         my $ispage = (($type eq 'page')? 1 : '');
                   16592:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16593:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16594:         }
                   16595:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16596:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  16597:     }
                   16598:     unless ($mapurl eq 'default') {
                   16599:         $path = 'default&'.
1.1075.2.46  raeburn  16600:                 &escape('Main Content').
1.1075.2.18  raeburn  16601:                 ':::::&'.$path;
                   16602:     }
                   16603:     return $path;
                   16604: }
                   16605: 
1.1075.2.14  raeburn  16606: sub captcha_display {
                   16607:     my ($context,$lonhost) = @_;
                   16608:     my ($output,$error);
1.1075.2.107  raeburn  16609:     my ($captcha,$pubkey,$privkey,$version) =
                   16610:         &get_captcha_config($context,$lonhost);
1.1075.2.14  raeburn  16611:     if ($captcha eq 'original') {
                   16612:         $output = &create_captcha();
                   16613:         unless ($output) {
                   16614:             $error = 'captcha';
                   16615:         }
                   16616:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16617:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  16618:         unless ($output) {
                   16619:             $error = 'recaptcha';
                   16620:         }
                   16621:     }
1.1075.2.107  raeburn  16622:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  16623: }
                   16624: 
                   16625: sub captcha_response {
                   16626:     my ($context,$lonhost) = @_;
                   16627:     my ($captcha_chk,$captcha_error);
1.1075.2.109  raeburn  16628:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
1.1075.2.14  raeburn  16629:     if ($captcha eq 'original') {
                   16630:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16631:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16632:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  16633:     } else {
                   16634:         $captcha_chk = 1;
                   16635:     }
                   16636:     return ($captcha_chk,$captcha_error);
                   16637: }
                   16638: 
                   16639: sub get_captcha_config {
                   16640:     my ($context,$lonhost) = @_;
1.1075.2.107  raeburn  16641:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  16642:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   16643:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   16644:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16645:     if ($context eq 'usercreation') {
                   16646:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   16647:         if (ref($domconfig{$context}) eq 'HASH') {
                   16648:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   16649:             if (ref($hashtocheck) eq 'HASH') {
                   16650:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   16651:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   16652:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   16653:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   16654:                     }
                   16655:                     if ($privkey && $pubkey) {
                   16656:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  16657:                         $version = $hashtocheck->{'recaptchaversion'};
                   16658:                         if ($version ne '2') {
                   16659:                             $version = 1;
                   16660:                         }
1.1075.2.14  raeburn  16661:                     } else {
                   16662:                         $captcha = 'original';
                   16663:                     }
                   16664:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   16665:                     $captcha = 'original';
                   16666:                 }
                   16667:             }
                   16668:         } else {
                   16669:             $captcha = 'captcha';
                   16670:         }
                   16671:     } elsif ($context eq 'login') {
                   16672:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   16673:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   16674:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   16675:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   16676:             if ($privkey && $pubkey) {
                   16677:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  16678:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   16679:                 if ($version ne '2') {
                   16680:                     $version = 1;
                   16681:                 }
1.1075.2.14  raeburn  16682:             } else {
                   16683:                 $captcha = 'original';
                   16684:             }
                   16685:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   16686:             $captcha = 'original';
                   16687:         }
                   16688:     }
1.1075.2.107  raeburn  16689:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  16690: }
                   16691: 
                   16692: sub create_captcha {
                   16693:     my %captcha_params = &captcha_settings();
                   16694:     my ($output,$maxtries,$tries) = ('',10,0);
                   16695:     while ($tries < $maxtries) {
                   16696:         $tries ++;
                   16697:         my $captcha = Authen::Captcha->new (
                   16698:                                            output_folder => $captcha_params{'output_dir'},
                   16699:                                            data_folder   => $captcha_params{'db_dir'},
                   16700:                                           );
                   16701:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   16702: 
                   16703:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   16704:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   16705:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  16706:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   16707:                       '<br />'.
                   16708:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  16709:             last;
                   16710:         }
                   16711:     }
                   16712:     return $output;
                   16713: }
                   16714: 
                   16715: sub captcha_settings {
                   16716:     my %captcha_params = (
                   16717:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   16718:                            www_output_dir => "/captchaspool",
                   16719:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   16720:                            numchars       => '5',
                   16721:                          );
                   16722:     return %captcha_params;
                   16723: }
                   16724: 
                   16725: sub check_captcha {
                   16726:     my ($captcha_chk,$captcha_error);
                   16727:     my $code = $env{'form.code'};
                   16728:     my $md5sum = $env{'form.crypt'};
                   16729:     my %captcha_params = &captcha_settings();
                   16730:     my $captcha = Authen::Captcha->new(
                   16731:                       output_folder => $captcha_params{'output_dir'},
                   16732:                       data_folder   => $captcha_params{'db_dir'},
                   16733:                   );
1.1075.2.26  raeburn  16734:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  16735:     my %captcha_hash = (
                   16736:                         0       => 'Code not checked (file error)',
                   16737:                        -1      => 'Failed: code expired',
                   16738:                        -2      => 'Failed: invalid code (not in database)',
                   16739:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   16740:     );
                   16741:     if ($captcha_chk != 1) {
                   16742:         $captcha_error = $captcha_hash{$captcha_chk}
                   16743:     }
                   16744:     return ($captcha_chk,$captcha_error);
                   16745: }
                   16746: 
                   16747: sub create_recaptcha {
1.1075.2.107  raeburn  16748:     my ($pubkey,$version) = @_;
                   16749:     if ($version >= 2) {
                   16750:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   16751:     } else {
                   16752:         my $use_ssl;
                   16753:         if ($ENV{'SERVER_PORT'} == 443) {
                   16754:             $use_ssl = 1;
                   16755:         }
                   16756:         my $captcha = Captcha::reCAPTCHA->new;
                   16757:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   16758:                $captcha->get_html($pubkey,undef,$use_ssl).
                   16759:                &mt('If the text is hard to read, [_1] will replace them.',
                   16760:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   16761:                '<br /><br />';
                   16762:      }
1.1075.2.14  raeburn  16763: }
                   16764: 
                   16765: sub check_recaptcha {
1.1075.2.107  raeburn  16766:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  16767:     my $captcha_chk;
1.1075.2.107  raeburn  16768:     if ($version >= 2) {
                   16769:         my $ua = LWP::UserAgent->new;
                   16770:         $ua->timeout(10);
                   16771:         my %info = (
                   16772:                      secret   => $privkey,
                   16773:                      response => $env{'form.g-recaptcha-response'},
                   16774:                      remoteip => $ENV{'REMOTE_ADDR'},
                   16775:                    );
                   16776:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   16777:         if ($response->is_success)  {
                   16778:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   16779:             if (ref($data) eq 'HASH') {
                   16780:                 if ($data->{'success'}) {
                   16781:                     $captcha_chk = 1;
                   16782:                 }
                   16783:             }
                   16784:         }
                   16785:     } else {
                   16786:         my $captcha = Captcha::reCAPTCHA->new;
                   16787:         my $captcha_result =
                   16788:             $captcha->check_answer(
                   16789:                                     $privkey,
                   16790:                                     $ENV{'REMOTE_ADDR'},
                   16791:                                     $env{'form.recaptcha_challenge_field'},
                   16792:                                     $env{'form.recaptcha_response_field'},
                   16793:                                   );
                   16794:         if ($captcha_result->{is_valid}) {
                   16795:             $captcha_chk = 1;
                   16796:         }
1.1075.2.14  raeburn  16797:     }
                   16798:     return $captcha_chk;
                   16799: }
                   16800: 
1.1075.2.64  raeburn  16801: sub emailusername_info {
1.1075.2.103  raeburn  16802:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  16803:     my %titles = &Apache::lonlocal::texthash (
                   16804:                      lastname      => 'Last Name',
                   16805:                      firstname     => 'First Name',
                   16806:                      institution   => 'School/college/university',
                   16807:                      location      => "School's city, state/province, country",
                   16808:                      web           => "School's web address",
                   16809:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  16810:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  16811:                  );
                   16812:     return (\@fields,\%titles);
                   16813: }
                   16814: 
1.1075.2.56  raeburn  16815: sub cleanup_html {
                   16816:     my ($incoming) = @_;
                   16817:     my $outgoing;
                   16818:     if ($incoming ne '') {
                   16819:         $outgoing = $incoming;
                   16820:         $outgoing =~ s/;/&#059;/g;
                   16821:         $outgoing =~ s/\#/&#035;/g;
                   16822:         $outgoing =~ s/\&/&#038;/g;
                   16823:         $outgoing =~ s/</&#060;/g;
                   16824:         $outgoing =~ s/>/&#062;/g;
                   16825:         $outgoing =~ s/\(/&#040/g;
                   16826:         $outgoing =~ s/\)/&#041;/g;
                   16827:         $outgoing =~ s/"/&#034;/g;
                   16828:         $outgoing =~ s/'/&#039;/g;
                   16829:         $outgoing =~ s/\$/&#036;/g;
                   16830:         $outgoing =~ s{/}{&#047;}g;
                   16831:         $outgoing =~ s/=/&#061;/g;
                   16832:         $outgoing =~ s/\\/&#092;/g
                   16833:     }
                   16834:     return $outgoing;
                   16835: }
                   16836: 
1.1075.2.74  raeburn  16837: # Checks for critical messages and returns a redirect url if one exists.
                   16838: # $interval indicates how often to check for messages.
                   16839: sub critical_redirect {
                   16840:     my ($interval) = @_;
                   16841:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16842:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   16843:                                         $env{'user.name'});
                   16844:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   16845:         my $redirecturl;
                   16846:         if ($what[0]) {
                   16847:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16848:                 $redirecturl='/adm/email?critical=display';
                   16849:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16850:                 return (1, $url);
                   16851:             }
                   16852:         }
                   16853:     }
                   16854:     return ();
                   16855: }
                   16856: 
1.1075.2.64  raeburn  16857: # Use:
                   16858: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16859: #
                   16860: ##################################################
                   16861: #          password associated functions         #
                   16862: ##################################################
                   16863: sub des_keys {
                   16864:     # Make a new key for DES encryption.
                   16865:     # Each key has two parts which are returned separately.
                   16866:     # Please note:  Each key must be passed through the &hex function
                   16867:     # before it is output to the web browser.  The hex versions cannot
                   16868:     # be used to decrypt.
                   16869:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16870:                 '8','9','a','b','c','d','e','f');
                   16871:     my $lkey='';
                   16872:     for (0..7) {
                   16873:         $lkey.=$hexstr[rand(15)];
                   16874:     }
                   16875:     my $ukey='';
                   16876:     for (0..7) {
                   16877:         $ukey.=$hexstr[rand(15)];
                   16878:     }
                   16879:     return ($lkey,$ukey);
                   16880: }
                   16881: 
                   16882: sub des_decrypt {
                   16883:     my ($key,$cyphertext) = @_;
                   16884:     my $keybin=pack("H16",$key);
                   16885:     my $cypher;
                   16886:     if ($Crypt::DES::VERSION>=2.03) {
                   16887:         $cypher=new Crypt::DES $keybin;
                   16888:     } else {
                   16889:         $cypher=new DES $keybin;
                   16890:     }
1.1075.2.106  raeburn  16891:     my $plaintext='';
                   16892:     my $cypherlength = length($cyphertext);
                   16893:     my $numchunks = int($cypherlength/32);
                   16894:     for (my $j=0; $j<$numchunks; $j++) {
                   16895:         my $start = $j*32;
                   16896:         my $cypherblock = substr($cyphertext,$start,32);
                   16897:         my $chunk =
                   16898:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   16899:         $chunk .=
                   16900:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   16901:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   16902:         $plaintext .= $chunk;
                   16903:     }
1.1075.2.64  raeburn  16904:     return $plaintext;
                   16905: }
                   16906: 
1.112     bowersj2 16907: 1;
                   16908: __END__;
1.41      ng       16909: 

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