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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1336  ! raeburn     4: # $Id: loncommon.pm,v 1.1335 2020/01/10 05:08:39 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1280    raeburn    74: use LONCAPA::LWPReq;
1.1328    raeburn    75: use HTTP::Request;
1.657     raeburn    76: use DateTime::TimeZone;
1.1241    raeburn    77: use DateTime::Locale;
1.1220    raeburn    78: use Encode();
1.1091    foxr       79: use Text::Aspell;
1.1094    raeburn    80: use Authen::Captcha;
                     81: use Captcha::reCAPTCHA;
1.1234    raeburn    82: use JSON::DWIW;
                     83: use LWP::UserAgent;
1.1174    raeburn    84: use Crypt::DES;
                     85: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   86: use MIME::Lite;
                     87: use MIME::Types;
1.1292    raeburn    88: use File::Copy();
1.1300    raeburn    89: use File::Path();
1.1309    raeburn    90: use String::CRC32();
                     91: use Short::URL();
1.117     www        92: 
1.517     raeburn    93: # ---------------------------------------------- Designs
                     94: use vars qw(%defaultdesign);
                     95: 
1.22      www        96: my $readit;
                     97: 
1.517     raeburn    98: 
1.157     matthew    99: ##
                    100: ## Global Variables
                    101: ##
1.46      matthew   102: 
1.643     foxr      103: 
                    104: # ----------------------------------------------- SSI with retries:
                    105: #
                    106: 
                    107: =pod
                    108: 
1.648     raeburn   109: =head1 Server Side include with retries:
1.643     foxr      110: 
                    111: =over 4
                    112: 
1.648     raeburn   113: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      114: 
                    115: Performs an ssi with some number of retries.  Retries continue either
                    116: until the result is ok or until the retry count supplied by the
                    117: caller is exhausted.  
                    118: 
                    119: Inputs:
1.648     raeburn   120: 
                    121: =over 4
                    122: 
1.643     foxr      123: resource   - Identifies the resource to insert.
1.648     raeburn   124: 
1.643     foxr      125: retries    - Count of the number of retries allowed.
1.648     raeburn   126: 
1.643     foxr      127: form       - Hash that identifies the rendering options.
                    128: 
1.648     raeburn   129: =back
                    130: 
                    131: Returns:
                    132: 
                    133: =over 4
                    134: 
1.643     foxr      135: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   136: 
1.643     foxr      137: response   - The response from the last attempt (which may or may not have been successful.
                    138: 
1.648     raeburn   139: =back
                    140: 
                    141: =back
                    142: 
1.643     foxr      143: =cut
                    144: 
                    145: sub ssi_with_retries {
                    146:     my ($resource, $retries, %form) = @_;
                    147: 
                    148: 
                    149:     my $ok = 0;			# True if we got a good response.
                    150:     my $content;
                    151:     my $response;
                    152: 
                    153:     # Try to get the ssi done. within the retries count:
                    154: 
                    155:     do {
                    156: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    157: 	$ok      = $response->is_success;
1.650     www       158:         if (!$ok) {
                    159:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    160:         }
1.643     foxr      161: 	$retries--;
                    162:     } while (!$ok && ($retries > 0));
                    163: 
                    164:     if (!$ok) {
                    165: 	$content = '';		# On error return an empty content.
                    166:     }
                    167:     return ($content, $response);
                    168: 
                    169: }
                    170: 
                    171: 
                    172: 
1.20      www       173: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  174: my %language;
1.124     www       175: my %supported_language;
1.1088    foxr      176: my %supported_codes;
1.1048    foxr      177: my %latex_language;		# For choosing hyphenation in <transl..>
                    178: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  179: my %cprtag;
1.192     taceyjo1  180: my %scprtag;
1.351     www       181: my %fe; my %fd; my %fm;
1.41      ng        182: my %category_extensions;
1.12      harris41  183: 
1.46      matthew   184: # ---------------------------------------------- Thesaurus variables
1.144     matthew   185: #
                    186: # %Keywords:
                    187: #      A hash used by &keyword to determine if a word is considered a keyword.
                    188: # $thesaurus_db_file 
                    189: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   190: 
                    191: my %Keywords;
                    192: my $thesaurus_db_file;
                    193: 
1.144     matthew   194: #
                    195: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    196: # thesaurus.tab, and filecategories.tab.
                    197: #
1.18      www       198: BEGIN {
1.46      matthew   199:     # Variable initialization
                    200:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    201:     #
1.22      www       202:     unless ($readit) {
1.12      harris41  203: # ------------------------------------------------------------------- languages
                    204:     {
1.158     raeburn   205:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    206:                                    '/language.tab';
1.1317    raeburn   207:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  208:             while (my $line = <$fh>) {
                    209:                 next if ($line=~/^\#/);
                    210:                 chomp($line);
1.1088    foxr      211:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   212:                 $language{$key}=$val.' - '.$enc;
                    213:                 if ($sup) {
                    214:                     $supported_language{$key}=$sup;
1.1088    foxr      215: 		    $supported_codes{$key}   = $code;
1.158     raeburn   216:                 }
1.1048    foxr      217: 		if ($latex) {
                    218: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      219: 		    $latex_language{$code} = $latex;
1.1048    foxr      220: 		}
1.158     raeburn   221:             }
                    222:             close($fh);
                    223:         }
1.12      harris41  224:     }
                    225: # ------------------------------------------------------------------ copyrights
                    226:     {
1.158     raeburn   227:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    228:                                   '/copyright.tab';
1.1317    raeburn   229:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  230:             while (my $line = <$fh>) {
                    231:                 next if ($line=~/^\#/);
                    232:                 chomp($line);
                    233:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   234:                 $cprtag{$key}=$val;
                    235:             }
                    236:             close($fh);
                    237:         }
1.12      harris41  238:     }
1.351     www       239: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  240:     {
                    241:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    242:                                   '/source_copyright.tab';
1.1317    raeburn   243:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  244:             while (my $line = <$fh>) {
                    245:                 next if ($line =~ /^\#/);
                    246:                 chomp($line);
                    247:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  248:                 $scprtag{$key}=$val;
                    249:             }
                    250:             close($fh);
                    251:         }
                    252:     }
1.63      www       253: 
1.517     raeburn   254: # -------------------------------------------------------------- default domain designs
1.63      www       255:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   256:     my $designfile = $designdir.'/default.tab';
1.1317    raeburn   257:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   258:         while (my $line = <$fh>) {
                    259:             next if ($line =~ /^\#/);
                    260:             chomp($line);
                    261:             my ($key,$val)=(split(/\=/,$line));
                    262:             if ($val) { $defaultdesign{$key}=$val; }
                    263:         }
                    264:         close($fh);
1.63      www       265:     }
                    266: 
1.15      harris41  267: # ------------------------------------------------------------- file categories
                    268:     {
1.158     raeburn   269:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    270:                                   '/filecategories.tab';
1.1317    raeburn   271:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  272: 	    while (my $line = <$fh>) {
                    273: 		next if ($line =~ /^\#/);
                    274: 		chomp($line);
                    275:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   276:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   277:             }
                    278:             close($fh);
                    279:         }
                    280: 
1.15      harris41  281:     }
1.12      harris41  282: # ------------------------------------------------------------------ file types
                    283:     {
1.158     raeburn   284:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    285:                '/filetypes.tab';
1.1317    raeburn   286:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  287:             while (my $line = <$fh>) {
                    288: 		next if ($line =~ /^\#/);
                    289: 		chomp($line);
                    290:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   291:                 if ($descr ne '') {
                    292:                     $fe{$ending}=lc($emb);
                    293:                     $fd{$ending}=$descr;
1.351     www       294:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   295:                 }
                    296:             }
                    297:             close($fh);
                    298:         }
1.12      harris41  299:     }
1.22      www       300:     &Apache::lonnet::logthis(
1.705     tempelho  301:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       302:     $readit=1;
1.46      matthew   303:     }  # end of unless($readit) 
1.32      matthew   304:     
                    305: }
1.112     bowersj2  306: 
1.42      matthew   307: ###############################################################
                    308: ##           HTML and Javascript Helper Functions            ##
                    309: ###############################################################
                    310: 
                    311: =pod 
                    312: 
1.112     bowersj2  313: =head1 HTML and Javascript Functions
1.42      matthew   314: 
1.112     bowersj2  315: =over 4
                    316: 
1.648     raeburn   317: =item * &browser_and_searcher_javascript()
1.112     bowersj2  318: 
                    319: X<browsing, javascript>X<searching, javascript>Returns a string
                    320: containing javascript with two functions, C<openbrowser> and
                    321: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    322: tags.
1.42      matthew   323: 
1.648     raeburn   324: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   325: 
                    326: inputs: formname, elementname, only, omit
                    327: 
                    328: formname and elementname indicate the name of the html form and name of
                    329: the element that the results of the browsing selection are to be placed in. 
                    330: 
                    331: Specifying 'only' will restrict the browser to displaying only files
1.185     www       332: with the given extension.  Can be a comma separated list.
1.42      matthew   333: 
                    334: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       335: with the given extension.  Can be a comma separated list.
1.42      matthew   336: 
1.648     raeburn   337: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   338: 
                    339: Inputs: formname, elementname
                    340: 
                    341: formname and elementname specify the name of the html form and the name
                    342: of the element the selection from the search results will be placed in.
1.542     raeburn   343: 
1.42      matthew   344: =cut
                    345: 
                    346: sub browser_and_searcher_javascript {
1.199     albertel  347:     my ($mode)=@_;
                    348:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  349:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   350:     return <<END;
1.219     albertel  351: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   352:     var editbrowser = null;
1.135     albertel  353:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       354:         var url = '$resurl/?';
1.42      matthew   355:         if (editbrowser == null) {
                    356:             url += 'launch=1&';
                    357:         }
                    358:         url += 'catalogmode=interactive&';
1.199     albertel  359:         url += 'mode=$mode&';
1.611     albertel  360:         url += 'inhibitmenu=yes&';
1.42      matthew   361:         url += 'form=' + formname + '&';
                    362:         if (only != null) {
                    363:             url += 'only=' + only + '&';
1.217     albertel  364:         } else {
                    365:             url += 'only=&';
                    366: 	}
1.42      matthew   367:         if (omit != null) {
                    368:             url += 'omit=' + omit + '&';
1.217     albertel  369:         } else {
                    370:             url += 'omit=&';
                    371: 	}
1.135     albertel  372:         if (titleelement != null) {
                    373:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  374:         } else {
                    375: 	    url += 'titleelement=&';
                    376: 	}
1.42      matthew   377:         url += 'element=' + elementname + '';
                    378:         var title = 'Browser';
1.435     albertel  379:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   380:         options += ',width=700,height=600';
                    381:         editbrowser = open(url,title,options,'1');
                    382:         editbrowser.focus();
                    383:     }
                    384:     var editsearcher;
1.135     albertel  385:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   386:         var url = '/adm/searchcat?';
                    387:         if (editsearcher == null) {
                    388:             url += 'launch=1&';
                    389:         }
                    390:         url += 'catalogmode=interactive&';
1.199     albertel  391:         url += 'mode=$mode&';
1.42      matthew   392:         url += 'form=' + formname + '&';
1.135     albertel  393:         if (titleelement != null) {
                    394:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  395:         } else {
                    396: 	    url += 'titleelement=&';
                    397: 	}
1.42      matthew   398:         url += 'element=' + elementname + '';
                    399:         var title = 'Search';
1.435     albertel  400:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   401:         options += ',width=700,height=600';
                    402:         editsearcher = open(url,title,options,'1');
                    403:         editsearcher.focus();
                    404:     }
1.219     albertel  405: // END LON-CAPA Internal -->
1.42      matthew   406: END
1.170     www       407: }
                    408: 
                    409: sub lastresurl {
1.258     albertel  410:     if ($env{'environment.lastresurl'}) {
                    411: 	return $env{'environment.lastresurl'}
1.170     www       412:     } else {
                    413: 	return '/res';
                    414:     }
                    415: }
                    416: 
                    417: sub storeresurl {
                    418:     my $resurl=&Apache::lonnet::clutter(shift);
                    419:     unless ($resurl=~/^\/res/) { return 0; }
                    420:     $resurl=~s/\/$//;
                    421:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   422:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       423:     return 1;
1.42      matthew   424: }
                    425: 
1.74      www       426: sub studentbrowser_javascript {
1.111     www       427:    unless (
1.258     albertel  428:             (($env{'request.course.id'}) && 
1.302     albertel  429:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    430: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    431: 					  '/'.$env{'request.course.sec'})
                    432: 	      ))
1.258     albertel  433:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       434:           ) { return ''; }  
1.74      www       435:    return (<<'ENDSTDBRW');
1.776     bisitz    436: <script type="text/javascript" language="Javascript">
1.824     bisitz    437: // <![CDATA[
1.74      www       438:     var stdeditbrowser;
1.999     www       439:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       440:         var url = '/adm/pickstudent?';
                    441:         var filter;
1.558     albertel  442: 	if (!ignorefilter) {
                    443: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    444: 	}
1.74      www       445:         if (filter != null) {
                    446:            if (filter != '') {
                    447:                url += 'filter='+filter+'&';
                    448: 	   }
                    449:         }
                    450:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       451:                                     '&udomelement='+udom+
                    452:                                     '&clicker='+clicker;
1.111     www       453: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   454:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       455:         var title = 'Student_Browser';
1.74      www       456:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    457:         options += ',width=700,height=600';
                    458:         stdeditbrowser = open(url,title,options,'1');
                    459:         stdeditbrowser.focus();
                    460:     }
1.824     bisitz    461: // ]]>
1.74      www       462: </script>
                    463: ENDSTDBRW
                    464: }
1.42      matthew   465: 
1.1003    www       466: sub resourcebrowser_javascript {
                    467:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       468:    return (<<'ENDRESBRW');
1.1003    www       469: <script type="text/javascript" language="Javascript">
                    470: // <![CDATA[
                    471:     var reseditbrowser;
1.1004    www       472:     function openresbrowser(formname,reslink) {
1.1005    www       473:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       474:         var title = 'Resource_Browser';
                    475:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       476:         options += ',width=700,height=500';
1.1004    www       477:         reseditbrowser = open(url,title,options,'1');
                    478:         reseditbrowser.focus();
1.1003    www       479:     }
                    480: // ]]>
                    481: </script>
1.1004    www       482: ENDRESBRW
1.1003    www       483: }
                    484: 
1.74      www       485: sub selectstudent_link {
1.999     www       486:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    487:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    488:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    489:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  490:    if ($env{'request.course.id'}) {  
1.302     albertel  491:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    492: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    493: 					'/'.$env{'request.course.sec'})) {
1.111     www       494: 	   return '';
                    495:        }
1.999     www       496:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   497:        if ($courseadvonly)  {
                    498:            $callargs .= ",'',1,1";
                    499:        }
                    500:        return '<span class="LC_nobreak">'.
                    501:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    502:               &mt('Select User').'</a></span>';
1.74      www       503:    }
1.258     albertel  504:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       505:        $callargs .= ",'',1"; 
1.793     raeburn   506:        return '<span class="LC_nobreak">'.
                    507:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    508:               &mt('Select User').'</a></span>';
1.111     www       509:    }
                    510:    return '';
1.91      www       511: }
                    512: 
1.1004    www       513: sub selectresource_link {
                    514:    my ($form,$reslink,$arg)=@_;
                    515:    
                    516:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    517:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    518:    unless ($env{'request.course.id'}) { return $arg; }
                    519:    return '<span class="LC_nobreak">'.
                    520:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    521:               $arg.'</a></span>';
                    522: }
                    523: 
                    524: 
                    525: 
1.653     raeburn   526: sub authorbrowser_javascript {
                    527:     return <<"ENDAUTHORBRW";
1.776     bisitz    528: <script type="text/javascript" language="JavaScript">
1.824     bisitz    529: // <![CDATA[
1.653     raeburn   530: var stdeditbrowser;
                    531: 
                    532: function openauthorbrowser(formname,udom) {
                    533:     var url = '/adm/pickauthor?';
                    534:     url += 'form='+formname+'&roledom='+udom;
                    535:     var title = 'Author_Browser';
                    536:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    537:     options += ',width=700,height=600';
                    538:     stdeditbrowser = open(url,title,options,'1');
                    539:     stdeditbrowser.focus();
                    540: }
                    541: 
1.824     bisitz    542: // ]]>
1.653     raeburn   543: </script>
                    544: ENDAUTHORBRW
                    545: }
                    546: 
1.91      www       547: sub coursebrowser_javascript {
1.1116    raeburn   548:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   549:         $credits_element,$instcode) = @_;
1.932     raeburn   550:     my $wintitle = 'Course_Browser';
1.931     raeburn   551:     if ($crstype eq 'Community') {
1.932     raeburn   552:         $wintitle = 'Community_Browser';
1.909     raeburn   553:     }
1.876     raeburn   554:     my $id_functions = &javascript_index_functions();
                    555:     my $output = '
1.776     bisitz    556: <script type="text/javascript" language="JavaScript">
1.824     bisitz    557: // <![CDATA[
1.468     raeburn   558:     var stdeditbrowser;'."\n";
1.876     raeburn   559: 
                    560:     $output .= <<"ENDSTDBRW";
1.909     raeburn   561:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       562:         var url = '/adm/pickcourse?';
1.895     raeburn   563:         var formid = getFormIdByName(formname);
1.876     raeburn   564:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  565:         if (domainfilter != null) {
                    566:            if (domainfilter != '') {
                    567:                url += 'domainfilter='+domainfilter+'&';
                    568: 	   }
                    569:         }
1.91      www       570:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  571: 	                            '&cdomelement='+udom+
                    572:                                     '&cnameelement='+desc;
1.468     raeburn   573:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   574:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   575:                 url += '&roleelement='+extra_element;
                    576:                 if (domainfilter == null || domainfilter == '') {
                    577:                     url += '&domainfilter='+extra_element;
                    578:                 }
1.234     raeburn   579:             }
1.468     raeburn   580:             else {
                    581:                 if (formname == 'portform') {
                    582:                     url += '&setroles='+extra_element;
1.800     raeburn   583:                 } else {
                    584:                     if (formname == 'rules') {
                    585:                         url += '&fixeddom='+extra_element; 
                    586:                     }
1.468     raeburn   587:                 }
                    588:             }     
1.230     raeburn   589:         }
1.909     raeburn   590:         if (type != null && type != '') {
                    591:             url += '&type='+type;
                    592:         }
                    593:         if (type_elem != null && type_elem != '') {
                    594:             url += '&typeelement='+type_elem;
                    595:         }
1.872     raeburn   596:         if (formname == 'ccrs') {
                    597:             var ownername = document.forms[formid].ccuname.value;
                    598:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   599:             url += '&cloner='+ownername+':'+ownerdom;
                    600:             if (type == 'Course') {
                    601:                 url += '&crscode='+document.forms[formid].crscode.value;
                    602:             }
1.1221    raeburn   603:         }
                    604:         if (formname == 'requestcrs') {
                    605:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   606:         }
1.293     raeburn   607:         if (multflag !=null && multflag != '') {
                    608:             url += '&multiple='+multflag;
                    609:         }
1.909     raeburn   610:         var title = '$wintitle';
1.91      www       611:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    612:         options += ',width=700,height=600';
                    613:         stdeditbrowser = open(url,title,options,'1');
                    614:         stdeditbrowser.focus();
                    615:     }
1.876     raeburn   616: $id_functions
                    617: ENDSTDBRW
1.1116    raeburn   618:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    619:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    620:                                       $credits_element);
1.876     raeburn   621:     }
                    622:     $output .= '
                    623: // ]]>
                    624: </script>';
                    625:     return $output;
                    626: }
                    627: 
                    628: sub javascript_index_functions {
                    629:     return <<"ENDJS";
                    630: 
                    631: function getFormIdByName(formname) {
                    632:     for (var i=0;i<document.forms.length;i++) {
                    633:         if (document.forms[i].name == formname) {
                    634:             return i;
                    635:         }
                    636:     }
                    637:     return -1;
                    638: }
                    639: 
                    640: function getIndexByName(formid,item) {
                    641:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    642:         if (document.forms[formid].elements[i].name == item) {
                    643:             return i;
                    644:         }
                    645:     }
                    646:     return -1;
                    647: }
1.468     raeburn   648: 
1.876     raeburn   649: function getDomainFromSelectbox(formname,udom) {
                    650:     var userdom;
                    651:     var formid = getFormIdByName(formname);
                    652:     if (formid > -1) {
                    653:         var domid = getIndexByName(formid,udom);
                    654:         if (domid > -1) {
                    655:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    656:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    657:             }
                    658:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    659:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   660:             }
                    661:         }
                    662:     }
1.876     raeburn   663:     return userdom;
                    664: }
                    665: 
                    666: ENDJS
1.468     raeburn   667: 
1.876     raeburn   668: }
                    669: 
1.1017    raeburn   670: sub javascript_array_indexof {
1.1018    raeburn   671:     return <<ENDJS;
1.1017    raeburn   672: <script type="text/javascript" language="JavaScript">
                    673: // <![CDATA[
                    674: 
                    675: if (!Array.prototype.indexOf) {
                    676:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    677:         "use strict";
                    678:         if (this === void 0 || this === null) {
                    679:             throw new TypeError();
                    680:         }
                    681:         var t = Object(this);
                    682:         var len = t.length >>> 0;
                    683:         if (len === 0) {
                    684:             return -1;
                    685:         }
                    686:         var n = 0;
                    687:         if (arguments.length > 0) {
                    688:             n = Number(arguments[1]);
1.1088    foxr      689:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   690:                 n = 0;
                    691:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    692:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    693:             }
                    694:         }
                    695:         if (n >= len) {
                    696:             return -1;
                    697:         }
                    698:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    699:         for (; k < len; k++) {
                    700:             if (k in t && t[k] === searchElement) {
                    701:                 return k;
                    702:             }
                    703:         }
                    704:         return -1;
                    705:     }
                    706: }
                    707: 
                    708: // ]]>
                    709: </script>
                    710: 
                    711: ENDJS
                    712: 
                    713: }
                    714: 
1.876     raeburn   715: sub userbrowser_javascript {
                    716:     my $id_functions = &javascript_index_functions();
                    717:     return <<"ENDUSERBRW";
                    718: 
1.888     raeburn   719: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   720:     var url = '/adm/pickuser?';
                    721:     var userdom = getDomainFromSelectbox(formname,udom);
                    722:     if (userdom != null) {
                    723:        if (userdom != '') {
                    724:            url += 'srchdom='+userdom+'&';
                    725:        }
                    726:     }
                    727:     url += 'form=' + formname + '&unameelement='+uname+
                    728:                                 '&udomelement='+udom+
                    729:                                 '&ulastelement='+ulast+
                    730:                                 '&ufirstelement='+ufirst+
                    731:                                 '&uemailelement='+uemail+
1.881     raeburn   732:                                 '&hideudomelement='+hideudom+
                    733:                                 '&coursedom='+crsdom;
1.888     raeburn   734:     if ((caller != null) && (caller != undefined)) {
                    735:         url += '&caller='+caller;
                    736:     }
1.876     raeburn   737:     var title = 'User_Browser';
                    738:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    739:     options += ',width=700,height=600';
                    740:     var stdeditbrowser = open(url,title,options,'1');
                    741:     stdeditbrowser.focus();
                    742: }
                    743: 
1.888     raeburn   744: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   745:     var formid = getFormIdByName(formname);
                    746:     if (formid > -1) {
1.888     raeburn   747:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   748:         var domid = getIndexByName(formid,udom);
                    749:         var hidedomid = getIndexByName(formid,origdom);
                    750:         if (hidedomid > -1) {
                    751:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   752:             var unameval = document.forms[formid].elements[unameid].value;
                    753:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    754:                 if (domid > -1) {
                    755:                     var slct = document.forms[formid].elements[domid];
                    756:                     if (slct.type == 'select-one') {
                    757:                         var i;
                    758:                         for (i=0;i<slct.length;i++) {
                    759:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    760:                         }
                    761:                     }
                    762:                     if (slct.type == 'hidden') {
                    763:                         slct.value = fixeddom;
1.876     raeburn   764:                     }
                    765:                 }
1.468     raeburn   766:             }
                    767:         }
                    768:     }
1.876     raeburn   769:     return;
                    770: }
                    771: 
                    772: $id_functions
                    773: ENDUSERBRW
1.468     raeburn   774: }
                    775: 
                    776: sub setsec_javascript {
1.1116    raeburn   777:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   778:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    779:         $communityrolestr);
                    780:     if ($role_element ne '') {
                    781:         my @allroles = ('st','ta','ep','in','ad');
                    782:         foreach my $crstype ('Course','Community') {
                    783:             if ($crstype eq 'Community') {
                    784:                 foreach my $role (@allroles) {
                    785:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    786:                 }
                    787:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    788:             } else {
                    789:                 foreach my $role (@allroles) {
                    790:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    791:                 }
                    792:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    793:             }
                    794:         }
                    795:         $rolestr = '"'.join('","',@allroles).'"';
                    796:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    797:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    798:     }
1.468     raeburn   799:     my $setsections = qq|
                    800: function setSect(sectionlist) {
1.629     raeburn   801:     var sectionsArray = new Array();
                    802:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    803:         sectionsArray = sectionlist.split(",");
                    804:     }
1.468     raeburn   805:     var numSections = sectionsArray.length;
                    806:     document.$formname.$sec_element.length = 0;
                    807:     if (numSections == 0) {
                    808:         document.$formname.$sec_element.multiple=false;
                    809:         document.$formname.$sec_element.size=1;
                    810:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    811:     } else {
                    812:         if (numSections == 1) {
                    813:             document.$formname.$sec_element.multiple=false;
                    814:             document.$formname.$sec_element.size=1;
                    815:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    816:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    817:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    818:         } else {
                    819:             for (var i=0; i<numSections; i++) {
                    820:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    821:             }
                    822:             document.$formname.$sec_element.multiple=true
                    823:             if (numSections < 3) {
                    824:                 document.$formname.$sec_element.size=numSections;
                    825:             } else {
                    826:                 document.$formname.$sec_element.size=3;
                    827:             }
                    828:             document.$formname.$sec_element.options[0].selected = false
                    829:         }
                    830:     }
1.91      www       831: }
1.905     raeburn   832: 
                    833: function setRole(crstype) {
1.468     raeburn   834: |;
1.905     raeburn   835:     if ($role_element eq '') {
                    836:         $setsections .= '    return;
                    837: }
                    838: ';
                    839:     } else {
                    840:         $setsections .= qq|
                    841:     var elementLength = document.$formname.$role_element.length;
                    842:     var allroles = Array($rolestr);
                    843:     var courserolenames = Array($courserolestr);
                    844:     var communityrolenames = Array($communityrolestr);
                    845:     if (elementLength != undefined) {
                    846:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    847:             if (crstype == 'Course') {
                    848:                 return;
                    849:             } else {
                    850:                 allroles[5] = 'co';
                    851:                 for (var i=0; i<6; i++) {
                    852:                     document.$formname.$role_element.options[i].value = allroles[i];
                    853:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    854:                 }
                    855:             }
                    856:         } else {
                    857:             if (crstype == 'Community') {
                    858:                 return;
                    859:             } else {
                    860:                 allroles[5] = 'cc';
                    861:                 for (var i=0; i<6; i++) {
                    862:                     document.$formname.$role_element.options[i].value = allroles[i];
                    863:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    864:                 }
                    865:             }
                    866:         }
                    867:     }
                    868:     return;
                    869: }
                    870: |;
                    871:     }
1.1116    raeburn   872:     if ($credits_element) {
                    873:         $setsections .= qq|
                    874: function setCredits(defaultcredits) {
                    875:     document.$formname.$credits_element.value = defaultcredits;
                    876:     return;
                    877: }
                    878: |;
                    879:     }
1.468     raeburn   880:     return $setsections;
                    881: }
                    882: 
1.91      www       883: sub selectcourse_link {
1.909     raeburn   884:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    885:        $typeelement) = @_;
                    886:    my $type = $selecttype;
1.871     raeburn   887:    my $linktext = &mt('Select Course');
                    888:    if ($selecttype eq 'Community') {
1.909     raeburn   889:        $linktext = &mt('Select Community');
1.1239    raeburn   890:    } elsif ($selecttype eq 'Placement') {
                    891:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   892:    } elsif ($selecttype eq 'Course/Community') {
                    893:        $linktext = &mt('Select Course/Community');
1.909     raeburn   894:        $type = '';
1.1019    raeburn   895:    } elsif ($selecttype eq 'Select') {
                    896:        $linktext = &mt('Select');
                    897:        $type = '';
1.871     raeburn   898:    }
1.787     bisitz    899:    return '<span class="LC_nobreak">'
                    900:          ."<a href='"
                    901:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    902:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   903:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   904:          ."'>".$linktext.'</a>'
1.787     bisitz    905:          .'</span>';
1.74      www       906: }
1.42      matthew   907: 
1.653     raeburn   908: sub selectauthor_link {
                    909:    my ($form,$udom)=@_;
                    910:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    911:           &mt('Select Author').'</a>';
                    912: }
                    913: 
1.876     raeburn   914: sub selectuser_link {
1.881     raeburn   915:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   916:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   917:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   918:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   919:            ');">'.$linktext.'</a>';
1.876     raeburn   920: }
                    921: 
1.273     raeburn   922: sub check_uncheck_jscript {
                    923:     my $jscript = <<"ENDSCRT";
                    924: function checkAll(field) {
                    925:     if (field.length > 0) {
                    926:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   927:             if (!field[i].disabled) { 
                    928:                 field[i].checked = true;
                    929:             }
1.273     raeburn   930:         }
                    931:     } else {
1.1093    raeburn   932:         if (!field.disabled) { 
                    933:             field.checked = true;
                    934:         }
1.273     raeburn   935:     }
                    936: }
                    937:  
                    938: function uncheckAll(field) {
                    939:     if (field.length > 0) {
                    940:         for (i = 0; i < field.length; i++) {
                    941:             field[i].checked = false ;
1.543     albertel  942:         }
                    943:     } else {
1.273     raeburn   944:         field.checked = false ;
                    945:     }
                    946: }
                    947: ENDSCRT
                    948:     return $jscript;
                    949: }
                    950: 
1.656     www       951: sub select_timezone {
1.1256    raeburn   952:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    953:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   954:    if ($includeempty) {
                    955:        $output .= '<option value=""';
                    956:        if (($selected eq '') || ($selected eq 'local')) {
                    957:            $output .= ' selected="selected" ';
                    958:        }
                    959:        $output .= '> </option>';
                    960:    }
1.657     raeburn   961:    my @timezones = DateTime::TimeZone->all_names;
                    962:    foreach my $tzone (@timezones) {
                    963:        $output.= '<option value="'.$tzone.'"';
                    964:        if ($tzone eq $selected) {
                    965:            $output.=' selected="selected"';
                    966:        }
                    967:        $output.=">$tzone</option>\n";
1.656     www       968:    }
                    969:    $output.="</select>";
                    970:    return $output;
                    971: }
1.273     raeburn   972: 
1.687     raeburn   973: sub select_datelocale {
1.1256    raeburn   974:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    975:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   976:     if ($includeempty) {
                    977:         $output .= '<option value=""';
                    978:         if ($selected eq '') {
                    979:             $output .= ' selected="selected" ';
                    980:         }
                    981:         $output .= '> </option>';
                    982:     }
1.1241    raeburn   983:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   984:     my (@possibles,%locale_names);
1.1241    raeburn   985:     my @locales = DateTime::Locale->ids();
                    986:     foreach my $id (@locales) {
                    987:         if ($id ne '') {
                    988:             my ($en_terr,$native_terr);
                    989:             my $loc = DateTime::Locale->load($id);
                    990:             if (ref($loc)) {
                    991:                 $en_terr = $loc->name();
                    992:                 $native_terr = $loc->native_name();
1.687     raeburn   993:                 if (grep(/^en$/,@languages) || !@languages) {
                    994:                     if ($en_terr ne '') {
                    995:                         $locale_names{$id} = '('.$en_terr.')';
                    996:                     } elsif ($native_terr ne '') {
                    997:                         $locale_names{$id} = $native_terr;
                    998:                     }
                    999:                 } else {
                   1000:                     if ($native_terr ne '') {
                   1001:                         $locale_names{$id} = $native_terr.' ';
                   1002:                     } elsif ($en_terr ne '') {
                   1003:                         $locale_names{$id} = '('.$en_terr.')';
                   1004:                     }
                   1005:                 }
1.1220    raeburn  1006:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1007:                 push(@possibles,$id);
                   1008:             } 
1.687     raeburn  1009:         }
                   1010:     }
                   1011:     foreach my $item (sort(@possibles)) {
                   1012:         $output.= '<option value="'.$item.'"';
                   1013:         if ($item eq $selected) {
                   1014:             $output.=' selected="selected"';
                   1015:         }
                   1016:         $output.=">$item";
                   1017:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1018:             $output.='  '.$locale_names{$item};
1.687     raeburn  1019:         }
                   1020:         $output.="</option>\n";
                   1021:     }
                   1022:     $output.="</select>";
                   1023:     return $output;
                   1024: }
                   1025: 
1.792     raeburn  1026: sub select_language {
1.1256    raeburn  1027:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1028:     my %langchoices;
                   1029:     if ($includeempty) {
1.1117    raeburn  1030:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1031:     }
                   1032:     foreach my $id (&languageids()) {
                   1033:         my $code = &supportedlanguagecode($id);
                   1034:         if ($code) {
                   1035:             $langchoices{$code} = &plainlanguagedescription($id);
                   1036:         }
                   1037:     }
1.1117    raeburn  1038:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1039:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1040: }
                   1041: 
1.42      matthew  1042: =pod
1.36      matthew  1043: 
1.1088    foxr     1044: 
                   1045: =item * &list_languages()
                   1046: 
                   1047: Returns an array reference that is suitable for use in language prompters.
                   1048: Each array element is itself a two element array.  The first element
                   1049: is the language code.  The second element a descsriptiuon of the 
                   1050: language itself.  This is suitable for use in e.g.
                   1051: &Apache::edit::select_arg (once dereferenced that is).
                   1052: 
                   1053: =cut 
                   1054: 
                   1055: sub list_languages {
                   1056:     my @lang_choices;
                   1057: 
                   1058:     foreach my $id (&languageids()) {
                   1059: 	my $code = &supportedlanguagecode($id);
                   1060: 	if ($code) {
                   1061: 	    my $selector    = $supported_codes{$id};
                   1062: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1063: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1064: 	}
                   1065:     }
                   1066:     return \@lang_choices;
                   1067: }
                   1068: 
                   1069: =pod
                   1070: 
1.648     raeburn  1071: =item * &linked_select_forms(...)
1.36      matthew  1072: 
                   1073: linked_select_forms returns a string containing a <script></script> block
                   1074: and html for two <select> menus.  The select menus will be linked in that
                   1075: changing the value of the first menu will result in new values being placed
                   1076: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1077: order unless a defined order is provided.
1.36      matthew  1078: 
                   1079: linked_select_forms takes the following ordered inputs:
                   1080: 
                   1081: =over 4
                   1082: 
1.112     bowersj2 1083: =item * $formname, the name of the <form> tag
1.36      matthew  1084: 
1.112     bowersj2 1085: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1086: 
1.112     bowersj2 1087: =item * $firstdefault, the default value for the first menu
1.36      matthew  1088: 
1.112     bowersj2 1089: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1090: 
1.112     bowersj2 1091: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1092: 
1.112     bowersj2 1093: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1094: 
1.609     raeburn  1095: =item * $menuorder, the order of values in the first menu
                   1096: 
1.1115    raeburn  1097: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1098:         event for the first <select> tag
                   1099: 
                   1100: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1101:         event for the second <select> tag
                   1102: 
1.1245    raeburn  1103: =item * $suffix, to differentiate separate uses of select2data javascript
                   1104:         objects in a page.
                   1105: 
1.41      ng       1106: =back 
                   1107: 
1.36      matthew  1108: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1109: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1110: values for the first select menu.  The text that coincides with the 
1.41      ng       1111: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1112: and text for the second menu are given in the hash pointed to by 
                   1113: $menu{$choice1}->{'select2'}.  
                   1114: 
1.112     bowersj2 1115:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1116:                        default => "B3",
                   1117:                        select2 => { 
                   1118:                            B1 => "Choice B1",
                   1119:                            B2 => "Choice B2",
                   1120:                            B3 => "Choice B3",
                   1121:                            B4 => "Choice B4"
1.609     raeburn  1122:                            },
                   1123:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1124:                    },
                   1125:                A2 => { text =>"Choice A2" ,
                   1126:                        default => "C2",
                   1127:                        select2 => { 
                   1128:                            C1 => "Choice C1",
                   1129:                            C2 => "Choice C2",
                   1130:                            C3 => "Choice C3"
1.609     raeburn  1131:                            },
                   1132:                        order => ['C2','C1','C3'],
1.112     bowersj2 1133:                    },
                   1134:                A3 => { text =>"Choice A3" ,
                   1135:                        default => "D6",
                   1136:                        select2 => { 
                   1137:                            D1 => "Choice D1",
                   1138:                            D2 => "Choice D2",
                   1139:                            D3 => "Choice D3",
                   1140:                            D4 => "Choice D4",
                   1141:                            D5 => "Choice D5",
                   1142:                            D6 => "Choice D6",
                   1143:                            D7 => "Choice D7"
1.609     raeburn  1144:                            },
                   1145:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1146:                    }
                   1147:                );
1.36      matthew  1148: 
                   1149: =cut
                   1150: 
                   1151: sub linked_select_forms {
                   1152:     my ($formname,
                   1153:         $middletext,
                   1154:         $firstdefault,
                   1155:         $firstselectname,
                   1156:         $secondselectname, 
1.609     raeburn  1157:         $hashref,
                   1158:         $menuorder,
1.1115    raeburn  1159:         $onchangefirst,
1.1245    raeburn  1160:         $onchangesecond,
                   1161:         $suffix
1.36      matthew  1162:         ) = @_;
                   1163:     my $second = "document.$formname.$secondselectname";
                   1164:     my $first = "document.$formname.$firstselectname";
                   1165:     # output the javascript to do the changing
                   1166:     my $result = '';
1.776     bisitz   1167:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1168:     $result.="// <![CDATA[\n";
1.1245    raeburn  1169:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1170:     $" = '","';
                   1171:     my $debug = '';
                   1172:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1173:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1174:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1175:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1176:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1177:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1178:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1179:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1180:         }
1.36      matthew  1181:         $result.="\"@s2values\");\n";
1.1245    raeburn  1182:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1183:         my @s2texts;
                   1184:         foreach my $value (@s2values) {
1.1263    raeburn  1185:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1186:         }
                   1187:         $result.="\"@s2texts\");\n";
                   1188:     }
                   1189:     $"=' ';
                   1190:     $result.= <<"END";
                   1191: 
1.1245    raeburn  1192: function select1${suffix}_changed() {
1.36      matthew  1193:     // Determine new choice
1.1245    raeburn  1194:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1195:     // update select2
1.1245    raeburn  1196:     var values     = select2data${suffix}[newvalue].values;
                   1197:     var texts      = select2data${suffix}[newvalue].texts;
                   1198:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1199:     var i;
                   1200:     // out with the old
1.1245    raeburn  1201:     $second.options.length = 0;
                   1202:     // in with the new
1.36      matthew  1203:     for (i=0;i<values.length; i++) {
                   1204:         $second.options[i] = new Option(values[i]);
1.143     matthew  1205:         $second.options[i].value = values[i];
1.36      matthew  1206:         $second.options[i].text = texts[i];
                   1207:         if (values[i] == select2def) {
                   1208:             $second.options[i].selected = true;
                   1209:         }
                   1210:     }
                   1211: }
1.824     bisitz   1212: // ]]>
1.36      matthew  1213: </script>
                   1214: END
                   1215:     # output the initial values for the selection lists
1.1245    raeburn  1216:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1217:     my @order = sort(keys(%{$hashref}));
                   1218:     if (ref($menuorder) eq 'ARRAY') {
                   1219:         @order = @{$menuorder};
                   1220:     }
                   1221:     foreach my $value (@order) {
1.36      matthew  1222:         $result.="    <option value=\"$value\" ";
1.253     albertel 1223:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1224:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1225:     }
                   1226:     $result .= "</select>\n";
                   1227:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1228:     $result .= $middletext;
1.1115    raeburn  1229:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1230:     if ($onchangesecond) {
                   1231:         $result .= ' onchange="'.$onchangesecond.'"';
                   1232:     }
                   1233:     $result .= ">\n";
1.36      matthew  1234:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1235:     
                   1236:     my @secondorder = sort(keys(%select2));
                   1237:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1238:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1239:     }
                   1240:     foreach my $value (@secondorder) {
1.36      matthew  1241:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1242:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1243:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1244:     }
                   1245:     $result .= "</select>\n";
                   1246:     #    return $debug;
                   1247:     return $result;
                   1248: }   #  end of sub linked_select_forms {
                   1249: 
1.45      matthew  1250: =pod
1.44      bowersj2 1251: 
1.973     raeburn  1252: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1253: 
1.112     bowersj2 1254: Returns a string corresponding to an HTML link to the given help
                   1255: $topic, where $topic corresponds to the name of a .tex file in
                   1256: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1257: spaces. 
                   1258: 
                   1259: $text will optionally be linked to the same topic, allowing you to
                   1260: link text in addition to the graphic. If you do not want to link
                   1261: text, but wish to specify one of the later parameters, pass an
                   1262: empty string. 
                   1263: 
                   1264: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1265: the link will not open a new window. If false, the link will open
                   1266: a new window using Javascript. (Default is false.) 
                   1267: 
                   1268: $width and $height are optional numerical parameters that will
                   1269: override the width and height of the popped up window, which may
1.973     raeburn  1270: be useful for certain help topics with big pictures included.
                   1271: 
                   1272: $imgid is the id of the img tag used for the help icon. This may be
                   1273: used in a javascript call to switch the image src.  See 
                   1274: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1275: 
                   1276: =cut
                   1277: 
                   1278: sub help_open_topic {
1.973     raeburn  1279:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1280:     $text = "" if (not defined $text);
1.44      bowersj2 1281:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1282:     $width = 500 if (not defined $width);
1.44      bowersj2 1283:     $height = 400 if (not defined $height);
                   1284:     my $filename = $topic;
                   1285:     $filename =~ s/ /_/g;
                   1286: 
1.48      bowersj2 1287:     my $template = "";
                   1288:     my $link;
1.572     banghart 1289:     
1.159     www      1290:     $topic=~s/\W/\_/g;
1.44      bowersj2 1291: 
1.572     banghart 1292:     if (!$stayOnPage) {
1.1033    www      1293: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1294:     } elsif ($stayOnPage eq 'popup') {
                   1295:         $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 1296:     } else {
1.48      bowersj2 1297: 	$link = "/adm/help/${filename}.hlp";
                   1298:     }
                   1299: 
                   1300:     # Add the text
1.1314    raeburn  1301:     my $target = ' target="_top"';
                   1302:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1303:         $target = '';
                   1304:     }
1.755     neumanie 1305:     if ($text ne "") {	
1.763     bisitz   1306: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1307:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1308:                   .$text.'</a>';
1.48      bowersj2 1309:     }
                   1310: 
1.763     bisitz   1311:     # (Always) Add the graphic
1.179     matthew  1312:     my $title = &mt('Online Help');
1.667     raeburn  1313:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1314:     if ($imgid ne '') {
                   1315:         $imgid = ' id="'.$imgid.'"';
                   1316:     }
1.1314    raeburn  1317:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1318:               .'<img src="'.$helpicon.'" border="0"'
                   1319:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1320:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1321:               .' /></a>';
                   1322:     if ($text ne "") {	
                   1323:         $template.='</span>';
                   1324:     }
1.44      bowersj2 1325:     return $template;
                   1326: 
1.106     bowersj2 1327: }
                   1328: 
                   1329: # This is a quicky function for Latex cheatsheet editing, since it 
                   1330: # appears in at least four places
                   1331: sub helpLatexCheatsheet {
1.1037    www      1332:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1333:     my $out;
1.106     bowersj2 1334:     my $addOther = '';
1.732     raeburn  1335:     if ($topic) {
1.1037    www      1336: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1337:     }
                   1338:     $out = '<span>' # Start cheatsheet
                   1339: 	  .$addOther
                   1340:           .'<span>'
1.1037    www      1341: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1342: 	  .'</span> <span>'
1.1037    www      1343: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1344: 	  .'</span>';
1.732     raeburn  1345:     unless ($not_author) {
1.1186    kruse    1346:         $out .= '<span>'
                   1347:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1348:                .'</span> <span>'
                   1349:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1350: 	       .'</span>';
1.732     raeburn  1351:     }
1.763     bisitz   1352:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1353:     return $out;
1.172     www      1354: }
                   1355: 
1.430     albertel 1356: sub general_help {
                   1357:     my $helptopic='Student_Intro';
                   1358:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1359: 	$helptopic='Authoring_Intro';
1.907     raeburn  1360:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1361: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1362:     } elsif ($env{'request.role'}=~/^dc/) {
                   1363:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1364:     }
                   1365:     return $helptopic;
                   1366: }
                   1367: 
                   1368: sub update_help_link {
                   1369:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1370:     my $origurl = $ENV{'REQUEST_URI'};
                   1371:     $origurl=~s|^/~|/priv/|;
                   1372:     my $timestamp = time;
                   1373:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1374:         $$datum = &escape($$datum);
                   1375:     }
                   1376: 
                   1377:     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";
                   1378:     my $output .= <<"ENDOUTPUT";
                   1379: <script type="text/javascript">
1.824     bisitz   1380: // <![CDATA[
1.430     albertel 1381: banner_link = '$banner_link';
1.824     bisitz   1382: // ]]>
1.430     albertel 1383: </script>
                   1384: ENDOUTPUT
                   1385:     return $output;
                   1386: }
                   1387: 
                   1388: # now just updates the help link and generates a blue icon
1.193     raeburn  1389: sub help_open_menu {
1.430     albertel 1390:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1391: 	= @_;    
1.949     droeschl 1392:     $stayOnPage = 1;
1.430     albertel 1393:     my $output;
                   1394:     if ($component_help) {
                   1395: 	if (!$text) {
                   1396: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1397: 				       $width,$height);
                   1398: 	} else {
                   1399: 	    my $help_text;
                   1400: 	    $help_text=&unescape($topic);
                   1401: 	    $output='<table><tr><td>'.
                   1402: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1403: 				 $width,$height).'</td></tr></table>';
                   1404: 	}
                   1405:     }
                   1406:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1407:     return $output.$banner_link;
                   1408: }
                   1409: 
                   1410: sub top_nav_help {
                   1411:     my ($text) = @_;
1.436     albertel 1412:     $text = &mt($text);
1.949     droeschl 1413:     my $stay_on_page = 1;
                   1414: 
1.1168    raeburn  1415:     my ($link,$banner_link);
                   1416:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1417:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1418: 	                         : "javascript:helpMenu('open')";
                   1419:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1420:     }
1.201     raeburn  1421:     my $title = &mt('Get help');
1.1168    raeburn  1422:     if ($link) {
                   1423:         return <<"END";
1.436     albertel 1424: $banner_link
1.1159    raeburn  1425: <a href="$link" title="$title">$text</a>
1.436     albertel 1426: END
1.1168    raeburn  1427:     } else {
                   1428:         return '&nbsp;'.$text.'&nbsp;';
                   1429:     }
1.436     albertel 1430: }
                   1431: 
                   1432: sub help_menu_js {
1.1154    raeburn  1433:     my ($httphost) = @_;
1.949     droeschl 1434:     my $stayOnPage = 1;
1.436     albertel 1435:     my $width = 620;
                   1436:     my $height = 600;
1.430     albertel 1437:     my $helptopic=&general_help();
1.1154    raeburn  1438:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1439:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1440:     my $start_page =
                   1441:         &Apache::loncommon::start_page('Help Menu', undef,
                   1442: 				       {'frameset'    => 1,
                   1443: 					'js_ready'    => 1,
1.1154    raeburn  1444:                                         'use_absolute' => $httphost,
1.331     albertel 1445: 					'add_entries' => {
1.1168    raeburn  1446: 					    'border' => '0', 
1.579     raeburn  1447: 					    'rows'   => "110,*",},});
1.331     albertel 1448:     my $end_page =
                   1449:         &Apache::loncommon::end_page({'frameset' => 1,
                   1450: 				      'js_ready' => 1,});
                   1451: 
1.436     albertel 1452:     my $template .= <<"ENDTEMPLATE";
                   1453: <script type="text/javascript">
1.877     bisitz   1454: // <![CDATA[
1.253     albertel 1455: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1456: var banner_link = '';
1.243     raeburn  1457: function helpMenu(target) {
                   1458:     var caller = this;
                   1459:     if (target == 'open') {
                   1460:         var newWindow = null;
                   1461:         try {
1.262     albertel 1462:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1463:         }
                   1464:         catch(error) {
                   1465:             writeHelp(caller);
                   1466:             return;
                   1467:         }
                   1468:         if (newWindow) {
                   1469:             caller = newWindow;
                   1470:         }
1.193     raeburn  1471:     }
1.243     raeburn  1472:     writeHelp(caller);
                   1473:     return;
                   1474: }
                   1475: function writeHelp(caller) {
1.1168    raeburn  1476:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1477:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1478:     caller.document.close();
                   1479:     caller.focus();
1.193     raeburn  1480: }
1.877     bisitz   1481: // END LON-CAPA Internal -->
1.253     albertel 1482: // ]]>
1.436     albertel 1483: </script>
1.193     raeburn  1484: ENDTEMPLATE
                   1485:     return $template;
                   1486: }
                   1487: 
1.172     www      1488: sub help_open_bug {
                   1489:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1490:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1491:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1492:     $text = "" if (not defined $text);
                   1493: 	$stayOnPage=1;
1.184     albertel 1494:     $width = 600 if (not defined $width);
                   1495:     $height = 600 if (not defined $height);
1.172     www      1496: 
                   1497:     $topic=~s/\W+/\+/g;
                   1498:     my $link='';
                   1499:     my $template='';
1.379     albertel 1500:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1501: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1502:     if (!$stayOnPage)
                   1503:     {
                   1504: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1505:     }
                   1506:     else
                   1507:     {
                   1508: 	$link = $url;
                   1509:     }
1.1314    raeburn  1510: 
                   1511:     my $target = ' target="_top"';
                   1512:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1513:         $target = '';
                   1514:     }
1.172     www      1515:     # Add the text
                   1516:     if ($text ne "")
                   1517:     {
                   1518: 	$template .= 
                   1519:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1314    raeburn  1520:   "<td bgcolor='#FF5555'><a".$target." href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1521:     }
                   1522: 
                   1523:     # Add the graphic
1.179     matthew  1524:     my $title = &mt('Report a Bug');
1.215     albertel 1525:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1526:     $template .= <<"ENDTEMPLATE";
1.1314    raeburn  1527:  <a$target href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1528: ENDTEMPLATE
                   1529:     if ($text ne '') { $template.='</td></tr></table>' };
                   1530:     return $template;
                   1531: 
                   1532: }
                   1533: 
                   1534: sub help_open_faq {
                   1535:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1536:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1537:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1538:     $text = "" if (not defined $text);
                   1539: 	$stayOnPage=1;
                   1540:     $width = 350 if (not defined $width);
                   1541:     $height = 400 if (not defined $height);
                   1542: 
                   1543:     $topic=~s/\W+/\+/g;
                   1544:     my $link='';
                   1545:     my $template='';
                   1546:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1547:     if (!$stayOnPage)
                   1548:     {
                   1549: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1550:     }
                   1551:     else
                   1552:     {
                   1553: 	$link = $url;
                   1554:     }
                   1555: 
                   1556:     # Add the text
                   1557:     if ($text ne "")
                   1558:     {
                   1559: 	$template .= 
1.173     www      1560:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1561:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1562:     }
                   1563: 
                   1564:     # Add the graphic
1.179     matthew  1565:     my $title = &mt('View the FAQ');
1.215     albertel 1566:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1567:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1568:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1569: ENDTEMPLATE
                   1570:     if ($text ne '') { $template.='</td></tr></table>' };
                   1571:     return $template;
                   1572: 
1.44      bowersj2 1573: }
1.37      matthew  1574: 
1.180     matthew  1575: ###############################################################
                   1576: ###############################################################
                   1577: 
1.45      matthew  1578: =pod
                   1579: 
1.648     raeburn  1580: =item * &change_content_javascript():
1.256     matthew  1581: 
                   1582: This and the next function allow you to create small sections of an
                   1583: otherwise static HTML page that you can update on the fly with
                   1584: Javascript, even in Netscape 4.
                   1585: 
                   1586: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1587: must be written to the HTML page once. It will prove the Javascript
                   1588: function "change(name, content)". Calling the change function with the
                   1589: name of the section 
                   1590: you want to update, matching the name passed to C<changable_area>, and
                   1591: the new content you want to put in there, will put the content into
                   1592: that area.
                   1593: 
                   1594: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1595: to contain room for the original contents. You need to "make space"
                   1596: for whatever changes you wish to make, and be B<sure> to check your
                   1597: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1598: it's adequate for updating a one-line status display, but little more.
                   1599: This script will set the space to 100% width, so you only need to
                   1600: worry about height in Netscape 4.
                   1601: 
                   1602: Modern browsers are much less limiting, and if you can commit to the
                   1603: user not using Netscape 4, this feature may be used freely with
                   1604: pretty much any HTML.
                   1605: 
                   1606: =cut
                   1607: 
                   1608: sub change_content_javascript {
                   1609:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1610:     if ($env{'browser.type'} eq 'netscape' &&
                   1611: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1612: 	return (<<NETSCAPE4);
                   1613: 	function change(name, content) {
                   1614: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1615: 	    doc.open();
                   1616: 	    doc.write(content);
                   1617: 	    doc.close();
                   1618: 	}
                   1619: NETSCAPE4
                   1620:     } else {
                   1621: 	# Otherwise, we need to use semi-standards-compliant code
                   1622: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1623: 	# is really scary, and every useful browser supports it
                   1624: 	return (<<DOMBASED);
                   1625: 	function change(name, content) {
                   1626: 	    element = document.getElementById(name);
                   1627: 	    element.innerHTML = content;
                   1628: 	}
                   1629: DOMBASED
                   1630:     }
                   1631: }
                   1632: 
                   1633: =pod
                   1634: 
1.648     raeburn  1635: =item * &changable_area($name,$origContent):
1.256     matthew  1636: 
                   1637: This provides a "changable area" that can be modified on the fly via
                   1638: the Javascript code provided in C<change_content_javascript>. $name is
                   1639: the name you will use to reference the area later; do not repeat the
                   1640: same name on a given HTML page more then once. $origContent is what
                   1641: the area will originally contain, which can be left blank.
                   1642: 
                   1643: =cut
                   1644: 
                   1645: sub changable_area {
                   1646:     my ($name, $origContent) = @_;
                   1647: 
1.258     albertel 1648:     if ($env{'browser.type'} eq 'netscape' &&
                   1649: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1650: 	# If this is netscape 4, we need to use the Layer tag
                   1651: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1652:     } else {
                   1653: 	return "<span id='$name'>$origContent</span>";
                   1654:     }
                   1655: }
                   1656: 
                   1657: =pod
                   1658: 
1.648     raeburn  1659: =item * &viewport_geometry_js 
1.590     raeburn  1660: 
                   1661: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1662: 
                   1663: =cut
                   1664: 
                   1665: 
                   1666: sub viewport_geometry_js { 
                   1667:     return <<"GEOMETRY";
                   1668: var Geometry = {};
                   1669: function init_geometry() {
                   1670:     if (Geometry.init) { return };
                   1671:     Geometry.init=1;
                   1672:     if (window.innerHeight) {
                   1673:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1674:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1675:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1676:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1677:     }
                   1678:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1679:         Geometry.getViewportHeight =
                   1680:             function() { return document.documentElement.clientHeight; };
                   1681:         Geometry.getViewportWidth =
                   1682:             function() { return document.documentElement.clientWidth; };
                   1683: 
                   1684:         Geometry.getHorizontalScroll =
                   1685:             function() { return document.documentElement.scrollLeft; };
                   1686:         Geometry.getVerticalScroll =
                   1687:             function() { return document.documentElement.scrollTop; };
                   1688:     }
                   1689:     else if (document.body.clientHeight) {
                   1690:         Geometry.getViewportHeight =
                   1691:             function() { return document.body.clientHeight; };
                   1692:         Geometry.getViewportWidth =
                   1693:             function() { return document.body.clientWidth; };
                   1694:         Geometry.getHorizontalScroll =
                   1695:             function() { return document.body.scrollLeft; };
                   1696:         Geometry.getVerticalScroll =
                   1697:             function() { return document.body.scrollTop; };
                   1698:     }
                   1699: }
                   1700: 
                   1701: GEOMETRY
                   1702: }
                   1703: 
                   1704: =pod
                   1705: 
1.648     raeburn  1706: =item * &viewport_size_js()
1.590     raeburn  1707: 
                   1708: 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. 
                   1709: 
                   1710: =cut
                   1711: 
                   1712: sub viewport_size_js {
                   1713:     my $geometry = &viewport_geometry_js();
                   1714:     return <<"DIMS";
                   1715: 
                   1716: $geometry
                   1717: 
                   1718: function getViewportDims(width,height) {
                   1719:     init_geometry();
                   1720:     width.value = Geometry.getViewportWidth();
                   1721:     height.value = Geometry.getViewportHeight();
                   1722:     return;
                   1723: }
                   1724: 
                   1725: DIMS
                   1726: }
                   1727: 
                   1728: =pod
                   1729: 
1.648     raeburn  1730: =item * &resize_textarea_js()
1.565     albertel 1731: 
                   1732: emits the needed javascript to resize a textarea to be as big as possible
                   1733: 
                   1734: creates a function resize_textrea that takes two IDs first should be
                   1735: the id of the element to resize, second should be the id of a div that
                   1736: surrounds everything that comes after the textarea, this routine needs
                   1737: to be attached to the <body> for the onload and onresize events.
                   1738: 
1.648     raeburn  1739: =back
1.565     albertel 1740: 
                   1741: =cut
                   1742: 
                   1743: sub resize_textarea_js {
1.590     raeburn  1744:     my $geometry = &viewport_geometry_js();
1.565     albertel 1745:     return <<"RESIZE";
                   1746:     <script type="text/javascript">
1.824     bisitz   1747: // <![CDATA[
1.590     raeburn  1748: $geometry
1.565     albertel 1749: 
1.588     albertel 1750: function getX(element) {
                   1751:     var x = 0;
                   1752:     while (element) {
                   1753: 	x += element.offsetLeft;
                   1754: 	element = element.offsetParent;
                   1755:     }
                   1756:     return x;
                   1757: }
                   1758: function getY(element) {
                   1759:     var y = 0;
                   1760:     while (element) {
                   1761: 	y += element.offsetTop;
                   1762: 	element = element.offsetParent;
                   1763:     }
                   1764:     return y;
                   1765: }
                   1766: 
                   1767: 
1.565     albertel 1768: function resize_textarea(textarea_id,bottom_id) {
                   1769:     init_geometry();
                   1770:     var textarea        = document.getElementById(textarea_id);
                   1771:     //alert(textarea);
                   1772: 
1.588     albertel 1773:     var textarea_top    = getY(textarea);
1.565     albertel 1774:     var textarea_height = textarea.offsetHeight;
                   1775:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1776:     var bottom_top      = getY(bottom);
1.565     albertel 1777:     var bottom_height   = bottom.offsetHeight;
                   1778:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1779:     var fudge           = 23;
1.565     albertel 1780:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1781:     if (new_height < 300) {
                   1782: 	new_height = 300;
                   1783:     }
                   1784:     textarea.style.height=new_height+'px';
                   1785: }
1.824     bisitz   1786: // ]]>
1.565     albertel 1787: </script>
                   1788: RESIZE
                   1789: 
                   1790: }
                   1791: 
1.1205    golterma 1792: sub colorfuleditor_js {
1.1248    raeburn  1793:     my $browse_or_search;
                   1794:     my $respath;
                   1795:     my ($cnum,$cdom) = &crsauthor_url();
                   1796:     if ($cnum) {
                   1797:         $respath = "/res/$cdom/$cnum/";
                   1798:         my %js_lt = &Apache::lonlocal::texthash(
                   1799:             sunm => 'Sub-directory name',
                   1800:             save => 'Save page to make this permanent',
                   1801:         );
                   1802:         &js_escape(\%js_lt);
                   1803:         $browse_or_search = <<"END";
                   1804: 
                   1805:     function toggleChooser(form,element,titleid,only,search) {
                   1806:         var disp = 'none';
                   1807:         if (document.getElementById('chooser_'+element)) {
                   1808:             var curr = document.getElementById('chooser_'+element).style.display;
                   1809:             if (curr == 'none') {
                   1810:                 disp='inline';
                   1811:                 if (form.elements['chooser_'+element].length) {
                   1812:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1813:                         form.elements['chooser_'+element][i].checked = false;
                   1814:                     }
                   1815:                 }
                   1816:                 toggleResImport(form,element);
                   1817:             }
                   1818:             document.getElementById('chooser_'+element).style.display = disp;
                   1819:         }
                   1820:     }
                   1821: 
                   1822:     function toggleCrsFile(form,element,numdirs) {
                   1823:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1824:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1825:             if (curr == 'none') {
                   1826:                 if (numdirs) {
                   1827:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1828:                     if (numdirs > 1) {
                   1829:                         window['select1'+element+'_changed']();
                   1830:                     }
                   1831:                 }
                   1832:             } 
                   1833:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1834:             
                   1835:         }
                   1836:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1837:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1838:             if (document.getElementById('uploadcrsres_'+element)) {
                   1839:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1840:             }
                   1841:         }
                   1842:         return;
                   1843:     }
                   1844: 
                   1845:     function toggleCrsUpload(form,element,numcrsdirs) {
                   1846:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1847:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1848:         }
                   1849:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1850:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1851:             if (curr == 'none') {
                   1852:                 if (numcrsdirs) {
                   1853:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
                   1854:                    form.elements['newsubdir_'+element][0].checked = true;
                   1855:                    toggleNewsubdir(form,element);
                   1856:                 }
                   1857:             }
                   1858:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1859:         }
                   1860:         return;
                   1861:     }
                   1862: 
                   1863:     function toggleResImport(form,element) {
                   1864:         var choices = new Array('crsres','upload');
                   1865:         for (var i=0; i<choices.length; i++) {
                   1866:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1867:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1868:             }
                   1869:         }
                   1870:     }
                   1871: 
                   1872:     function toggleNewsubdir(form,element) {
                   1873:         var newsub = form.elements['newsubdir_'+element];
                   1874:         if (newsub) {
                   1875:             if (newsub.length) {
                   1876:                 for (var j=0; j<newsub.length; j++) {
                   1877:                     if (newsub[j].checked) {
                   1878:                         if (document.getElementById('newsubdirname_'+element)) {
                   1879:                             if (newsub[j].value == '1') {
                   1880:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1881:                                 if (document.getElementById('newsubdir_'+element)) {
                   1882:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1883:                                 }
                   1884:                             } else {
                   1885:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1886:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1887:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1888:                             }
                   1889:                         }
                   1890:                         break; 
                   1891:                     }
                   1892:                 }
                   1893:             }
                   1894:         }
                   1895:     }
                   1896: 
                   1897:     function updateCrsFile(form,element) {
                   1898:         var directory = form.elements['coursepath_'+element];
                   1899:         var filename = form.elements['coursefile_'+element];
                   1900:         var path = directory.options[directory.selectedIndex].value;
                   1901:         var file = filename.options[filename.selectedIndex].value;
                   1902:         form.elements[element].value = '$respath';
                   1903:         if (path == '/') {
                   1904:             form.elements[element].value += file;
                   1905:         } else {
                   1906:             form.elements[element].value += path+'/'+file;
                   1907:         }
                   1908:         unClean();
                   1909:         if (document.getElementById('previewimg_'+element)) {
                   1910:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1911:             var newsrc = document.getElementById('previewimg_'+element).src; 
                   1912:         }
                   1913:         if (document.getElementById('showimg_'+element)) {
                   1914:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1915:         }
                   1916:         toggleChooser(form,element);
                   1917:         return;
                   1918:     }
                   1919: 
                   1920:     function uploadDone(suffix,name) {
                   1921:         if (name) {
                   1922: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1923:             unClean();
                   1924:             toggleChooser(document.forms["lonhomework"],suffix);
                   1925:         }
                   1926:     }
                   1927: 
                   1928: \$(document).ready(function(){
                   1929: 
                   1930:     \$(document).delegate('form :submit', 'click', function( event ) {
                   1931:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   1932:             var buttonId = this.id;
                   1933:             var suffix = buttonId.toString();
                   1934:             suffix = suffix.replace(/^crsupload_/,'');
                   1935:             event.preventDefault();
                   1936:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   1937:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   1938:             \$(this.form).submit();
                   1939:             document.lonhomework.target = '';
                   1940:             if (document.getElementById('crsuploadto_'+suffix)) {
                   1941:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   1942:             }
                   1943:             return false;
                   1944:         }
                   1945:     });
                   1946: });
                   1947: END
                   1948:     }
1.1205    golterma 1949:     return <<"COLORFULEDIT"
                   1950: <script type="text/javascript">
                   1951: // <![CDATA[>
                   1952:     function fold_box(curDepth, lastresource){
                   1953: 
                   1954:     // we need a list because there can be several blocks you need to fold in one tag
                   1955:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1956:     // but there is only one folding button per tag
                   1957:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1958: 
                   1959:         if(block.item(0).style.display == 'none'){
                   1960: 
                   1961:             foldbutton.value = '@{[&mt("Hide")]}';
                   1962:             for (i = 0; i < block.length; i++){
                   1963:                 block.item(i).style.display = '';
                   1964:             }
                   1965:         }else{
                   1966: 
                   1967:             foldbutton.value = '@{[&mt("Show")]}';
                   1968:             for (i = 0; i < block.length; i++){
                   1969:                 // block.item(i).style.visibility = 'collapse';
                   1970:                 block.item(i).style.display = 'none';
                   1971:             }
                   1972:         };
                   1973:         saveState(lastresource);
                   1974:     }
                   1975: 
                   1976:     function saveState (lastresource) {
                   1977: 
                   1978:         var tag_list = getTagList();
                   1979:         if(tag_list != null){
                   1980:             var timestamp = new Date().getTime();
                   1981:             var key = lastresource;
                   1982: 
                   1983:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1984:             // starting with timestamp
                   1985:             var value = timestamp+';';
                   1986: 
                   1987:             // building the list of key-value pairs
                   1988:             for(var i = 0; i < tag_list.length; i++){
                   1989:                 value += tag_list[i]+',';
                   1990:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1991:             }
                   1992: 
                   1993:             // only iterate whole storage if nothing to override
                   1994:             if(localStorage.getItem(key) == null){        
                   1995: 
                   1996:                 // prevent storage from growing large
                   1997:                 if(localStorage.length > 50){
                   1998:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1999:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2000:                     var oldest_key;
                   2001:                     
                   2002:                     for(var i = 1; i < localStorage.length; i++){
                   2003:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2004:                             oldest_key = localStorage.key(i);
                   2005:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2006:                         }
                   2007:                     }
                   2008:                     localStorage.removeItem(oldest_key);
                   2009:                 }
                   2010:             }
                   2011:             localStorage.setItem(key,value);
                   2012:         }
                   2013:     }
                   2014: 
                   2015:     // restore folding status of blocks (on page load)
                   2016:     function restoreState (lastresource) {
                   2017:         if(localStorage.getItem(lastresource) != null){
                   2018:             var key = lastresource;
                   2019:             var value = localStorage.getItem(key);
                   2020:             var regex_delTimestamp = /^\d+;/;
                   2021: 
                   2022:             value.replace(regex_delTimestamp, '');
                   2023: 
                   2024:             var valueArr = value.split(';');
                   2025:             var pairs;
                   2026:             var elements;
                   2027:             for (var i = 0; i < valueArr.length; i++){
                   2028:                 pairs = valueArr[i].split(',');
                   2029:                 elements = document.getElementsByName(pairs[0]);
                   2030: 
                   2031:                 for (var j = 0; j < elements.length; j++){  
                   2032:                     elements[j].style.display = pairs[1];
                   2033:                     if (pairs[1] == "none"){
                   2034:                         var regex_id = /([_\\d]+)\$/;
                   2035:                         regex_id.exec(pairs[0]);
                   2036:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2037:                     }
                   2038:                 }
                   2039:             }
                   2040:         }
                   2041:     }
                   2042: 
                   2043:     function getTagList () {
                   2044:         
                   2045:         var stringToSearch = document.lonhomework.innerHTML;
                   2046: 
                   2047:         var ret = new Array();
                   2048:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2049:         var tag_list = stringToSearch.match(regex_findBlock);
                   2050: 
                   2051:         if(tag_list != null){
                   2052:             for(var i = 0; i < tag_list.length; i++){            
                   2053:                 ret.push(tag_list[i].replace(/"/, ''));
                   2054:             }
                   2055:         }
                   2056:         return ret;
                   2057:     }
                   2058: 
                   2059:     function saveScrollPosition (resource) {
                   2060:         var tag_list = getTagList();
                   2061: 
                   2062:         // we dont always want to jump to the first block
                   2063:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2064:         if(\$(window).scrollTop() > 170){
                   2065:             if(tag_list != null){
                   2066:                 var result;
                   2067:                 for(var i = 0; i < tag_list.length; i++){
                   2068:                     if(isElementInViewport(tag_list[i])){
                   2069:                         result += tag_list[i]+';';
                   2070:                     }
                   2071:                 }
                   2072:                 sessionStorage.setItem('anchor_'+resource, result);
                   2073:             }
                   2074:         } else {
                   2075:             // we dont need to save zero, just delete the item to leave everything tidy
                   2076:             sessionStorage.removeItem('anchor_'+resource);
                   2077:         }
                   2078:     }
                   2079: 
                   2080:     function restoreScrollPosition(resource){
                   2081: 
                   2082:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2083:         if(elem != null){
                   2084:             var tag_list = elem.split(';');
                   2085:             var elem_list;
                   2086: 
                   2087:             for(var i = 0; i < tag_list.length; i++){
                   2088:                 elem_list = document.getElementsByName(tag_list[i]);
                   2089:                 
                   2090:                 if(elem_list.length > 0){
                   2091:                     elem = elem_list[0];
                   2092:                     break;
                   2093:                 }
                   2094:             }
                   2095:             elem.scrollIntoView();
                   2096:         }
                   2097:     }
                   2098: 
                   2099:     function isElementInViewport(el) {
                   2100: 
                   2101:         // change to last element instead of first
                   2102:         var elem = document.getElementsByName(el);
                   2103:         var rect = elem[0].getBoundingClientRect();
                   2104: 
                   2105:         return (
                   2106:             rect.top >= 0 &&
                   2107:             rect.left >= 0 &&
                   2108:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2109:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2110:         );
                   2111:     }
                   2112:     
                   2113:     function autosize(depth){
                   2114:         var cmInst = window['cm'+depth];
                   2115:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2116: 
                   2117:         // is fixed size, switching to dynamic
                   2118:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2119:             cmInst.setSize("","auto");
                   2120:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2121:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2122: 
                   2123:         // is dynamic size, switching to fixed
                   2124:         } else {
                   2125:             cmInst.setSize("","300px");
                   2126:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2127:             sessionStorage.removeItem("autosized_"+depth);
                   2128:         }
                   2129:     }
                   2130: 
1.1248    raeburn  2131: $browse_or_search
1.1205    golterma 2132: 
                   2133: // ]]>
                   2134: </script>
                   2135: COLORFULEDIT
                   2136: }
                   2137: 
                   2138: sub xmleditor_js {
                   2139:     return <<XMLEDIT
                   2140: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2141: <script type="text/javascript">
                   2142: // <![CDATA[>
                   2143: 
                   2144:     function saveScrollPosition (resource) {
                   2145: 
                   2146:         var scrollPos = \$(window).scrollTop();
                   2147:         sessionStorage.setItem(resource,scrollPos);
                   2148:     }
                   2149: 
                   2150:     function restoreScrollPosition(resource){
                   2151: 
                   2152:         var scrollPos = sessionStorage.getItem(resource);
                   2153:         \$(window).scrollTop(scrollPos);
                   2154:     }
                   2155: 
                   2156:     // unless internet explorer
                   2157:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2158: 
                   2159:         \$(document).ready(function() {
                   2160:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2161:         });
                   2162:     }
                   2163: 
                   2164:     // inserts text at cursor position into codemirror (xml editor only)
                   2165:     function insertText(text){
                   2166:         cm.focus();
                   2167:         var curPos = cm.getCursor();
                   2168:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2169:     }
                   2170: // ]]>
                   2171: </script>
                   2172: XMLEDIT
                   2173: }
                   2174: 
                   2175: sub insert_folding_button {
                   2176:     my $curDepth = $Apache::lonxml::curdepth;
                   2177:     my $lastresource = $env{'request.ambiguous'};
                   2178: 
                   2179:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2180:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2181: }
                   2182: 
1.1248    raeburn  2183: sub crsauthor_url {
                   2184:     my ($url) = @_;
                   2185:     if ($url eq '') {
                   2186:         $url = $ENV{'REQUEST_URI'};
                   2187:     }
                   2188:     my ($cnum,$cdom);
                   2189:     if ($env{'request.course.id'}) {
                   2190:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2191:         if ($audom ne '' && $auname ne '') {
                   2192:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2193:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2194:                 $cnum = $auname;
                   2195:                 $cdom = $audom;
                   2196:             }
                   2197:         }
                   2198:     }
                   2199:     return ($cnum,$cdom);
                   2200: }
                   2201: 
                   2202: sub import_crsauthor_form {
1.1265    raeburn  2203:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2204:     return (0) unless ($env{'request.course.id'});
                   2205:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2206:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2207:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2208:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2209:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2210:     my @ids=&Apache::lonnet::current_machine_ids();
                   2211:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
                   2212:     
                   2213:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2214:         $is_home = 1;
                   2215:     }
                   2216:     $relpath = "/priv/$cdom/$cnum";
                   2217:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
                   2218:     my %lt = &Apache::lonlocal::texthash (
                   2219:         fnam => 'Filename',
                   2220:         dire => 'Directory',
                   2221:     );
                   2222:     my $numdirs = scalar(keys(%files));
                   2223:     my (%possexts,$singledir,@singledirfiles);
                   2224:     if ($only) {
                   2225:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
                   2226:     }
                   2227:     my (%nonemptydirs,$possdirs);
                   2228:     if ($numdirs > 1) {
                   2229:         my @order;
                   2230:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
                   2231:             if (ref($files{$key}) eq 'HASH') {
                   2232:                 my $shown = $key;
                   2233:                 if ($key eq '') {
                   2234:                     $shown = '/';
                   2235:                 }
                   2236:                 my @ordered = ();
                   2237:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
1.1315    raeburn  2238:                     next if ($file =~ /\.rights$/);
1.1248    raeburn  2239:                     if ($only) {
                   2240:                         my ($ext) = ($file =~ /\.([^.]+)$/);
                   2241:                         unless ($possexts{lc($ext)}) {
                   2242:                             next;
                   2243:                         }
                   2244:                     }
                   2245:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
                   2246:                     push(@ordered,$file);
                   2247:                 }
                   2248:                 if (@ordered) {
                   2249:                     push(@order,$key);
                   2250:                     $nonemptydirs{$key} = 1;
                   2251:                     $selimport_menus{$key}->{'text'} = $shown;
                   2252:                     $selimport_menus{$key}->{'default'} = '';
                   2253:                     $selimport_menus{$key}->{'select2'}->{''} = '';
                   2254:                     $selimport_menus{$key}->{'order'} = \@ordered;
                   2255:                 }
                   2256:             }
                   2257:         }
                   2258:         $possdirs = scalar(keys(%nonemptydirs));
                   2259:         if ($possdirs > 1) {
                   2260:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
                   2261:             $output = $lt{'dire'}.
                   2262:                       &linked_select_forms($form,'<br />'.
                   2263:                                            $lt{'fnam'},'',
                   2264:                                            $firstselectname,$secondselectname,
                   2265:                                            \%selimport_menus,\@order,
                   2266:                                            $onchangefirst,'',$suffix).'<br />';
                   2267:         } elsif ($possdirs == 1) {
                   2268:             $singledir = (keys(%nonemptydirs))[0];
                   2269:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
                   2270:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
                   2271:             }
                   2272:             delete($selimport_menus{$singledir});
                   2273:         }
                   2274:     } elsif ($numdirs == 1) {
                   2275:         $singledir = (keys(%files))[0];
                   2276:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
                   2277:             if ($only) {
                   2278:                 my ($ext) = ($file =~ /\.([^.]+)$/);
                   2279:                 unless ($possexts{lc($ext)}) {
                   2280:                     next;
                   2281:                 }
1.1315    raeburn  2282:             } else {
                   2283:                 next if ($file =~ /\.rights$/);
1.1248    raeburn  2284:             }
                   2285:             push(@singledirfiles,$file);
                   2286:         }
                   2287:         if (@singledirfiles) {
1.1315    raeburn  2288:             $possdirs = 1;
1.1248    raeburn  2289:         }
                   2290:     }
                   2291:     if (($possdirs == 1) && (@singledirfiles)) {
                   2292:         my $showdir = $singledir;
                   2293:         if ($singledir eq '') {
                   2294:             $showdir = '/';
                   2295:         }
                   2296:         $output = $lt{'dire'}.
                   2297:                   '<select name="'.$firstselectname.'">'.
                   2298:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
                   2299:                   '</select><br />'.
                   2300:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
                   2301:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
                   2302:         foreach my $file (@singledirfiles) {
                   2303:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
                   2304:         }
                   2305:         $output .= '</select><br />'."\n";
                   2306:     }
                   2307:     return ($possdirs,$output);
                   2308: }
                   2309: 
1.565     albertel 2310: =pod
                   2311: 
1.256     matthew  2312: =head1 Excel and CSV file utility routines
                   2313: 
                   2314: =cut
                   2315: 
                   2316: ###############################################################
                   2317: ###############################################################
                   2318: 
                   2319: =pod
                   2320: 
1.1162    raeburn  2321: =over 4
                   2322: 
1.648     raeburn  2323: =item * &csv_translate($text) 
1.37      matthew  2324: 
1.185     www      2325: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2326: format.
                   2327: 
                   2328: =cut
                   2329: 
1.180     matthew  2330: ###############################################################
                   2331: ###############################################################
1.37      matthew  2332: sub csv_translate {
                   2333:     my $text = shift;
                   2334:     $text =~ s/\"/\"\"/g;
1.209     albertel 2335:     $text =~ s/\n/ /g;
1.37      matthew  2336:     return $text;
                   2337: }
1.180     matthew  2338: 
                   2339: ###############################################################
                   2340: ###############################################################
                   2341: 
                   2342: =pod
                   2343: 
1.648     raeburn  2344: =item * &define_excel_formats()
1.180     matthew  2345: 
                   2346: Define some commonly used Excel cell formats.
                   2347: 
                   2348: Currently supported formats:
                   2349: 
                   2350: =over 4
                   2351: 
                   2352: =item header
                   2353: 
                   2354: =item bold
                   2355: 
                   2356: =item h1
                   2357: 
                   2358: =item h2
                   2359: 
                   2360: =item h3
                   2361: 
1.256     matthew  2362: =item h4
                   2363: 
                   2364: =item i
                   2365: 
1.180     matthew  2366: =item date
                   2367: 
                   2368: =back
                   2369: 
                   2370: Inputs: $workbook
                   2371: 
                   2372: Returns: $format, a hash reference.
                   2373: 
1.1057    foxr     2374: 
1.180     matthew  2375: =cut
                   2376: 
                   2377: ###############################################################
                   2378: ###############################################################
                   2379: sub define_excel_formats {
                   2380:     my ($workbook) = @_;
                   2381:     my $format;
                   2382:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2383:                                                 bottom    => 1,
                   2384:                                                 align     => 'center');
                   2385:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2386:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2387:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2388:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2389:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2390:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2391:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2392:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2393:     return $format;
                   2394: }
                   2395: 
                   2396: ###############################################################
                   2397: ###############################################################
1.113     bowersj2 2398: 
                   2399: =pod
                   2400: 
1.648     raeburn  2401: =item * &create_workbook()
1.255     matthew  2402: 
                   2403: Create an Excel worksheet.  If it fails, output message on the
                   2404: request object and return undefs.
                   2405: 
                   2406: Inputs: Apache request object
                   2407: 
                   2408: Returns (undef) on failure, 
                   2409:     Excel worksheet object, scalar with filename, and formats 
                   2410:     from &Apache::loncommon::define_excel_formats on success
                   2411: 
                   2412: =cut
                   2413: 
                   2414: ###############################################################
                   2415: ###############################################################
                   2416: sub create_workbook {
                   2417:     my ($r) = @_;
                   2418:         #
                   2419:     # Create the excel spreadsheet
                   2420:     my $filename = '/prtspool/'.
1.258     albertel 2421:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2422:         time.'_'.rand(1000000000).'.xls';
                   2423:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2424:     if (! defined($workbook)) {
                   2425:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2426:         $r->print(
                   2427:             '<p class="LC_error">'
                   2428:            .&mt('Problems occurred in creating the new Excel file.')
                   2429:            .' '.&mt('This error has been logged.')
                   2430:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2431:            .'</p>'
                   2432:         );
1.255     matthew  2433:         return (undef);
                   2434:     }
                   2435:     #
1.1014    foxr     2436:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2437:     #
                   2438:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2439:     return ($workbook,$filename,$format);
                   2440: }
                   2441: 
                   2442: ###############################################################
                   2443: ###############################################################
                   2444: 
                   2445: =pod
                   2446: 
1.648     raeburn  2447: =item * &create_text_file()
1.113     bowersj2 2448: 
1.542     raeburn  2449: Create a file to write to and eventually make available to the user.
1.256     matthew  2450: If file creation fails, outputs an error message on the request object and 
                   2451: return undefs.
1.113     bowersj2 2452: 
1.256     matthew  2453: Inputs: Apache request object, and file suffix
1.113     bowersj2 2454: 
1.256     matthew  2455: Returns (undef) on failure, 
                   2456:     Filehandle and filename on success.
1.113     bowersj2 2457: 
                   2458: =cut
                   2459: 
1.256     matthew  2460: ###############################################################
                   2461: ###############################################################
                   2462: sub create_text_file {
                   2463:     my ($r,$suffix) = @_;
                   2464:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2465:     my $fh;
                   2466:     my $filename = '/prtspool/'.
1.258     albertel 2467:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2468:         time.'_'.rand(1000000000).'.'.$suffix;
                   2469:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2470:     if (! defined($fh)) {
                   2471:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2472:         $r->print(
                   2473:             '<p class="LC_error">'
                   2474:            .&mt('Problems occurred in creating the output file.')
                   2475:            .' '.&mt('This error has been logged.')
                   2476:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2477:            .'</p>'
                   2478:         );
1.113     bowersj2 2479:     }
1.256     matthew  2480:     return ($fh,$filename)
1.113     bowersj2 2481: }
                   2482: 
                   2483: 
1.256     matthew  2484: =pod 
1.113     bowersj2 2485: 
                   2486: =back
                   2487: 
                   2488: =cut
1.37      matthew  2489: 
                   2490: ###############################################################
1.33      matthew  2491: ##        Home server <option> list generating code          ##
                   2492: ###############################################################
1.35      matthew  2493: 
1.169     www      2494: # ------------------------------------------
                   2495: 
                   2496: sub domain_select {
1.1289    raeburn  2497:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2498:     my @possdoms;
                   2499:     if (ref($incdoms) eq 'ARRAY') {
                   2500:         @possdoms = @{$incdoms};
                   2501:     } else {
                   2502:         @possdoms = &Apache::lonnet::all_domains();
                   2503:     }
                   2504: 
1.169     www      2505:     my %domains=map { 
1.514     albertel 2506: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2507:     } @possdoms;
                   2508: 
                   2509:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2510:         foreach my $dom (@{$excdoms}) {
                   2511:             delete($domains{$dom});
                   2512:         }
                   2513:     }
                   2514: 
1.169     www      2515:     if ($multiple) {
                   2516: 	$domains{''}=&mt('Any domain');
1.550     albertel 2517: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2518: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2519:     } else {
1.550     albertel 2520: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2521: 	return &select_form($name,$value,\%domains);
1.169     www      2522:     }
                   2523: }
                   2524: 
1.282     albertel 2525: #-------------------------------------------
                   2526: 
                   2527: =pod
                   2528: 
1.519     raeburn  2529: =head1 Routines for form select boxes
                   2530: 
                   2531: =over 4
                   2532: 
1.648     raeburn  2533: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2534: 
                   2535: Returns a string containing a <select> element int multiple mode
                   2536: 
                   2537: 
                   2538: Args:
                   2539:   $name - name of the <select> element
1.506     raeburn  2540:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2541:   $size - number of rows long the select element is
1.283     albertel 2542:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2543:           (shown text should already have been &mt())
1.506     raeburn  2544:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2545: 
1.282     albertel 2546: =cut
                   2547: 
                   2548: #-------------------------------------------
1.169     www      2549: sub multiple_select_form {
1.284     albertel 2550:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2551:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2552:     my $output='';
1.191     matthew  2553:     if (! defined($size)) {
                   2554:         $size = 4;
1.283     albertel 2555:         if (scalar(keys(%$hash))<4) {
                   2556:             $size = scalar(keys(%$hash));
1.191     matthew  2557:         }
                   2558:     }
1.734     bisitz   2559:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2560:     my @order;
1.506     raeburn  2561:     if (ref($order) eq 'ARRAY')  {
                   2562:         @order = @{$order};
                   2563:     } else {
                   2564:         @order = sort(keys(%$hash));
1.501     banghart 2565:     }
                   2566:     if (exists($$hash{'select_form_order'})) {
                   2567:         @order = @{$$hash{'select_form_order'}};
                   2568:     }
                   2569:         
1.284     albertel 2570:     foreach my $key (@order) {
1.356     albertel 2571:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2572:         $output.='selected="selected" ' if ($selected{$key});
                   2573:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2574:     }
                   2575:     $output.="</select>\n";
                   2576:     return $output;
                   2577: }
                   2578: 
1.88      www      2579: #-------------------------------------------
                   2580: 
                   2581: =pod
                   2582: 
1.1254    raeburn  2583: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2584: 
                   2585: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2586: allow a user to select options from a ref to a hash containing:
                   2587: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2588: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2589: An optional arg -- $readonly -- if true will cause the select form
                   2590: to be disabled, e.g., for the case where an instructor has a section-
                   2591: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2592: 
1.88      www      2593: See lonrights.pm for an example invocation and use.
                   2594: 
                   2595: =cut
                   2596: 
                   2597: #-------------------------------------------
                   2598: sub select_form {
1.1228    raeburn  2599:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2600:     return unless (ref($hashref) eq 'HASH');
                   2601:     if ($onchange) {
                   2602:         $onchange = ' onchange="'.$onchange.'"';
                   2603:     }
1.1228    raeburn  2604:     my $disabled;
                   2605:     if ($readonly) {
                   2606:         $disabled = ' disabled="disabled"';
                   2607:     }
                   2608:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2609:     my @keys;
1.970     raeburn  2610:     if (exists($hashref->{'select_form_order'})) {
                   2611: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2612:     } else {
1.970     raeburn  2613: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2614:     }
1.356     albertel 2615:     foreach my $key (@keys) {
                   2616:         $selectform.=
                   2617: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2618:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2619:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2620:     }
                   2621:     $selectform.="</select>";
                   2622:     return $selectform;
                   2623: }
                   2624: 
1.475     www      2625: # For display filters
                   2626: 
                   2627: sub display_filter {
1.1074    raeburn  2628:     my ($context) = @_;
1.475     www      2629:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2630:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2631:     my $phraseinput = 'hidden';
                   2632:     my $includeinput = 'hidden';
                   2633:     my ($checked,$includetypestext);
                   2634:     if ($env{'form.displayfilter'} eq 'containing') {
                   2635:         $phraseinput = 'text'; 
                   2636:         if ($context eq 'parmslog') {
                   2637:             $includeinput = 'checkbox';
                   2638:             if ($env{'form.includetypes'}) {
                   2639:                 $checked = ' checked="checked"';
                   2640:             }
                   2641:             $includetypestext = &mt('Include parameter types');
                   2642:         }
                   2643:     } else {
                   2644:         $includetypestext = '&nbsp;';
                   2645:     }
                   2646:     my ($additional,$secondid,$thirdid);
                   2647:     if ($context eq 'parmslog') {
                   2648:         $additional = 
                   2649:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2650:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2651:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2652:             '</label>';
                   2653:         $secondid = 'includetypes';
                   2654:         $thirdid = 'includetypestext';
                   2655:     }
                   2656:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2657:                                                     '$secondid','$thirdid')";
                   2658:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2659: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2660: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2661: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2662:            &mt('Filter: [_1]',
1.477     www      2663: 	   &select_form($env{'form.displayfilter'},
                   2664: 			'displayfilter',
1.970     raeburn  2665: 			{'currentfolder' => 'Current folder/page',
1.477     www      2666: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2667: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2668: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2669:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2670:                          '" />'.$additional;
                   2671: }
                   2672: 
                   2673: sub display_filter_js {
                   2674:     my $includetext = &mt('Include parameter types');
                   2675:     return <<"ENDJS";
                   2676:   
                   2677: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2678:     var firstType = 'hidden';
                   2679:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2680:         firstType = 'text';
                   2681:     }
                   2682:     firstObject = document.getElementById(firstid);
                   2683:     if (typeof(firstObject) == 'object') {
                   2684:         if (firstObject.type != firstType) {
                   2685:             changeInputType(firstObject,firstType);
                   2686:         }
                   2687:     }
                   2688:     if (context == 'parmslog') {
                   2689:         var secondType = 'hidden';
                   2690:         if (firstType == 'text') {
                   2691:             secondType = 'checkbox';
                   2692:         }
                   2693:         secondObject = document.getElementById(secondid);  
                   2694:         if (typeof(secondObject) == 'object') {
                   2695:             if (secondObject.type != secondType) {
                   2696:                 changeInputType(secondObject,secondType);
                   2697:             }
                   2698:         }
                   2699:         var textItem = document.getElementById(thirdid);
                   2700:         var currtext = textItem.innerHTML;
                   2701:         var newtext;
                   2702:         if (firstType == 'text') {
                   2703:             newtext = '$includetext';
                   2704:         } else {
                   2705:             newtext = '&nbsp;';
                   2706:         }
                   2707:         if (currtext != newtext) {
                   2708:             textItem.innerHTML = newtext;
                   2709:         }
                   2710:     }
                   2711:     return;
                   2712: }
                   2713: 
                   2714: function changeInputType(oldObject,newType) {
                   2715:     var newObject = document.createElement('input');
                   2716:     newObject.type = newType;
                   2717:     if (oldObject.size) {
                   2718:         newObject.size = oldObject.size;
                   2719:     }
                   2720:     if (oldObject.value) {
                   2721:         newObject.value = oldObject.value;
                   2722:     }
                   2723:     if (oldObject.name) {
                   2724:         newObject.name = oldObject.name;
                   2725:     }
                   2726:     if (oldObject.id) {
                   2727:         newObject.id = oldObject.id;
                   2728:     }
                   2729:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2730:     return;
                   2731: }
                   2732: 
                   2733: ENDJS
1.475     www      2734: }
                   2735: 
1.167     www      2736: sub gradeleveldescription {
                   2737:     my $gradelevel=shift;
                   2738:     my %gradelevels=(0 => 'Not specified',
                   2739: 		     1 => 'Grade 1',
                   2740: 		     2 => 'Grade 2',
                   2741: 		     3 => 'Grade 3',
                   2742: 		     4 => 'Grade 4',
                   2743: 		     5 => 'Grade 5',
                   2744: 		     6 => 'Grade 6',
                   2745: 		     7 => 'Grade 7',
                   2746: 		     8 => 'Grade 8',
                   2747: 		     9 => 'Grade 9',
                   2748: 		     10 => 'Grade 10',
                   2749: 		     11 => 'Grade 11',
                   2750: 		     12 => 'Grade 12',
                   2751: 		     13 => 'Grade 13',
                   2752: 		     14 => '100 Level',
                   2753: 		     15 => '200 Level',
                   2754: 		     16 => '300 Level',
                   2755: 		     17 => '400 Level',
                   2756: 		     18 => 'Graduate Level');
                   2757:     return &mt($gradelevels{$gradelevel});
                   2758: }
                   2759: 
1.163     www      2760: sub select_level_form {
                   2761:     my ($deflevel,$name)=@_;
                   2762:     unless ($deflevel) { $deflevel=0; }
1.167     www      2763:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2764:     for (my $i=0; $i<=18; $i++) {
                   2765:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2766:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2767:                 ">".&gradeleveldescription($i)."</option>\n";
                   2768:     }
                   2769:     $selectform.="</select>";
                   2770:     return $selectform;
1.163     www      2771: }
1.167     www      2772: 
1.35      matthew  2773: #-------------------------------------------
                   2774: 
1.45      matthew  2775: =pod
                   2776: 
1.1256    raeburn  2777: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2778: 
                   2779: Returns a string containing a <select name='$name' size='1'> form to 
                   2780: allow a user to select the domain to preform an operation in.  
                   2781: See loncreateuser.pm for an example invocation and use.
                   2782: 
1.90      www      2783: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2784: selected");
                   2785: 
1.743     raeburn  2786: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2787: 
1.910     raeburn  2788: 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.
                   2789: 
1.1121    raeburn  2790: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2791: 
                   2792: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2793: 
1.1256    raeburn  2794: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2795: 
1.35      matthew  2796: =cut
                   2797: 
                   2798: #-------------------------------------------
1.34      matthew  2799: sub select_dom_form {
1.1256    raeburn  2800:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2801:     if ($onchange) {
1.874     raeburn  2802:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2803:     }
1.1256    raeburn  2804:     if ($disabled) {
                   2805:         $disabled = ' disabled="disabled"';
                   2806:     }
1.1121    raeburn  2807:     my (@domains,%exclude);
1.910     raeburn  2808:     if (ref($incdoms) eq 'ARRAY') {
                   2809:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2810:     } else {
                   2811:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2812:     }
1.90      www      2813:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2814:     if (ref($excdoms) eq 'ARRAY') {
                   2815:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2816:     }
1.1256    raeburn  2817:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2818:     foreach my $dom (@domains) {
1.1121    raeburn  2819:         next if ($exclude{$dom});
1.356     albertel 2820:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2821:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2822:         if ($showdomdesc) {
                   2823:             if ($dom ne '') {
                   2824:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2825:                 if ($domdesc ne '') {
                   2826:                     $selectdomain .= ' ('.$domdesc.')';
                   2827:                 }
                   2828:             } 
                   2829:         }
                   2830:         $selectdomain .= "</option>\n";
1.34      matthew  2831:     }
                   2832:     $selectdomain.="</select>";
                   2833:     return $selectdomain;
                   2834: }
                   2835: 
1.35      matthew  2836: #-------------------------------------------
                   2837: 
1.45      matthew  2838: =pod
                   2839: 
1.648     raeburn  2840: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2841: 
1.586     raeburn  2842: input: 4 arguments (two required, two optional) - 
                   2843:     $domain - domain of new user
                   2844:     $name - name of form element
                   2845:     $default - Value of 'default' causes a default item to be first 
                   2846:                             option, and selected by default. 
                   2847:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2848:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2849: output: returns 2 items: 
1.586     raeburn  2850: (a) form element which contains either:
                   2851:    (i) <select name="$name">
                   2852:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2853:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2854:        </select>
                   2855:        form item if there are multiple library servers in $domain, or
                   2856:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2857:        if there is only one library server in $domain.
                   2858: 
                   2859: (b) number of library servers found.
                   2860: 
                   2861: See loncreateuser.pm for example of use.
1.35      matthew  2862: 
                   2863: =cut
                   2864: 
                   2865: #-------------------------------------------
1.586     raeburn  2866: sub home_server_form_item {
                   2867:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2868:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2869:     my $result;
                   2870:     my $numlib = keys(%servers);
                   2871:     if ($numlib > 1) {
                   2872:         $result .= '<select name="'.$name.'" />'."\n";
                   2873:         if ($default) {
1.804     bisitz   2874:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2875:                        '</option>'."\n";
                   2876:         }
                   2877:         foreach my $hostid (sort(keys(%servers))) {
                   2878:             $result.= '<option value="'.$hostid.'">'.
                   2879: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2880:         }
                   2881:         $result .= '</select>'."\n";
                   2882:     } elsif ($numlib == 1) {
                   2883:         my $hostid;
                   2884:         foreach my $item (keys(%servers)) {
                   2885:             $hostid = $item;
                   2886:         }
                   2887:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2888:                    $hostid.'" />';
                   2889:                    if (!$hide) {
                   2890:                        $result .= $hostid.' '.$servers{$hostid};
                   2891:                    }
                   2892:                    $result .= "\n";
                   2893:     } elsif ($default) {
                   2894:         $result .= '<input type="hidden" name="'.$name.
                   2895:                    '" value="default" />';
                   2896:                    if (!$hide) {
                   2897:                        $result .= &mt('default');
                   2898:                    }
                   2899:                    $result .= "\n";
1.33      matthew  2900:     }
1.586     raeburn  2901:     return ($result,$numlib);
1.33      matthew  2902: }
1.112     bowersj2 2903: 
                   2904: =pod
                   2905: 
1.534     albertel 2906: =back 
                   2907: 
1.112     bowersj2 2908: =cut
1.87      matthew  2909: 
                   2910: ###############################################################
1.112     bowersj2 2911: ##                  Decoding User Agent                      ##
1.87      matthew  2912: ###############################################################
                   2913: 
                   2914: =pod
                   2915: 
1.112     bowersj2 2916: =head1 Decoding the User Agent
                   2917: 
                   2918: =over 4
                   2919: 
                   2920: =item * &decode_user_agent()
1.87      matthew  2921: 
                   2922: Inputs: $r
                   2923: 
                   2924: Outputs:
                   2925: 
                   2926: =over 4
                   2927: 
1.112     bowersj2 2928: =item * $httpbrowser
1.87      matthew  2929: 
1.112     bowersj2 2930: =item * $clientbrowser
1.87      matthew  2931: 
1.112     bowersj2 2932: =item * $clientversion
1.87      matthew  2933: 
1.112     bowersj2 2934: =item * $clientmathml
1.87      matthew  2935: 
1.112     bowersj2 2936: =item * $clientunicode
1.87      matthew  2937: 
1.112     bowersj2 2938: =item * $clientos
1.87      matthew  2939: 
1.1137    raeburn  2940: =item * $clientmobile
                   2941: 
1.1141    raeburn  2942: =item * $clientinfo
                   2943: 
1.1194    raeburn  2944: =item * $clientosversion
                   2945: 
1.87      matthew  2946: =back
                   2947: 
1.157     matthew  2948: =back 
                   2949: 
1.87      matthew  2950: =cut
                   2951: 
                   2952: ###############################################################
                   2953: ###############################################################
                   2954: sub decode_user_agent {
1.247     albertel 2955:     my ($r)=@_;
1.87      matthew  2956:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2957:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2958:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2959:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2960:     my $clientbrowser='unknown';
                   2961:     my $clientversion='0';
                   2962:     my $clientmathml='';
                   2963:     my $clientunicode='0';
1.1137    raeburn  2964:     my $clientmobile=0;
1.1194    raeburn  2965:     my $clientosversion='';
1.87      matthew  2966:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2967:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2968: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2969: 	    $clientbrowser=$bname;
                   2970:             $httpbrowser=~/$vreg/i;
                   2971: 	    $clientversion=$1;
                   2972:             $clientmathml=($clientversion>=$minv);
                   2973:             $clientunicode=($clientversion>=$univ);
                   2974: 	}
                   2975:     }
                   2976:     my $clientos='unknown';
1.1141    raeburn  2977:     my $clientinfo;
1.87      matthew  2978:     if (($httpbrowser=~/linux/i) ||
                   2979:         ($httpbrowser=~/unix/i) ||
                   2980:         ($httpbrowser=~/ux/i) ||
                   2981:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2982:     if (($httpbrowser=~/vax/i) ||
                   2983:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2984:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2985:     if (($httpbrowser=~/mac/i) ||
                   2986:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2987:     if ($httpbrowser=~/win/i) {
                   2988:         $clientos='win';
                   2989:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2990:             $clientosversion = $1;
                   2991:         }
                   2992:     }
1.87      matthew  2993:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  2994:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2995:         $clientmobile=lc($1);
                   2996:     }
1.1141    raeburn  2997:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2998:         $clientinfo = 'firefox-'.$1;
                   2999:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3000:         $clientinfo = 'chromeframe-'.$1;
                   3001:     }
1.87      matthew  3002:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3003:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3004:             $clientosversion);
1.87      matthew  3005: }
                   3006: 
1.32      matthew  3007: ###############################################################
                   3008: ##    Authentication changing form generation subroutines    ##
                   3009: ###############################################################
                   3010: ##
                   3011: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3012: ## hash, and have reasonable default values.
                   3013: ##
                   3014: ##    formname = the name given in the <form> tag.
1.35      matthew  3015: #-------------------------------------------
                   3016: 
1.45      matthew  3017: =pod
                   3018: 
1.112     bowersj2 3019: =head1 Authentication Routines
                   3020: 
                   3021: =over 4
                   3022: 
1.648     raeburn  3023: =item * &authform_xxxxxx()
1.35      matthew  3024: 
                   3025: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3026: handle some of the conveniences required for authentication forms.  
                   3027: This is not an optimal method, but it works.  
                   3028: 
                   3029: =over 4
                   3030: 
1.112     bowersj2 3031: =item * authform_header
1.35      matthew  3032: 
1.112     bowersj2 3033: =item * authform_authorwarning
1.35      matthew  3034: 
1.112     bowersj2 3035: =item * authform_nochange
1.35      matthew  3036: 
1.112     bowersj2 3037: =item * authform_kerberos
1.35      matthew  3038: 
1.112     bowersj2 3039: =item * authform_internal
1.35      matthew  3040: 
1.112     bowersj2 3041: =item * authform_filesystem
1.35      matthew  3042: 
1.1310    raeburn  3043: =item * authform_lti
                   3044: 
1.35      matthew  3045: =back
                   3046: 
1.648     raeburn  3047: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3048: 
1.35      matthew  3049: =cut
                   3050: 
                   3051: #-------------------------------------------
1.32      matthew  3052: sub authform_header{  
                   3053:     my %in = (
                   3054:         formname => 'cu',
1.80      albertel 3055:         kerb_def_dom => '',
1.32      matthew  3056:         @_,
                   3057:     );
                   3058:     $in{'formname'} = 'document.' . $in{'formname'};
                   3059:     my $result='';
1.80      albertel 3060: 
                   3061: #---------------------------------------------- Code for upper case translation
                   3062:     my $Javascript_toUpperCase;
                   3063:     unless ($in{kerb_def_dom}) {
                   3064:         $Javascript_toUpperCase =<<"END";
                   3065:         switch (choice) {
                   3066:            case 'krb': currentform.elements[choicearg].value =
                   3067:                currentform.elements[choicearg].value.toUpperCase();
                   3068:                break;
                   3069:            default:
                   3070:         }
                   3071: END
                   3072:     } else {
                   3073:         $Javascript_toUpperCase = "";
                   3074:     }
                   3075: 
1.165     raeburn  3076:     my $radioval = "'nochange'";
1.591     raeburn  3077:     if (defined($in{'curr_authtype'})) {
                   3078:         if ($in{'curr_authtype'} ne '') {
                   3079:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3080:         }
1.174     matthew  3081:     }
1.165     raeburn  3082:     my $argfield = 'null';
1.591     raeburn  3083:     if (defined($in{'mode'})) {
1.165     raeburn  3084:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3085:             if (defined($in{'curr_autharg'})) {
                   3086:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3087:                     $argfield = "'$in{'curr_autharg'}'";
                   3088:                 }
                   3089:             }
                   3090:         }
                   3091:     }
                   3092: 
1.32      matthew  3093:     $result.=<<"END";
                   3094: var current = new Object();
1.165     raeburn  3095: current.radiovalue = $radioval;
                   3096: current.argfield = $argfield;
1.32      matthew  3097: 
                   3098: function changed_radio(choice,currentform) {
                   3099:     var choicearg = choice + 'arg';
                   3100:     // If a radio button in changed, we need to change the argfield
                   3101:     if (current.radiovalue != choice) {
                   3102:         current.radiovalue = choice;
                   3103:         if (current.argfield != null) {
                   3104:             currentform.elements[current.argfield].value = '';
                   3105:         }
                   3106:         if (choice == 'nochange') {
                   3107:             current.argfield = null;
                   3108:         } else {
                   3109:             current.argfield = choicearg;
                   3110:             switch(choice) {
                   3111:                 case 'krb': 
                   3112:                     currentform.elements[current.argfield].value = 
                   3113:                         "$in{'kerb_def_dom'}";
                   3114:                 break;
                   3115:               default:
                   3116:                 break;
                   3117:             }
                   3118:         }
                   3119:     }
                   3120:     return;
                   3121: }
1.22      www      3122: 
1.32      matthew  3123: function changed_text(choice,currentform) {
                   3124:     var choicearg = choice + 'arg';
                   3125:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3126:         $Javascript_toUpperCase
1.32      matthew  3127:         // clear old field
                   3128:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3129:             currentform.elements[current.argfield].value = '';
                   3130:         }
                   3131:         current.argfield = choicearg;
                   3132:     }
                   3133:     set_auth_radio_buttons(choice,currentform);
                   3134:     return;
1.20      www      3135: }
1.32      matthew  3136: 
                   3137: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3138:     var numauthchoices = currentform.login.length;
                   3139:     if (typeof numauthchoices  == "undefined") {
                   3140:         return;
                   3141:     } 
1.32      matthew  3142:     var i=0;
1.986     raeburn  3143:     while (i < numauthchoices) {
1.32      matthew  3144:         if (currentform.login[i].value == newvalue) { break; }
                   3145:         i++;
                   3146:     }
1.986     raeburn  3147:     if (i == numauthchoices) {
1.32      matthew  3148:         return;
                   3149:     }
                   3150:     current.radiovalue = newvalue;
                   3151:     currentform.login[i].checked = true;
                   3152:     return;
                   3153: }
                   3154: END
                   3155:     return $result;
                   3156: }
                   3157: 
1.1106    raeburn  3158: sub authform_authorwarning {
1.32      matthew  3159:     my $result='';
1.144     matthew  3160:     $result='<i>'.
                   3161:         &mt('As a general rule, only authors or co-authors should be '.
                   3162:             'filesystem authenticated '.
                   3163:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3164:     return $result;
                   3165: }
                   3166: 
1.1106    raeburn  3167: sub authform_nochange {
1.32      matthew  3168:     my %in = (
                   3169:               formname => 'document.cu',
                   3170:               kerb_def_dom => 'MSU.EDU',
                   3171:               @_,
                   3172:           );
1.1106    raeburn  3173:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3174:     my $result;
1.1104    raeburn  3175:     if (!$authnum) {
1.1105    raeburn  3176:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3177:     } else {
                   3178:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3179:                   '<input type="radio" name="login" value="nochange" '.
                   3180:                   'checked="checked" onclick="'.
1.281     albertel 3181:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3182: 	    '</label>';
1.586     raeburn  3183:     }
1.32      matthew  3184:     return $result;
                   3185: }
                   3186: 
1.591     raeburn  3187: sub authform_kerberos {
1.32      matthew  3188:     my %in = (
                   3189:               formname => 'document.cu',
                   3190:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3191:               kerb_def_auth => 'krb4',
1.32      matthew  3192:               @_,
                   3193:               );
1.586     raeburn  3194:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3195:         $autharg,$jscall,$disabled);
1.1106    raeburn  3196:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3197:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3198:        $check5 = ' checked="checked"';
1.80      albertel 3199:     } else {
1.772     bisitz   3200:        $check4 = ' checked="checked"';
1.80      albertel 3201:     }
1.1259    raeburn  3202:     if ($in{'readonly'}) {
                   3203:         $disabled = ' disabled="disabled"';
                   3204:     }
1.165     raeburn  3205:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3206:     if (defined($in{'curr_authtype'})) {
                   3207:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3208:             $krbcheck = ' checked="checked"';
1.623     raeburn  3209:             if (defined($in{'mode'})) {
                   3210:                 if ($in{'mode'} eq 'modifyuser') {
                   3211:                     $krbcheck = '';
                   3212:                 }
                   3213:             }
1.591     raeburn  3214:             if (defined($in{'curr_kerb_ver'})) {
                   3215:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3216:                     $check5 = ' checked="checked"';
1.591     raeburn  3217:                     $check4 = '';
                   3218:                 } else {
1.772     bisitz   3219:                     $check4 = ' checked="checked"';
1.591     raeburn  3220:                     $check5 = '';
                   3221:                 }
1.586     raeburn  3222:             }
1.591     raeburn  3223:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3224:                 $krbarg = $in{'curr_autharg'};
                   3225:             }
1.586     raeburn  3226:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3227:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3228:                     $result = 
                   3229:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3230:         $in{'curr_autharg'},$krbver);
                   3231:                 } else {
                   3232:                     $result =
                   3233:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3234:                 }
                   3235:                 return $result; 
                   3236:             }
                   3237:         }
                   3238:     } else {
                   3239:         if ($authnum == 1) {
1.784     bisitz   3240:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3241:         }
                   3242:     }
1.586     raeburn  3243:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3244:         return;
1.587     raeburn  3245:     } elsif ($authtype eq '') {
1.591     raeburn  3246:         if (defined($in{'mode'})) {
1.587     raeburn  3247:             if ($in{'mode'} eq 'modifycourse') {
                   3248:                 if ($authnum == 1) {
1.1259    raeburn  3249:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3250:                 }
                   3251:             }
                   3252:         }
1.586     raeburn  3253:     }
                   3254:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3255:     if ($authtype eq '') {
                   3256:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3257:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3258:                     $krbcheck.$disabled.' />';
1.586     raeburn  3259:     }
                   3260:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3261:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3262:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3263:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3264:          $in{'curr_authtype'} eq 'krb4')) {
                   3265:         $result .= &mt
1.144     matthew  3266:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3267:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3268:          '<label>'.$authtype,
1.281     albertel 3269:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3270:              'value="'.$krbarg.'" '.
1.1259    raeburn  3271:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3272:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3273:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3274: 	 '</label>');
1.586     raeburn  3275:     } elsif ($can_assign{'krb4'}) {
                   3276:         $result .= &mt
                   3277:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3278:          '[_3] Version 4 [_4]',
                   3279:          '<label>'.$authtype,
                   3280:          '</label><input type="text" size="10" name="krbarg" '.
                   3281:              'value="'.$krbarg.'" '.
1.1259    raeburn  3282:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3283:          '<label><input type="hidden" name="krbver" value="4" />',
                   3284:          '</label>');
                   3285:     } elsif ($can_assign{'krb5'}) {
                   3286:         $result .= &mt
                   3287:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3288:          '[_3] Version 5 [_4]',
                   3289:          '<label>'.$authtype,
                   3290:          '</label><input type="text" size="10" name="krbarg" '.
                   3291:              'value="'.$krbarg.'" '.
1.1259    raeburn  3292:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3293:          '<label><input type="hidden" name="krbver" value="5" />',
                   3294:          '</label>');
                   3295:     }
1.32      matthew  3296:     return $result;
                   3297: }
                   3298: 
1.1106    raeburn  3299: sub authform_internal {
1.586     raeburn  3300:     my %in = (
1.32      matthew  3301:                 formname => 'document.cu',
                   3302:                 kerb_def_dom => 'MSU.EDU',
                   3303:                 @_,
                   3304:                 );
1.1259    raeburn  3305:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3306:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3307:     if ($in{'readonly'}) {
                   3308:         $disabled = ' disabled="disabled"';
                   3309:     }
1.591     raeburn  3310:     if (defined($in{'curr_authtype'})) {
                   3311:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3312:             if ($can_assign{'int'}) {
1.772     bisitz   3313:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3314:                 if (defined($in{'mode'})) {
                   3315:                     if ($in{'mode'} eq 'modifyuser') {
                   3316:                         $intcheck = '';
                   3317:                     }
                   3318:                 }
1.591     raeburn  3319:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3320:                     $intarg = $in{'curr_autharg'};
                   3321:                 }
                   3322:             } else {
                   3323:                 $result = &mt('Currently internally authenticated.');
                   3324:                 return $result;
1.165     raeburn  3325:             }
                   3326:         }
1.586     raeburn  3327:     } else {
                   3328:         if ($authnum == 1) {
1.784     bisitz   3329:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3330:         }
                   3331:     }
                   3332:     if (!$can_assign{'int'}) {
                   3333:         return;
1.587     raeburn  3334:     } elsif ($authtype eq '') {
1.591     raeburn  3335:         if (defined($in{'mode'})) {
1.587     raeburn  3336:             if ($in{'mode'} eq 'modifycourse') {
                   3337:                 if ($authnum == 1) {
1.1259    raeburn  3338:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3339:                 }
                   3340:             }
                   3341:         }
1.165     raeburn  3342:     }
1.586     raeburn  3343:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3344:     if ($authtype eq '') {
                   3345:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3346:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3347:     }
1.605     bisitz   3348:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3349:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3350:     $result = &mt
1.144     matthew  3351:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3352:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3353:     $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  3354:     return $result;
                   3355: }
                   3356: 
1.1104    raeburn  3357: sub authform_local {
1.32      matthew  3358:     my %in = (
                   3359:               formname => 'document.cu',
                   3360:               kerb_def_dom => 'MSU.EDU',
                   3361:               @_,
                   3362:               );
1.1259    raeburn  3363:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3364:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3365:     if ($in{'readonly'}) {
                   3366:         $disabled = ' disabled="disabled"';
                   3367:     } 
1.591     raeburn  3368:     if (defined($in{'curr_authtype'})) {
                   3369:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3370:             if ($can_assign{'loc'}) {
1.772     bisitz   3371:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3372:                 if (defined($in{'mode'})) {
                   3373:                     if ($in{'mode'} eq 'modifyuser') {
                   3374:                         $loccheck = '';
                   3375:                     }
                   3376:                 }
1.591     raeburn  3377:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3378:                     $locarg = $in{'curr_autharg'};
                   3379:                 }
                   3380:             } else {
                   3381:                 $result = &mt('Currently using local (institutional) authentication.');
                   3382:                 return $result;
1.165     raeburn  3383:             }
                   3384:         }
1.586     raeburn  3385:     } else {
                   3386:         if ($authnum == 1) {
1.784     bisitz   3387:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3388:         }
                   3389:     }
                   3390:     if (!$can_assign{'loc'}) {
                   3391:         return;
1.587     raeburn  3392:     } elsif ($authtype eq '') {
1.591     raeburn  3393:         if (defined($in{'mode'})) {
1.587     raeburn  3394:             if ($in{'mode'} eq 'modifycourse') {
                   3395:                 if ($authnum == 1) {
1.1259    raeburn  3396:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3397:                 }
                   3398:             }
                   3399:         }
1.165     raeburn  3400:     }
1.586     raeburn  3401:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3402:     if ($authtype eq '') {
                   3403:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3404:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3405:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3406:     }
                   3407:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3408:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3409:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3410:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3411:     return $result;
                   3412: }
                   3413: 
1.1106    raeburn  3414: sub authform_filesystem {
1.32      matthew  3415:     my %in = (
                   3416:               formname => 'document.cu',
                   3417:               kerb_def_dom => 'MSU.EDU',
                   3418:               @_,
                   3419:               );
1.1259    raeburn  3420:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3421:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3422:     if ($in{'readonly'}) {
                   3423:         $disabled = ' disabled="disabled"';
                   3424:     }
1.591     raeburn  3425:     if (defined($in{'curr_authtype'})) {
                   3426:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3427:             if ($can_assign{'fsys'}) {
1.772     bisitz   3428:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3429:                 if (defined($in{'mode'})) {
                   3430:                     if ($in{'mode'} eq 'modifyuser') {
                   3431:                         $fsyscheck = '';
                   3432:                     }
                   3433:                 }
1.586     raeburn  3434:             } else {
                   3435:                 $result = &mt('Currently Filesystem Authenticated.');
                   3436:                 return $result;
1.1259    raeburn  3437:             }
1.586     raeburn  3438:         }
                   3439:     } else {
                   3440:         if ($authnum == 1) {
1.784     bisitz   3441:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3442:         }
                   3443:     }
                   3444:     if (!$can_assign{'fsys'}) {
                   3445:         return;
1.587     raeburn  3446:     } elsif ($authtype eq '') {
1.591     raeburn  3447:         if (defined($in{'mode'})) {
1.587     raeburn  3448:             if ($in{'mode'} eq 'modifycourse') {
                   3449:                 if ($authnum == 1) {
1.1259    raeburn  3450:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3451:                 }
                   3452:             }
                   3453:         }
1.586     raeburn  3454:     }
                   3455:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3456:     if ($authtype eq '') {
                   3457:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3458:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3459:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3460:     }
1.1310    raeburn  3461:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3462:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3463:     $result = &mt
1.144     matthew  3464:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3465:          '<label>'.$authtype,'</label>'.$autharg);
                   3466:     return $result;
                   3467: }
                   3468: 
                   3469: sub authform_lti {
                   3470:     my %in = (
                   3471:               formname => 'document.cu',
                   3472:               kerb_def_dom => 'MSU.EDU',
                   3473:               @_,
                   3474:               );
                   3475:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3476:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3477:     if ($in{'readonly'}) {
                   3478:         $disabled = ' disabled="disabled"';
                   3479:     }
                   3480:     if (defined($in{'curr_authtype'})) {
                   3481:         if ($in{'curr_authtype'} eq 'lti') {
                   3482:             if ($can_assign{'lti'}) {
                   3483:                 $lticheck = 'checked="checked" ';
                   3484:                 if (defined($in{'mode'})) {
                   3485:                     if ($in{'mode'} eq 'modifyuser') {
                   3486:                         $lticheck = '';
                   3487:                     }
                   3488:                 }
                   3489:             } else {
                   3490:                 $result = &mt('Currently LTI Authenticated.');
                   3491:                 return $result;
                   3492:             }
                   3493:         }
                   3494:     } else {
                   3495:         if ($authnum == 1) {
                   3496:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3497:         }
                   3498:     }
                   3499:     if (!$can_assign{'lti'}) {
                   3500:         return;
                   3501:     } elsif ($authtype eq '') {
                   3502:         if (defined($in{'mode'})) {
                   3503:             if ($in{'mode'} eq 'modifycourse') {
                   3504:                 if ($authnum == 1) {
                   3505:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3506:                 }
                   3507:             }
                   3508:         }
                   3509:     }
                   3510:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3511:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3512:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3513:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3514:                     $jscall.'"'.$disabled.' />';
                   3515:     }
                   3516:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3517:     if ($authtype) {
                   3518:         $result = &mt('[_1] LTI Authenticated',
                   3519:                       '<label>'.$authtype.'</label>'.$autharg);
                   3520:     } else {
                   3521:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3522:                   $autharg;
                   3523:     }
1.32      matthew  3524:     return $result;
                   3525: }
                   3526: 
1.586     raeburn  3527: sub get_assignable_auth {
                   3528:     my ($dom) = @_;
                   3529:     if ($dom eq '') {
                   3530:         $dom = $env{'request.role.domain'};
                   3531:     }
                   3532:     my %can_assign = (
                   3533:                           krb4 => 1,
                   3534:                           krb5 => 1,
                   3535:                           int  => 1,
                   3536:                           loc  => 1,
1.1310    raeburn  3537:                           lti  => 1,
1.586     raeburn  3538:                      );
                   3539:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3540:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3541:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3542:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3543:             my $context;
                   3544:             if ($env{'request.role'} =~ /^au/) {
                   3545:                 $context = 'author';
1.1259    raeburn  3546:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3547:                 $context = 'domain';
                   3548:             } elsif ($env{'request.course.id'}) {
                   3549:                 $context = 'course';
                   3550:             }
                   3551:             if ($context) {
                   3552:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3553:                    %can_assign = %{$authhash->{$context}}; 
                   3554:                 }
                   3555:             }
                   3556:         }
                   3557:     }
                   3558:     my $authnum = 0;
                   3559:     foreach my $key (keys(%can_assign)) {
                   3560:         if ($can_assign{$key}) {
                   3561:             $authnum ++;
                   3562:         }
                   3563:     }
                   3564:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3565:         $authnum --;
                   3566:     }
                   3567:     return ($authnum,%can_assign);
                   3568: }
                   3569: 
1.1331    raeburn  3570: sub check_passwd_rules {
                   3571:     my ($domain,$plainpass) = @_;
                   3572:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3573:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3574:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3575:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3576:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3577:             if ($passwdconf{'min'} > $min) {
                   3578:                 $min = $passwdconf{'min'};
                   3579:             }
1.1331    raeburn  3580:         }
                   3581:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3582:             $max = $passwdconf{'max'};
                   3583:         }
                   3584:         @chars = @{$passwdconf{'chars'}};
                   3585:     }
                   3586:     if (($min) && (length($plainpass) < $min)) {
                   3587:         push(@brokerule,'min');
                   3588:     }
                   3589:     if (($max) && (length($plainpass) > $max)) {
                   3590:         push(@brokerule,'max');
                   3591:     }
                   3592:     if (@chars) {
                   3593:         my %rules;
                   3594:         map { $rules{$_} = 1; } @chars;
                   3595:         if ($rules{'uc'}) {
                   3596:             unless ($plainpass =~ /[A-Z]/) {
                   3597:                 push(@brokerule,'uc');
                   3598:             }
                   3599:         }
                   3600:         if ($rules{'lc'}) {
1.1332    raeburn  3601:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3602:                 push(@brokerule,'lc');
                   3603:             }
                   3604:         }
                   3605:         if ($rules{'num'}) {
                   3606:             unless ($plainpass =~ /\d/) {
                   3607:                 push(@brokerule,'num');
                   3608:             }
                   3609:         }
                   3610:         if ($rules{'spec'}) {
                   3611:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3612:                 push(@brokerule,'spec');
                   3613:             }
                   3614:         }
                   3615:     }
                   3616:     if (@brokerule) {
                   3617:         my %rulenames = &Apache::lonlocal::texthash(
                   3618:             uc   => 'At least one upper case letter',
                   3619:             lc   => 'At least one lower case letter',
                   3620:             num  => 'At least one number',
                   3621:             spec => 'At least one non-alphanumeric',
                   3622:         );
                   3623:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3624:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3625:         $rulenames{'num'} .= ': 0123456789';
                   3626:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3627:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3628:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3629:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336  ! raeburn  3630:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3631:             if (grep(/^$rule$/,@brokerule)) {
                   3632:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3633:             }
                   3634:         }
                   3635:         $warning .= '</ul>';
                   3636:     }
1.1332    raeburn  3637:     if (wantarray) {
                   3638:         return @brokerule;
                   3639:     }
1.1331    raeburn  3640:     return $warning;
                   3641: }
                   3642: 
1.80      albertel 3643: ###############################################################
                   3644: ##    Get Kerberos Defaults for Domain                 ##
                   3645: ###############################################################
                   3646: ##
                   3647: ## Returns default kerberos version and an associated argument
                   3648: ## as listed in file domain.tab. If not listed, provides
                   3649: ## appropriate default domain and kerberos version.
                   3650: ##
                   3651: #-------------------------------------------
                   3652: 
                   3653: =pod
                   3654: 
1.648     raeburn  3655: =item * &get_kerberos_defaults()
1.80      albertel 3656: 
                   3657: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3658: version and domain. If not found, it defaults to version 4 and the 
                   3659: domain of the server.
1.80      albertel 3660: 
1.648     raeburn  3661: =over 4
                   3662: 
1.80      albertel 3663: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3664: 
1.648     raeburn  3665: =back
                   3666: 
                   3667: =back
                   3668: 
1.80      albertel 3669: =cut
                   3670: 
                   3671: #-------------------------------------------
                   3672: sub get_kerberos_defaults {
                   3673:     my $domain=shift;
1.641     raeburn  3674:     my ($krbdef,$krbdefdom);
                   3675:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3676:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3677:         $krbdef = $domdefaults{'auth_def'};
                   3678:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3679:     } else {
1.80      albertel 3680:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3681:         my $krbdefdom=$1;
                   3682:         $krbdefdom=~tr/a-z/A-Z/;
                   3683:         $krbdef = "krb4";
                   3684:     }
                   3685:     return ($krbdef,$krbdefdom);
                   3686: }
1.112     bowersj2 3687: 
1.32      matthew  3688: 
1.46      matthew  3689: ###############################################################
                   3690: ##                Thesaurus Functions                        ##
                   3691: ###############################################################
1.20      www      3692: 
1.46      matthew  3693: =pod
1.20      www      3694: 
1.112     bowersj2 3695: =head1 Thesaurus Functions
                   3696: 
                   3697: =over 4
                   3698: 
1.648     raeburn  3699: =item * &initialize_keywords()
1.46      matthew  3700: 
                   3701: Initializes the package variable %Keywords if it is empty.  Uses the
                   3702: package variable $thesaurus_db_file.
                   3703: 
                   3704: =cut
                   3705: 
                   3706: ###################################################
                   3707: 
                   3708: sub initialize_keywords {
                   3709:     return 1 if (scalar keys(%Keywords));
                   3710:     # If we are here, %Keywords is empty, so fill it up
                   3711:     #   Make sure the file we need exists...
                   3712:     if (! -e $thesaurus_db_file) {
                   3713:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3714:                                  " failed because it does not exist");
                   3715:         return 0;
                   3716:     }
                   3717:     #   Set up the hash as a database
                   3718:     my %thesaurus_db;
                   3719:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3720:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3721:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3722:                                  $thesaurus_db_file);
                   3723:         return 0;
                   3724:     } 
                   3725:     #  Get the average number of appearances of a word.
                   3726:     my $avecount = $thesaurus_db{'average.count'};
                   3727:     #  Put keywords (those that appear > average) into %Keywords
                   3728:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3729:         my ($count,undef) = split /:/,$data;
                   3730:         $Keywords{$word}++ if ($count > $avecount);
                   3731:     }
                   3732:     untie %thesaurus_db;
                   3733:     # Remove special values from %Keywords.
1.356     albertel 3734:     foreach my $value ('total.count','average.count') {
                   3735:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3736:   }
1.46      matthew  3737:     return 1;
                   3738: }
                   3739: 
                   3740: ###################################################
                   3741: 
                   3742: =pod
                   3743: 
1.648     raeburn  3744: =item * &keyword($word)
1.46      matthew  3745: 
                   3746: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3747: than the average number of times in the thesaurus database.  Calls 
                   3748: &initialize_keywords
                   3749: 
                   3750: =cut
                   3751: 
                   3752: ###################################################
1.20      www      3753: 
                   3754: sub keyword {
1.46      matthew  3755:     return if (!&initialize_keywords());
                   3756:     my $word=lc(shift());
                   3757:     $word=~s/\W//g;
                   3758:     return exists($Keywords{$word});
1.20      www      3759: }
1.46      matthew  3760: 
                   3761: ###############################################################
                   3762: 
                   3763: =pod 
1.20      www      3764: 
1.648     raeburn  3765: =item * &get_related_words()
1.46      matthew  3766: 
1.160     matthew  3767: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3768: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3769: will be returned.  The order of the words returned is determined by the
                   3770: database which holds them.
                   3771: 
                   3772: Uses global $thesaurus_db_file.
                   3773: 
1.1057    foxr     3774: 
1.46      matthew  3775: =cut
                   3776: 
                   3777: ###############################################################
                   3778: sub get_related_words {
                   3779:     my $keyword = shift;
                   3780:     my %thesaurus_db;
                   3781:     if (! -e $thesaurus_db_file) {
                   3782:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3783:                                  "failed because the file does not exist");
                   3784:         return ();
                   3785:     }
                   3786:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3787:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3788:         return ();
                   3789:     } 
                   3790:     my @Words=();
1.429     www      3791:     my $count=0;
1.46      matthew  3792:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3793: 	# The first element is the number of times
                   3794: 	# the word appears.  We do not need it now.
1.429     www      3795: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3796: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3797: 	my $threshold=$mostfrequentcount/10;
                   3798:         foreach my $possibleword (@RelatedWords) {
                   3799:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3800:             if ($wordcount>$threshold) {
                   3801: 		push(@Words,$word);
                   3802:                 $count++;
                   3803:                 if ($count>10) { last; }
                   3804: 	    }
1.20      www      3805:         }
                   3806:     }
1.46      matthew  3807:     untie %thesaurus_db;
                   3808:     return @Words;
1.14      harris41 3809: }
1.1090    foxr     3810: ###############################################################
                   3811: #
                   3812: #  Spell checking
                   3813: #
                   3814: 
                   3815: =pod
                   3816: 
1.1142    raeburn  3817: =back
                   3818: 
1.1090    foxr     3819: =head1 Spell checking
                   3820: 
                   3821: =over 4
                   3822: 
                   3823: =item * &check_spelling($wordlist $language)
                   3824: 
                   3825: Takes a string containing words and feeds it to an external
                   3826: spellcheck program via a pipeline. Returns a string containing
                   3827: them mis-spelled words.
                   3828: 
                   3829: Parameters:
                   3830: 
                   3831: =over 4
                   3832: 
                   3833: =item - $wordlist
                   3834: 
                   3835: String that will be fed into the spellcheck program.
                   3836: 
                   3837: =item - $language
                   3838: 
                   3839: Language string that specifies the language for which the spell
                   3840: check will be performed.
                   3841: 
                   3842: =back
                   3843: 
                   3844: =back
                   3845: 
                   3846: Note: This sub assumes that aspell is installed.
                   3847: 
                   3848: 
                   3849: =cut
                   3850: 
1.46      matthew  3851: 
1.1090    foxr     3852: sub check_spelling {
                   3853:     my ($wordlist, $language) = @_;
1.1091    foxr     3854:     my @misspellings;
                   3855:     
                   3856:     # Generate the speller and set the langauge.
                   3857:     # if explicitly selected:
1.1090    foxr     3858: 
1.1091    foxr     3859:     my $speller = Text::Aspell->new;
1.1090    foxr     3860:     if ($language) {
1.1091    foxr     3861: 	$speller->set_option('lang', $language);
1.1090    foxr     3862:     }
                   3863: 
1.1091    foxr     3864:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3865: 
1.1091    foxr     3866:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3867: 
1.1091    foxr     3868:     foreach my $word (@words) {
                   3869: 	if(! $speller->check($word)) {
                   3870: 	    push(@misspellings, $word);
1.1090    foxr     3871: 	}
                   3872:     }
1.1091    foxr     3873:     return join(' ', @misspellings);
                   3874:     
1.1090    foxr     3875: }
                   3876: 
1.61      www      3877: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3878: =pod
                   3879: 
1.112     bowersj2 3880: =head1 User Name Functions
                   3881: 
                   3882: =over 4
                   3883: 
1.648     raeburn  3884: =item * &plainname($uname,$udom,$first)
1.81      albertel 3885: 
1.112     bowersj2 3886: Takes a users logon name and returns it as a string in
1.226     albertel 3887: "first middle last generation" form 
                   3888: if $first is set to 'lastname' then it returns it as
                   3889: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3890: 
                   3891: =cut
1.61      www      3892: 
1.295     www      3893: 
1.81      albertel 3894: ###############################################################
1.61      www      3895: sub plainname {
1.226     albertel 3896:     my ($uname,$udom,$first)=@_;
1.537     albertel 3897:     return if (!defined($uname) || !defined($udom));
1.295     www      3898:     my %names=&getnames($uname,$udom);
1.226     albertel 3899:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3900: 					  $names{'middlename'},
                   3901: 					  $names{'lastname'},
                   3902: 					  $names{'generation'},$first);
                   3903:     $name=~s/^\s+//;
1.62      www      3904:     $name=~s/\s+$//;
                   3905:     $name=~s/\s+/ /g;
1.353     albertel 3906:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3907:     return $name;
1.61      www      3908: }
1.66      www      3909: 
                   3910: # -------------------------------------------------------------------- Nickname
1.81      albertel 3911: =pod
                   3912: 
1.648     raeburn  3913: =item * &nickname($uname,$udom)
1.81      albertel 3914: 
                   3915: Gets a users name and returns it as a string as
                   3916: 
                   3917: "&quot;nickname&quot;"
1.66      www      3918: 
1.81      albertel 3919: if the user has a nickname or
                   3920: 
                   3921: "first middle last generation"
                   3922: 
                   3923: if the user does not
                   3924: 
                   3925: =cut
1.66      www      3926: 
                   3927: sub nickname {
                   3928:     my ($uname,$udom)=@_;
1.537     albertel 3929:     return if (!defined($uname) || !defined($udom));
1.295     www      3930:     my %names=&getnames($uname,$udom);
1.68      albertel 3931:     my $name=$names{'nickname'};
1.66      www      3932:     if ($name) {
                   3933:        $name='&quot;'.$name.'&quot;'; 
                   3934:     } else {
                   3935:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3936: 	     $names{'lastname'}.' '.$names{'generation'};
                   3937:        $name=~s/\s+$//;
                   3938:        $name=~s/\s+/ /g;
                   3939:     }
                   3940:     return $name;
                   3941: }
                   3942: 
1.295     www      3943: sub getnames {
                   3944:     my ($uname,$udom)=@_;
1.537     albertel 3945:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3946:     if ($udom eq 'public' && $uname eq 'public') {
                   3947: 	return ('lastname' => &mt('Public'));
                   3948:     }
1.295     www      3949:     my $id=$uname.':'.$udom;
                   3950:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3951:     if ($cached) {
                   3952: 	return %{$names};
                   3953:     } else {
                   3954: 	my %loadnames=&Apache::lonnet::get('environment',
                   3955:                     ['firstname','middlename','lastname','generation','nickname'],
                   3956: 					 $udom,$uname);
                   3957: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3958: 	return %loadnames;
                   3959:     }
                   3960: }
1.61      www      3961: 
1.542     raeburn  3962: # -------------------------------------------------------------------- getemails
1.648     raeburn  3963: 
1.542     raeburn  3964: =pod
                   3965: 
1.648     raeburn  3966: =item * &getemails($uname,$udom)
1.542     raeburn  3967: 
                   3968: Gets a user's email information and returns it as a hash with keys:
                   3969: notification, critnotification, permanentemail
                   3970: 
                   3971: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3972: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3973:  
1.648     raeburn  3974: 
1.542     raeburn  3975: =cut
                   3976: 
1.648     raeburn  3977: 
1.466     albertel 3978: sub getemails {
                   3979:     my ($uname,$udom)=@_;
                   3980:     if ($udom eq 'public' && $uname eq 'public') {
                   3981: 	return;
                   3982:     }
1.467     www      3983:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3984:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3985:     my $id=$uname.':'.$udom;
                   3986:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3987:     if ($cached) {
                   3988: 	return %{$names};
                   3989:     } else {
                   3990: 	my %loadnames=&Apache::lonnet::get('environment',
                   3991:                     			   ['notification','critnotification',
                   3992: 					    'permanentemail'],
                   3993: 					   $udom,$uname);
                   3994: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3995: 	return %loadnames;
                   3996:     }
                   3997: }
                   3998: 
1.551     albertel 3999: sub flush_email_cache {
                   4000:     my ($uname,$udom)=@_;
                   4001:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4002:     if (!$uname) { $uname=$env{'user.name'};   }
                   4003:     return if ($udom eq 'public' && $uname eq 'public');
                   4004:     my $id=$uname.':'.$udom;
                   4005:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4006: }
                   4007: 
1.728     raeburn  4008: # -------------------------------------------------------------------- getlangs
                   4009: 
                   4010: =pod
                   4011: 
                   4012: =item * &getlangs($uname,$udom)
                   4013: 
                   4014: Gets a user's language preference and returns it as a hash with key:
                   4015: language.
                   4016: 
                   4017: =cut
                   4018: 
                   4019: 
                   4020: sub getlangs {
                   4021:     my ($uname,$udom) = @_;
                   4022:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4023:     if (!$uname) { $uname=$env{'user.name'};   }
                   4024:     my $id=$uname.':'.$udom;
                   4025:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4026:     if ($cached) {
                   4027:         return %{$langs};
                   4028:     } else {
                   4029:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4030:                                            $udom,$uname);
                   4031:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4032:         return %loadlangs;
                   4033:     }
                   4034: }
                   4035: 
                   4036: sub flush_langs_cache {
                   4037:     my ($uname,$udom)=@_;
                   4038:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4039:     if (!$uname) { $uname=$env{'user.name'};   }
                   4040:     return if ($udom eq 'public' && $uname eq 'public');
                   4041:     my $id=$uname.':'.$udom;
                   4042:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4043: }
                   4044: 
1.61      www      4045: # ------------------------------------------------------------------ Screenname
1.81      albertel 4046: 
                   4047: =pod
                   4048: 
1.648     raeburn  4049: =item * &screenname($uname,$udom)
1.81      albertel 4050: 
                   4051: Gets a users screenname and returns it as a string
                   4052: 
                   4053: =cut
1.61      www      4054: 
                   4055: sub screenname {
                   4056:     my ($uname,$udom)=@_;
1.258     albertel 4057:     if ($uname eq $env{'user.name'} &&
                   4058: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4059:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4060:     return $names{'screenname'};
1.62      www      4061: }
                   4062: 
1.212     albertel 4063: 
1.802     bisitz   4064: # ------------------------------------------------------------- Confirm Wrapper
                   4065: =pod
                   4066: 
1.1142    raeburn  4067: =item * &confirmwrapper($message)
1.802     bisitz   4068: 
                   4069: Wrap messages about completion of operation in box
                   4070: 
                   4071: =cut
                   4072: 
                   4073: sub confirmwrapper {
                   4074:     my ($message)=@_;
                   4075:     if ($message) {
                   4076:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4077:                .$message."\n"
                   4078:                .'</div>'."\n";
                   4079:     } else {
                   4080:         return $message;
                   4081:     }
                   4082: }
                   4083: 
1.62      www      4084: # ------------------------------------------------------------- Message Wrapper
                   4085: 
                   4086: sub messagewrapper {
1.369     www      4087:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4088:     return 
1.441     albertel 4089:         '<a href="/adm/email?compose=individual&amp;'.
                   4090:         'recname='.$username.'&amp;recdom='.$domain.
                   4091: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4092:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4093: }
1.802     bisitz   4094: 
1.74      www      4095: # --------------------------------------------------------------- Notes Wrapper
                   4096: 
                   4097: sub noteswrapper {
                   4098:     my ($link,$un,$do)=@_;
                   4099:     return 
1.896     amueller 4100: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4101: }
1.802     bisitz   4102: 
1.62      www      4103: # ------------------------------------------------------------- Aboutme Wrapper
                   4104: 
                   4105: sub aboutmewrapper {
1.1070    raeburn  4106:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4107:     if (!defined($username)  && !defined($domain)) {
                   4108:         return;
                   4109:     }
1.1096    raeburn  4110:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4111: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4112: }
                   4113: 
                   4114: # ------------------------------------------------------------ Syllabus Wrapper
                   4115: 
                   4116: sub syllabuswrapper {
1.707     bisitz   4117:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4118:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4119: }
1.14      harris41 4120: 
1.802     bisitz   4121: # -----------------------------------------------------------------------------
                   4122: 
1.208     matthew  4123: sub track_student_link {
1.887     raeburn  4124:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4125:     my $link ="/adm/trackstudent?";
1.208     matthew  4126:     my $title = 'View recent activity';
                   4127:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4128:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4129:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4130:         $title .= ' of this student';
1.268     albertel 4131:     } 
1.208     matthew  4132:     if (defined($target) && $target !~ /^\s*$/) {
                   4133:         $target = qq{target="$target"};
                   4134:     } else {
                   4135:         $target = '';
                   4136:     }
1.268     albertel 4137:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4138:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4139:     $title = &mt($title);
                   4140:     $linktext = &mt($linktext);
1.448     albertel 4141:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4142: 	&help_open_topic('View_recent_activity');
1.208     matthew  4143: }
                   4144: 
1.781     raeburn  4145: sub slot_reservations_link {
                   4146:     my ($linktext,$sname,$sdom,$target) = @_;
                   4147:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4148:     my $title = 'View slot reservation history';
                   4149:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4150:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4151:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4152:         $title .= ' of this student';
                   4153:     }
                   4154:     if (defined($target) && $target !~ /^\s*$/) {
                   4155:         $target = qq{target="$target"};
                   4156:     } else {
                   4157:         $target = '';
                   4158:     }
                   4159:     $title = &mt($title);
                   4160:     $linktext = &mt($linktext);
                   4161:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4162: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4163: 
                   4164: }
                   4165: 
1.508     www      4166: # ===================================================== Display a student photo
                   4167: 
                   4168: 
1.509     albertel 4169: sub student_image_tag {
1.508     www      4170:     my ($domain,$user)=@_;
                   4171:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4172:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4173: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4174:     } else {
                   4175: 	return '';
                   4176:     }
                   4177: }
                   4178: 
1.112     bowersj2 4179: =pod
                   4180: 
                   4181: =back
                   4182: 
                   4183: =head1 Access .tab File Data
                   4184: 
                   4185: =over 4
                   4186: 
1.648     raeburn  4187: =item * &languageids() 
1.112     bowersj2 4188: 
                   4189: returns list of all language ids
                   4190: 
                   4191: =cut
                   4192: 
1.14      harris41 4193: sub languageids {
1.16      harris41 4194:     return sort(keys(%language));
1.14      harris41 4195: }
                   4196: 
1.112     bowersj2 4197: =pod
                   4198: 
1.648     raeburn  4199: =item * &languagedescription() 
1.112     bowersj2 4200: 
                   4201: returns description of a specified language id
                   4202: 
                   4203: =cut
                   4204: 
1.14      harris41 4205: sub languagedescription {
1.125     www      4206:     my $code=shift;
                   4207:     return  ($supported_language{$code}?'* ':'').
                   4208:             $language{$code}.
1.126     www      4209: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4210: }
                   4211: 
1.1048    foxr     4212: =pod
                   4213: 
                   4214: =item * &plainlanguagedescription
                   4215: 
                   4216: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4217: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4218: 
                   4219: =cut
                   4220: 
1.145     www      4221: sub plainlanguagedescription {
                   4222:     my $code=shift;
                   4223:     return $language{$code};
                   4224: }
                   4225: 
1.1048    foxr     4226: =pod
                   4227: 
                   4228: =item * &supportedlanguagecode
                   4229: 
                   4230: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4231: code.
                   4232: 
                   4233: =cut
                   4234: 
1.145     www      4235: sub supportedlanguagecode {
                   4236:     my $code=shift;
                   4237:     return $supported_language{$code};
1.97      www      4238: }
                   4239: 
1.112     bowersj2 4240: =pod
                   4241: 
1.1048    foxr     4242: =item * &latexlanguage()
                   4243: 
                   4244: Given a language key code returns the correspondnig language to use
                   4245: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4246: is no supported hyphenation for the language code.
                   4247: 
                   4248: =cut
                   4249: 
                   4250: sub latexlanguage {
                   4251:     my $code = shift;
                   4252:     return $latex_language{$code};
                   4253: }
                   4254: 
                   4255: =pod
                   4256: 
                   4257: =item * &latexhyphenation()
                   4258: 
                   4259: Same as above but what's supplied is the language as it might be stored
                   4260: in the metadata.
                   4261: 
                   4262: =cut
                   4263: 
                   4264: sub latexhyphenation {
                   4265:     my $key = shift;
                   4266:     return $latex_language_bykey{$key};
                   4267: }
                   4268: 
                   4269: =pod
                   4270: 
1.648     raeburn  4271: =item * &copyrightids() 
1.112     bowersj2 4272: 
                   4273: returns list of all copyrights
                   4274: 
                   4275: =cut
                   4276: 
                   4277: sub copyrightids {
                   4278:     return sort(keys(%cprtag));
                   4279: }
                   4280: 
                   4281: =pod
                   4282: 
1.648     raeburn  4283: =item * &copyrightdescription() 
1.112     bowersj2 4284: 
                   4285: returns description of a specified copyright id
                   4286: 
                   4287: =cut
                   4288: 
                   4289: sub copyrightdescription {
1.166     www      4290:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4291: }
1.197     matthew  4292: 
                   4293: =pod
                   4294: 
1.648     raeburn  4295: =item * &source_copyrightids() 
1.192     taceyjo1 4296: 
                   4297: returns list of all source copyrights
                   4298: 
                   4299: =cut
                   4300: 
                   4301: sub source_copyrightids {
                   4302:     return sort(keys(%scprtag));
                   4303: }
                   4304: 
                   4305: =pod
                   4306: 
1.648     raeburn  4307: =item * &source_copyrightdescription() 
1.192     taceyjo1 4308: 
                   4309: returns description of a specified source copyright id
                   4310: 
                   4311: =cut
                   4312: 
                   4313: sub source_copyrightdescription {
                   4314:     return &mt($scprtag{shift(@_)});
                   4315: }
1.112     bowersj2 4316: 
                   4317: =pod
                   4318: 
1.648     raeburn  4319: =item * &filecategories() 
1.112     bowersj2 4320: 
                   4321: returns list of all file categories
                   4322: 
                   4323: =cut
                   4324: 
                   4325: sub filecategories {
                   4326:     return sort(keys(%category_extensions));
                   4327: }
                   4328: 
                   4329: =pod
                   4330: 
1.648     raeburn  4331: =item * &filecategorytypes() 
1.112     bowersj2 4332: 
                   4333: returns list of file types belonging to a given file
                   4334: category
                   4335: 
                   4336: =cut
                   4337: 
                   4338: sub filecategorytypes {
1.356     albertel 4339:     my ($cat) = @_;
1.1248    raeburn  4340:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4341:         return @{$category_extensions{lc($cat)}};
                   4342:     } else {
                   4343:         return ();
                   4344:     }
1.112     bowersj2 4345: }
                   4346: 
                   4347: =pod
                   4348: 
1.648     raeburn  4349: =item * &fileembstyle() 
1.112     bowersj2 4350: 
                   4351: returns embedding style for a specified file type
                   4352: 
                   4353: =cut
                   4354: 
                   4355: sub fileembstyle {
                   4356:     return $fe{lc(shift(@_))};
1.169     www      4357: }
                   4358: 
1.351     www      4359: sub filemimetype {
                   4360:     return $fm{lc(shift(@_))};
                   4361: }
                   4362: 
1.169     www      4363: 
                   4364: sub filecategoryselect {
                   4365:     my ($name,$value)=@_;
1.189     matthew  4366:     return &select_form($value,$name,
1.970     raeburn  4367:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4368: }
                   4369: 
                   4370: =pod
                   4371: 
1.648     raeburn  4372: =item * &filedescription() 
1.112     bowersj2 4373: 
                   4374: returns description for a specified file type
                   4375: 
                   4376: =cut
                   4377: 
                   4378: sub filedescription {
1.188     matthew  4379:     my $file_description = $fd{lc(shift())};
                   4380:     $file_description =~ s:([\[\]]):~$1:g;
                   4381:     return &mt($file_description);
1.112     bowersj2 4382: }
                   4383: 
                   4384: =pod
                   4385: 
1.648     raeburn  4386: =item * &filedescriptionex() 
1.112     bowersj2 4387: 
                   4388: returns description for a specified file type with
                   4389: extra formatting
                   4390: 
                   4391: =cut
                   4392: 
                   4393: sub filedescriptionex {
                   4394:     my $ex=shift;
1.188     matthew  4395:     my $file_description = $fd{lc($ex)};
                   4396:     $file_description =~ s:([\[\]]):~$1:g;
                   4397:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4398: }
                   4399: 
                   4400: # End of .tab access
                   4401: =pod
                   4402: 
                   4403: =back
                   4404: 
                   4405: =cut
                   4406: 
                   4407: # ------------------------------------------------------------------ File Types
                   4408: sub fileextensions {
                   4409:     return sort(keys(%fe));
                   4410: }
                   4411: 
1.97      www      4412: # ----------------------------------------------------------- Display Languages
                   4413: # returns a hash with all desired display languages
                   4414: #
                   4415: 
                   4416: sub display_languages {
                   4417:     my %languages=();
1.695     raeburn  4418:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4419: 	$languages{$lang}=1;
1.97      www      4420:     }
                   4421:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4422:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4423: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4424: 	    $languages{$lang}=1;
1.97      www      4425:         }
                   4426:     }
                   4427:     return %languages;
1.14      harris41 4428: }
                   4429: 
1.582     albertel 4430: sub languages {
                   4431:     my ($possible_langs) = @_;
1.695     raeburn  4432:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4433:     if (!ref($possible_langs)) {
                   4434: 	if( wantarray ) {
                   4435: 	    return @preferred_langs;
                   4436: 	} else {
                   4437: 	    return $preferred_langs[0];
                   4438: 	}
                   4439:     }
                   4440:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4441:     my @preferred_possibilities;
                   4442:     foreach my $preferred_lang (@preferred_langs) {
                   4443: 	if (exists($possibilities{$preferred_lang})) {
                   4444: 	    push(@preferred_possibilities, $preferred_lang);
                   4445: 	}
                   4446:     }
                   4447:     if( wantarray ) {
                   4448: 	return @preferred_possibilities;
                   4449:     }
                   4450:     return $preferred_possibilities[0];
                   4451: }
                   4452: 
1.742     raeburn  4453: sub user_lang {
                   4454:     my ($touname,$toudom,$fromcid) = @_;
                   4455:     my @userlangs;
                   4456:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4457:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4458:                     $env{'course.'.$fromcid.'.languages'}));
                   4459:     } else {
                   4460:         my %langhash = &getlangs($touname,$toudom);
                   4461:         if ($langhash{'languages'} ne '') {
                   4462:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4463:         } else {
                   4464:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4465:             if ($domdefs{'lang_def'} ne '') {
                   4466:                 @userlangs = ($domdefs{'lang_def'});
                   4467:             }
                   4468:         }
                   4469:     }
                   4470:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4471:     my $user_lh = Apache::localize->get_handle(@languages);
                   4472:     return $user_lh;
                   4473: }
                   4474: 
                   4475: 
1.112     bowersj2 4476: ###############################################################
                   4477: ##               Student Answer Attempts                     ##
                   4478: ###############################################################
                   4479: 
                   4480: =pod
                   4481: 
                   4482: =head1 Alternate Problem Views
                   4483: 
                   4484: =over 4
                   4485: 
1.648     raeburn  4486: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4487:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4488: 
                   4489: Return string with previous attempt on problem. Arguments:
                   4490: 
                   4491: =over 4
                   4492: 
                   4493: =item * $symb: Problem, including path
                   4494: 
                   4495: =item * $username: username of the desired student
                   4496: 
                   4497: =item * $domain: domain of the desired student
1.14      harris41 4498: 
1.112     bowersj2 4499: =item * $course: Course ID
1.14      harris41 4500: 
1.112     bowersj2 4501: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4502:     something
1.14      harris41 4503: 
1.112     bowersj2 4504: =item * $regexp: if string matches this regexp, the string will be
                   4505:     sent to $gradesub
1.14      harris41 4506: 
1.112     bowersj2 4507: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4508: 
1.1199    raeburn  4509: =item * $usec: section of the desired student
                   4510: 
                   4511: =item * $identifier: counter for student (multiple students one problem) or 
                   4512:     problem (one student; whole sequence).
                   4513: 
1.112     bowersj2 4514: =back
1.14      harris41 4515: 
1.112     bowersj2 4516: The output string is a table containing all desired attempts, if any.
1.16      harris41 4517: 
1.112     bowersj2 4518: =cut
1.1       albertel 4519: 
                   4520: sub get_previous_attempt {
1.1199    raeburn  4521:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4522:   my $prevattempts='';
1.43      ng       4523:   no strict 'refs';
1.1       albertel 4524:   if ($symb) {
1.3       albertel 4525:     my (%returnhash)=
                   4526:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4527:     if ($returnhash{'version'}) {
                   4528:       my %lasthash=();
                   4529:       my $version;
                   4530:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4531:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4532:             if ($key =~ /\.rawrndseed$/) {
                   4533:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4534:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4535:             } else {
                   4536:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4537:             }
1.19      harris41 4538:         }
1.1       albertel 4539:       }
1.596     albertel 4540:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4541:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4542:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4543:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4544:       foreach my $key (sort(keys(%lasthash))) {
                   4545: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4546: 	if ($#parts > 0) {
1.31      albertel 4547: 	  my $data=$parts[-1];
1.989     raeburn  4548:           next if ($data eq 'foilorder');
1.31      albertel 4549: 	  pop(@parts);
1.1010    www      4550:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4551:           if ($data eq 'type') {
                   4552:               unless ($showsurv) {
                   4553:                   my $id = join(',',@parts);
                   4554:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4555:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4556:                       $lasthidden{$ign.'.'.$id} = 1;
                   4557:                   }
1.945     raeburn  4558:               }
1.1199    raeburn  4559:               if ($identifier ne '') {
                   4560:                   my $id = join(',',@parts);
                   4561:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4562:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4563:                       $hidestatus{$ign.'.'.$id} = 1;
                   4564:                   }
                   4565:               }
                   4566:           } elsif ($data eq 'regrader') {
                   4567:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4568:                   my $id = join(',',@parts);
                   4569:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4570:               }
1.1010    www      4571:           } 
1.31      albertel 4572: 	} else {
1.41      ng       4573: 	  if ($#parts == 0) {
                   4574: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4575: 	  } else {
                   4576: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4577: 	  }
1.31      albertel 4578: 	}
1.16      harris41 4579:       }
1.596     albertel 4580:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4581:       if ($getattempt eq '') {
1.1199    raeburn  4582:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4583:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4584:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4585:                 foreach my $id (keys(%regraded)) {
                   4586:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4587:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4588:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4589:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4590:                     }
                   4591:                 }
                   4592:             }
1.1200    raeburn  4593:         }
                   4594: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4595:             my (@hidden,@unsolved);
1.945     raeburn  4596:             if (%typeparts) {
                   4597:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4598:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4599:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4600:                         push(@hidden,$id);
1.1199    raeburn  4601:                     } elsif ($identifier ne '') {
                   4602:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4603:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4604:                                 ($hidestatus{$id})) {
1.1200    raeburn  4605:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4606:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4607:                                 push(@{$solved{$id}},$version);
                   4608:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4609:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4610:                                 my $skip;
                   4611:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4612:                                     foreach my $reset (@{$resets{$id}}) {
                   4613:                                         if ($reset > $solved{$id}[-1]) {
                   4614:                                             $skip=1;
                   4615:                                             last;
                   4616:                                         }
                   4617:                                     }
                   4618:                                 }
                   4619:                                 unless ($skip) {
                   4620:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4621:                                     push(@unsolved,$partslist);
                   4622:                                 }
                   4623:                             }
                   4624:                         }
1.945     raeburn  4625:                     }
                   4626:                 }
                   4627:             }
                   4628:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4629:                            '<td>'.&mt('Transaction [_1]',$version);
                   4630:             if (@unsolved) {
                   4631:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4632:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4633:                                  &mt('Hide').'</label></span>';
                   4634:             }
                   4635:             $prevattempts .= '</td>';
1.945     raeburn  4636:             if (@hidden) {
                   4637:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4638:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4639:                     my $hide;
                   4640:                     foreach my $id (@hidden) {
                   4641:                         if ($key =~ /^\Q$id\E/) {
                   4642:                             $hide = 1;
                   4643:                             last;
                   4644:                         }
                   4645:                     }
                   4646:                     if ($hide) {
                   4647:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4648:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4649:                             my $value = &format_previous_attempt_value($key,
                   4650:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4651:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4652:                         } else {
                   4653:                             $prevattempts.='<td>&nbsp;</td>';
                   4654:                         }
                   4655:                     } else {
                   4656:                         if ($key =~ /\./) {
1.1212    raeburn  4657:                             my $value = $returnhash{$version.':'.$key};
                   4658:                             if ($key =~ /\.rndseed$/) {
                   4659:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4660:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4661:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4662:                                 }
                   4663:                             }
                   4664:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4665:                                            '&nbsp;</td>';
1.945     raeburn  4666:                         } else {
                   4667:                             $prevattempts.='<td>&nbsp;</td>';
                   4668:                         }
                   4669:                     }
                   4670:                 }
                   4671:             } else {
                   4672: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4673:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4674:                     my $value = $returnhash{$version.':'.$key};
                   4675:                     if ($key =~ /\.rndseed$/) {
                   4676:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4677:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4678:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4679:                         }
                   4680:                     }
                   4681:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4682:                                    '&nbsp;</td>';
1.945     raeburn  4683: 	        }
                   4684:             }
                   4685: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4686: 	 }
1.1       albertel 4687:       }
1.945     raeburn  4688:       my @currhidden = keys(%lasthidden);
1.596     albertel 4689:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4690:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4691:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4692:           if (%typeparts) {
                   4693:               my $hidden;
                   4694:               foreach my $id (@currhidden) {
                   4695:                   if ($key =~ /^\Q$id\E/) {
                   4696:                       $hidden = 1;
                   4697:                       last;
                   4698:                   }
                   4699:               }
                   4700:               if ($hidden) {
                   4701:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4702:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4703:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4704:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4705:                           $value = &$gradesub($value);
                   4706:                       }
1.1173    kruse    4707:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4708:                   } else {
                   4709:                       $prevattempts.='<td>&nbsp;</td>';
                   4710:                   }
                   4711:               } else {
                   4712:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4713:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4714:                       $value = &$gradesub($value);
                   4715:                   }
1.1173    kruse    4716:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4717:               }
                   4718:           } else {
                   4719: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4720: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4721:                   $value = &$gradesub($value);
                   4722:               }
1.1173    kruse    4723: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4724:           }
1.16      harris41 4725:       }
1.596     albertel 4726:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4727:     } else {
1.1305    raeburn  4728:       my $msg;
                   4729:       if ($symb =~ /ext\.tool$/) {
                   4730:           $msg = &mt('No grade passed back.');
                   4731:       } else {
                   4732:           $msg = &mt('Nothing submitted - no attempts.');
                   4733:       }
1.596     albertel 4734:       $prevattempts=
                   4735: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  4736: 	  '<td>'.$msg.'</td>'.
1.596     albertel 4737: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4738:     }
                   4739:   } else {
1.596     albertel 4740:     $prevattempts=
                   4741: 	  &start_data_table().&start_data_table_row().
                   4742: 	  '<td>'.&mt('No data.').'</td>'.
                   4743: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4744:   }
1.10      albertel 4745: }
                   4746: 
1.581     albertel 4747: sub format_previous_attempt_value {
                   4748:     my ($key,$value) = @_;
1.1011    www      4749:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4750:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4751:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4752:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4753:     } elsif ($key =~ /answerstring$/) {
                   4754:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4755:         my @answer = %answers;
                   4756:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4757:         my @anskeys = sort(keys(%answers));
                   4758:         if (@anskeys == 1) {
                   4759:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4760:             if ($answer =~ m{\0}) {
                   4761:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4762:             }
                   4763:             my $tag_internal_answer_name = 'INTERNAL';
                   4764:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4765:                 $value = $answer; 
                   4766:             } else {
                   4767:                 $value = $anskeys[0].'='.$answer;
                   4768:             }
                   4769:         } else {
                   4770:             foreach my $ans (@anskeys) {
                   4771:                 my $answer = $answers{$ans};
1.1001    raeburn  4772:                 if ($answer =~ m{\0}) {
                   4773:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4774:                 }
                   4775:                 $value .=  $ans.'='.$answer.'<br />';;
                   4776:             } 
                   4777:         }
1.581     albertel 4778:     } else {
1.1173    kruse    4779:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4780:     }
                   4781:     return $value;
                   4782: }
                   4783: 
                   4784: 
1.107     albertel 4785: sub relative_to_absolute {
                   4786:     my ($url,$output)=@_;
                   4787:     my $parser=HTML::TokeParser->new(\$output);
                   4788:     my $token;
                   4789:     my $thisdir=$url;
                   4790:     my @rlinks=();
                   4791:     while ($token=$parser->get_token) {
                   4792: 	if ($token->[0] eq 'S') {
                   4793: 	    if ($token->[1] eq 'a') {
                   4794: 		if ($token->[2]->{'href'}) {
                   4795: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4796: 		}
                   4797: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4798: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4799: 	    } elsif ($token->[1] eq 'base') {
                   4800: 		$thisdir=$token->[2]->{'href'};
                   4801: 	    }
                   4802: 	}
                   4803:     }
                   4804:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4805:     foreach my $link (@rlinks) {
1.726     raeburn  4806: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4807: 		($link=~/^\//) ||
                   4808: 		($link=~/^javascript:/i) ||
                   4809: 		($link=~/^mailto:/i) ||
                   4810: 		($link=~/^\#/)) {
                   4811: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4812: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4813: 	}
                   4814:     }
                   4815: # -------------------------------------------------- Deal with Applet codebases
                   4816:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4817:     return $output;
                   4818: }
                   4819: 
1.112     bowersj2 4820: =pod
                   4821: 
1.648     raeburn  4822: =item * &get_student_view()
1.112     bowersj2 4823: 
                   4824: show a snapshot of what student was looking at
                   4825: 
                   4826: =cut
                   4827: 
1.10      albertel 4828: sub get_student_view {
1.186     albertel 4829:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4830:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4831:   my (%form);
1.10      albertel 4832:   my @elements=('symb','courseid','domain','username');
                   4833:   foreach my $element (@elements) {
1.186     albertel 4834:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4835:   }
1.186     albertel 4836:   if (defined($moreenv)) {
                   4837:       %form=(%form,%{$moreenv});
                   4838:   }
1.236     albertel 4839:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4840:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  4841:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   4842:       $feedurl =~ s{^/adm/wrapper}{};
                   4843:   }
1.650     www      4844:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4845:   $userview=~s/\<body[^\>]*\>//gi;
                   4846:   $userview=~s/\<\/body\>//gi;
                   4847:   $userview=~s/\<html\>//gi;
                   4848:   $userview=~s/\<\/html\>//gi;
                   4849:   $userview=~s/\<head\>//gi;
                   4850:   $userview=~s/\<\/head\>//gi;
                   4851:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4852:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4853:   if (wantarray) {
                   4854:      return ($userview,$response);
                   4855:   } else {
                   4856:      return $userview;
                   4857:   }
                   4858: }
                   4859: 
                   4860: sub get_student_view_with_retries {
                   4861:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4862: 
                   4863:     my $ok = 0;                 # True if we got a good response.
                   4864:     my $content;
                   4865:     my $response;
                   4866: 
                   4867:     # Try to get the student_view done. within the retries count:
                   4868:     
                   4869:     do {
                   4870:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4871:          $ok      = $response->is_success;
                   4872:          if (!$ok) {
                   4873:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4874:          }
                   4875:          $retries--;
                   4876:     } while (!$ok && ($retries > 0));
                   4877:     
                   4878:     if (!$ok) {
                   4879:        $content = '';          # On error return an empty content.
                   4880:     }
1.651     www      4881:     if (wantarray) {
                   4882:        return ($content, $response);
                   4883:     } else {
                   4884:        return $content;
                   4885:     }
1.11      albertel 4886: }
                   4887: 
1.112     bowersj2 4888: =pod
                   4889: 
1.648     raeburn  4890: =item * &get_student_answers() 
1.112     bowersj2 4891: 
                   4892: show a snapshot of how student was answering problem
                   4893: 
                   4894: =cut
                   4895: 
1.11      albertel 4896: sub get_student_answers {
1.100     sakharuk 4897:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4898:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4899:   my (%moreenv);
1.11      albertel 4900:   my @elements=('symb','courseid','domain','username');
                   4901:   foreach my $element (@elements) {
1.186     albertel 4902:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4903:   }
1.186     albertel 4904:   $moreenv{'grade_target'}='answer';
                   4905:   %moreenv=(%form,%moreenv);
1.497     raeburn  4906:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4907:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4908:   return $userview;
1.1       albertel 4909: }
1.116     albertel 4910: 
                   4911: =pod
                   4912: 
                   4913: =item * &submlink()
                   4914: 
1.242     albertel 4915: Inputs: $text $uname $udom $symb $target
1.116     albertel 4916: 
                   4917: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4918: 
                   4919: =cut
                   4920: 
                   4921: ###############################################
                   4922: sub submlink {
1.242     albertel 4923:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4924:     if (!($uname && $udom)) {
                   4925: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4926: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4927: 	if (!$symb) { $symb=$cursymb; }
                   4928:     }
1.254     matthew  4929:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4930:     $symb=&escape($symb);
1.960     bisitz   4931:     if ($target) { $target=" target=\"$target\""; }
                   4932:     return
                   4933:         '<a href="/adm/grades?command=submission'.
                   4934:         '&amp;symb='.$symb.
                   4935:         '&amp;student='.$uname.
                   4936:         '&amp;userdom='.$udom.'"'.
                   4937:         $target.'>'.$text.'</a>';
1.242     albertel 4938: }
                   4939: ##############################################
                   4940: 
                   4941: =pod
                   4942: 
                   4943: =item * &pgrdlink()
                   4944: 
                   4945: Inputs: $text $uname $udom $symb $target
                   4946: 
                   4947: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4948: 
                   4949: =cut
                   4950: 
                   4951: ###############################################
                   4952: sub pgrdlink {
                   4953:     my $link=&submlink(@_);
                   4954:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4955:     return $link;
                   4956: }
                   4957: ##############################################
                   4958: 
                   4959: =pod
                   4960: 
                   4961: =item * &pprmlink()
                   4962: 
                   4963: Inputs: $text $uname $udom $symb $target
                   4964: 
                   4965: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4966: student and a specific resource
1.242     albertel 4967: 
                   4968: =cut
                   4969: 
                   4970: ###############################################
                   4971: sub pprmlink {
                   4972:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4973:     if (!($uname && $udom)) {
                   4974: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4975: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4976: 	if (!$symb) { $symb=$cursymb; }
                   4977:     }
1.254     matthew  4978:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4979:     $symb=&escape($symb);
1.242     albertel 4980:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4981:     return '<a href="/adm/parmset?command=set&amp;'.
                   4982: 	'symb='.$symb.'&amp;uname='.$uname.
                   4983: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4984: }
                   4985: ##############################################
1.37      matthew  4986: 
1.112     bowersj2 4987: =pod
                   4988: 
                   4989: =back
                   4990: 
                   4991: =cut
                   4992: 
1.37      matthew  4993: ###############################################
1.51      www      4994: 
                   4995: 
                   4996: sub timehash {
1.687     raeburn  4997:     my ($thistime) = @_;
                   4998:     my $timezone = &Apache::lonlocal::gettimezone();
                   4999:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5000:                      ->set_time_zone($timezone);
                   5001:     my $wday = $dt->day_of_week();
                   5002:     if ($wday == 7) { $wday = 0; }
                   5003:     return ( 'second' => $dt->second(),
                   5004:              'minute' => $dt->minute(),
                   5005:              'hour'   => $dt->hour(),
                   5006:              'day'     => $dt->day_of_month(),
                   5007:              'month'   => $dt->month(),
                   5008:              'year'    => $dt->year(),
                   5009:              'weekday' => $wday,
                   5010:              'dayyear' => $dt->day_of_year(),
                   5011:              'dlsav'   => $dt->is_dst() );
1.51      www      5012: }
                   5013: 
1.370     www      5014: sub utc_string {
                   5015:     my ($date)=@_;
1.371     www      5016:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5017: }
                   5018: 
1.51      www      5019: sub maketime {
                   5020:     my %th=@_;
1.687     raeburn  5021:     my ($epoch_time,$timezone,$dt);
                   5022:     $timezone = &Apache::lonlocal::gettimezone();
                   5023:     eval {
                   5024:         $dt = DateTime->new( year   => $th{'year'},
                   5025:                              month  => $th{'month'},
                   5026:                              day    => $th{'day'},
                   5027:                              hour   => $th{'hour'},
                   5028:                              minute => $th{'minute'},
                   5029:                              second => $th{'second'},
                   5030:                              time_zone => $timezone,
                   5031:                          );
                   5032:     };
                   5033:     if (!$@) {
                   5034:         $epoch_time = $dt->epoch;
                   5035:         if ($epoch_time) {
                   5036:             return $epoch_time;
                   5037:         }
                   5038:     }
1.51      www      5039:     return POSIX::mktime(
                   5040:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5041:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5042: }
                   5043: 
                   5044: #########################################
1.51      www      5045: 
                   5046: sub findallcourses {
1.482     raeburn  5047:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5048:     my %roles;
                   5049:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5050:     my %courses;
1.51      www      5051:     my $now=time;
1.482     raeburn  5052:     if (!defined($uname)) {
                   5053:         $uname = $env{'user.name'};
                   5054:     }
                   5055:     if (!defined($udom)) {
                   5056:         $udom = $env{'user.domain'};
                   5057:     }
                   5058:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5059:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5060:         if (!%roles) {
                   5061:             %roles = (
                   5062:                        cc => 1,
1.907     raeburn  5063:                        co => 1,
1.482     raeburn  5064:                        in => 1,
                   5065:                        ep => 1,
                   5066:                        ta => 1,
                   5067:                        cr => 1,
                   5068:                        st => 1,
                   5069:              );
                   5070:         }
                   5071:         foreach my $entry (keys(%roleshash)) {
                   5072:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5073:             if ($trole =~ /^cr/) { 
                   5074:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5075:             } else {
                   5076:                 next if (!exists($roles{$trole}));
                   5077:             }
                   5078:             if ($tend) {
                   5079:                 next if ($tend < $now);
                   5080:             }
                   5081:             if ($tstart) {
                   5082:                 next if ($tstart > $now);
                   5083:             }
1.1058    raeburn  5084:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5085:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5086:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5087:             if ($secpart eq '') {
                   5088:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5089:                 $sec = 'none';
1.1058    raeburn  5090:                 $value .= $cnum.'/';
1.482     raeburn  5091:             } else {
                   5092:                 $cnum = $cnumpart;
                   5093:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5094:                 $value .= $cnum.'/'.$sec;
                   5095:             }
                   5096:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5097:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5098:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5099:                 }
                   5100:             } else {
                   5101:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5102:             }
1.482     raeburn  5103:         }
                   5104:     } else {
                   5105:         foreach my $key (keys(%env)) {
1.483     albertel 5106: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5107:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5108: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5109: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5110: 	        next if (%roles && !exists($roles{$role}));
                   5111: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5112:                 my $active=1;
                   5113:                 if ($starttime) {
                   5114: 		    if ($now<$starttime) { $active=0; }
                   5115:                 }
                   5116:                 if ($endtime) {
                   5117:                     if ($now>$endtime) { $active=0; }
                   5118:                 }
                   5119:                 if ($active) {
1.1058    raeburn  5120:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5121:                     if ($sec eq '') {
                   5122:                         $sec = 'none';
1.1058    raeburn  5123:                     } else {
                   5124:                         $value .= $sec;
                   5125:                     }
                   5126:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5127:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5128:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5129:                         }
                   5130:                     } else {
                   5131:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5132:                     }
1.474     raeburn  5133:                 }
                   5134:             }
1.51      www      5135:         }
                   5136:     }
1.474     raeburn  5137:     return %courses;
1.51      www      5138: }
1.37      matthew  5139: 
1.54      www      5140: ###############################################
1.474     raeburn  5141: 
                   5142: sub blockcheck {
1.1189    raeburn  5143:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  5144: 
1.1189    raeburn  5145:     if (defined($udom) && defined($uname)) {
                   5146:         # If uname and udom are for a course, check for blocks in the course.
                   5147:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5148:             my ($startblock,$endblock,$triggerblock) =
                   5149:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   5150:             return ($startblock,$endblock,$triggerblock);
                   5151:         }
                   5152:     } else {
1.490     raeburn  5153:         $udom = $env{'user.domain'};
                   5154:         $uname = $env{'user.name'};
                   5155:     }
                   5156: 
1.502     raeburn  5157:     my $startblock = 0;
                   5158:     my $endblock = 0;
1.1062    raeburn  5159:     my $triggerblock = '';
1.482     raeburn  5160:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  5161: 
1.490     raeburn  5162:     # If uname is for a user, and activity is course-specific, i.e.,
                   5163:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5164: 
1.490     raeburn  5165:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5166:          $activity eq 'groups' || $activity eq 'printout' ||
                   5167:          $activity eq 'reinit' || $activity eq 'alert') &&
1.1189    raeburn  5168:         ($env{'request.course.id'})) {
1.490     raeburn  5169:         foreach my $key (keys(%live_courses)) {
                   5170:             if ($key ne $env{'request.course.id'}) {
                   5171:                 delete($live_courses{$key});
                   5172:             }
                   5173:         }
                   5174:     }
                   5175: 
                   5176:     my $otheruser = 0;
                   5177:     my %own_courses;
                   5178:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5179:         # Resource belongs to user other than current user.
                   5180:         $otheruser = 1;
                   5181:         # Gather courses for current user
                   5182:         %own_courses = 
                   5183:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5184:     }
                   5185: 
                   5186:     # Gather active course roles - course coordinator, instructor, 
                   5187:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5188: 
                   5189:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5190:         my ($cdom,$cnum);
                   5191:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5192:             $cdom = $env{'course.'.$course.'.domain'};
                   5193:             $cnum = $env{'course.'.$course.'.num'};
                   5194:         } else {
1.490     raeburn  5195:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5196:         }
                   5197:         my $no_ownblock = 0;
                   5198:         my $no_userblock = 0;
1.533     raeburn  5199:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5200:             # Check if current user has 'evb' priv for this
                   5201:             if (defined($own_courses{$course})) {
                   5202:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5203:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5204:                     if ($sec ne 'none') {
                   5205:                         $checkrole .= '/'.$sec;
                   5206:                     }
                   5207:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5208:                         $no_ownblock = 1;
                   5209:                         last;
                   5210:                     }
                   5211:                 }
                   5212:             }
                   5213:             # if they have 'evb' priv and are currently not playing student
                   5214:             next if (($no_ownblock) &&
                   5215:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5216:         }
1.474     raeburn  5217:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5218:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5219:             if ($sec ne 'none') {
1.482     raeburn  5220:                 $checkrole .= '/'.$sec;
1.474     raeburn  5221:             }
1.490     raeburn  5222:             if ($otheruser) {
                   5223:                 # Resource belongs to user other than current user.
                   5224:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5225:                 my (%allroles,%userroles);
                   5226:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5227:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5228:                         my ($trole,$tdom,$tnum,$tsec);
                   5229:                         if ($entry =~ /^cr/) {
                   5230:                             ($trole,$tdom,$tnum,$tsec) = 
                   5231:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5232:                         } else {
                   5233:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5234:                         }
                   5235:                         my ($spec,$area,$trest);
                   5236:                         $area = '/'.$tdom.'/'.$tnum;
                   5237:                         $trest = $tnum;
                   5238:                         if ($tsec ne '') {
                   5239:                             $area .= '/'.$tsec;
                   5240:                             $trest .= '/'.$tsec;
                   5241:                         }
                   5242:                         $spec = $trole.'.'.$area;
                   5243:                         if ($trole =~ /^cr/) {
                   5244:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5245:                                                               $tdom,$spec,$trest,$area);
                   5246:                         } else {
                   5247:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5248:                                                                 $tdom,$spec,$trest,$area);
                   5249:                         }
                   5250:                     }
1.1276    raeburn  5251:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5252:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5253:                         if ($1) {
                   5254:                             $no_userblock = 1;
                   5255:                             last;
                   5256:                         }
1.486     raeburn  5257:                     }
                   5258:                 }
1.490     raeburn  5259:             } else {
                   5260:                 # Resource belongs to current user
                   5261:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5262:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5263:                     $no_ownblock = 1;
                   5264:                     last;
                   5265:                 }
1.474     raeburn  5266:             }
                   5267:         }
                   5268:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5269:         next if (($no_ownblock) &&
1.491     albertel 5270:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5271:         next if ($no_userblock);
1.474     raeburn  5272: 
1.1303    raeburn  5273:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5274:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5275: 
1.1062    raeburn  5276:         my ($start,$end,$trigger) = 
                   5277:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  5278:         if (($start != 0) && 
                   5279:             (($startblock == 0) || ($startblock > $start))) {
                   5280:             $startblock = $start;
1.1062    raeburn  5281:             if ($trigger ne '') {
                   5282:                 $triggerblock = $trigger;
                   5283:             }
1.502     raeburn  5284:         }
                   5285:         if (($end != 0)  &&
                   5286:             (($endblock == 0) || ($endblock < $end))) {
                   5287:             $endblock = $end;
1.1062    raeburn  5288:             if ($trigger ne '') {
                   5289:                 $triggerblock = $trigger;
                   5290:             }
1.502     raeburn  5291:         }
1.490     raeburn  5292:     }
1.1062    raeburn  5293:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5294: }
                   5295: 
                   5296: sub get_blocks {
1.1062    raeburn  5297:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  5298:     my $startblock = 0;
                   5299:     my $endblock = 0;
1.1062    raeburn  5300:     my $triggerblock = '';
1.490     raeburn  5301:     my $course = $cdom.'_'.$cnum;
                   5302:     $setters->{$course} = {};
                   5303:     $setters->{$course}{'staff'} = [];
                   5304:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5305:     $setters->{$course}{'triggers'} = [];
                   5306:     my (@blockers,%triggered);
                   5307:     my $now = time;
                   5308:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5309:     if ($activity eq 'docs') {
                   5310:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   5311:         foreach my $block (@blockers) {
                   5312:             if ($block =~ /^firstaccess____(.+)$/) {
                   5313:                 my $item = $1;
                   5314:                 my $type = 'map';
                   5315:                 my $timersymb = $item;
                   5316:                 if ($item eq 'course') {
                   5317:                     $type = 'course';
                   5318:                 } elsif ($item =~ /___\d+___/) {
                   5319:                     $type = 'resource';
                   5320:                 } else {
                   5321:                     $timersymb = &Apache::lonnet::symbread($item);
                   5322:                 }
                   5323:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5324:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5325:                 $triggered{$block} = {
                   5326:                                        start => $start,
                   5327:                                        end   => $end,
                   5328:                                        type  => $type,
                   5329:                                      };
                   5330:             }
                   5331:         }
                   5332:     } else {
                   5333:         foreach my $block (keys(%commblocks)) {
                   5334:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5335:                 my ($start,$end) = ($1,$2);
                   5336:                 if ($start <= time && $end >= time) {
                   5337:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5338:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5339:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5340:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5341:                                     push(@blockers,$block);
                   5342:                                 }
                   5343:                             }
                   5344:                         }
                   5345:                     }
                   5346:                 }
                   5347:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5348:                 my $item = $1;
                   5349:                 my $timersymb = $item; 
                   5350:                 my $type = 'map';
                   5351:                 if ($item eq 'course') {
                   5352:                     $type = 'course';
                   5353:                 } elsif ($item =~ /___\d+___/) {
                   5354:                     $type = 'resource';
                   5355:                 } else {
                   5356:                     $timersymb = &Apache::lonnet::symbread($item);
                   5357:                 }
                   5358:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5359:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5360:                 if ($start && $end) {
                   5361:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5362:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5363:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5364:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5365:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5366:                                         push(@blockers,$block);
                   5367:                                         $triggered{$block} = {
                   5368:                                                                start => $start,
                   5369:                                                                end   => $end,
                   5370:                                                                type  => $type,
                   5371:                                                              };
                   5372:                                     }
                   5373:                                 }
                   5374:                             }
1.1062    raeburn  5375:                         }
                   5376:                     }
1.490     raeburn  5377:                 }
1.1062    raeburn  5378:             }
                   5379:         }
                   5380:     }
                   5381:     foreach my $blocker (@blockers) {
                   5382:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5383:             &parse_block_record($commblocks{$blocker});
                   5384:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5385:         my ($start,$end,$triggertype);
                   5386:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5387:             ($start,$end) = ($1,$2);
                   5388:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5389:             $start = $triggered{$blocker}{'start'};
                   5390:             $end = $triggered{$blocker}{'end'};
                   5391:             $triggertype = $triggered{$blocker}{'type'};
                   5392:         }
                   5393:         if ($start) {
                   5394:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5395:             if ($triggertype) {
                   5396:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5397:             } else {
                   5398:                 push(@{$$setters{$course}{'triggers'}},0);
                   5399:             }
                   5400:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5401:                 $startblock = $start;
                   5402:                 if ($triggertype) {
                   5403:                     $triggerblock = $blocker;
1.474     raeburn  5404:                 }
                   5405:             }
1.1062    raeburn  5406:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5407:                $endblock = $end;
                   5408:                if ($triggertype) {
                   5409:                    $triggerblock = $blocker;
                   5410:                }
                   5411:             }
1.474     raeburn  5412:         }
                   5413:     }
1.1062    raeburn  5414:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5415: }
                   5416: 
                   5417: sub parse_block_record {
                   5418:     my ($record) = @_;
                   5419:     my ($setuname,$setudom,$title,$blocks);
                   5420:     if (ref($record) eq 'HASH') {
                   5421:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5422:         $title = &unescape($record->{'event'});
                   5423:         $blocks = $record->{'blocks'};
                   5424:     } else {
                   5425:         my @data = split(/:/,$record,3);
                   5426:         if (scalar(@data) eq 2) {
                   5427:             $title = $data[1];
                   5428:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5429:         } else {
                   5430:             ($setuname,$setudom,$title) = @data;
                   5431:         }
                   5432:         $blocks = { 'com' => 'on' };
                   5433:     }
                   5434:     return ($setuname,$setudom,$title,$blocks);
                   5435: }
                   5436: 
1.854     kalberla 5437: sub blocking_status {
1.1189    raeburn  5438:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  5439:     my %setters;
1.890     droeschl 5440: 
1.1061    raeburn  5441: # check for active blocking
1.1062    raeburn  5442:     my ($startblock,$endblock,$triggerblock) = 
1.1189    raeburn  5443:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  5444:     my $blocked = 0;
                   5445:     if ($startblock && $endblock) {
                   5446:         $blocked = 1;
                   5447:     }
1.890     droeschl 5448: 
1.1061    raeburn  5449: # caller just wants to know whether a block is active
                   5450:     if (!wantarray) { return $blocked; }
                   5451: 
                   5452: # build a link to a popup window containing the details
                   5453:     my $querystring  = "?activity=$activity";
                   5454: # $uname and $udom decide whose portfolio the user is trying to look at
1.1232    raeburn  5455:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   5456:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5457:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5458:     } elsif ($activity eq 'docs') {
                   5459:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   5460:     }
1.1061    raeburn  5461: 
                   5462:     my $output .= <<'END_MYBLOCK';
                   5463: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5464:     var options = "width=" + w + ",height=" + h + ",";
                   5465:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5466:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5467:     var newWin = window.open(url, wdwName, options);
                   5468:     newWin.focus();
                   5469: }
1.890     droeschl 5470: END_MYBLOCK
1.854     kalberla 5471: 
1.1061    raeburn  5472:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5473:   
1.1061    raeburn  5474:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5475:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5476:     my $class = 'LC_comblock';
1.1062    raeburn  5477:     if ($activity eq 'docs') {
                   5478:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5479:         $class = '';
1.1063    raeburn  5480:     } elsif ($activity eq 'printout') {
                   5481:         $text = &mt('Printing Blocked');
1.1232    raeburn  5482:     } elsif ($activity eq 'passwd') {
                   5483:         $text = &mt('Password Changing Blocked');
1.1282    raeburn  5484:     } elsif ($activity eq 'alert') {
                   5485:         $text = &mt('Checking Critical Messages Blocked');
                   5486:     } elsif ($activity eq 'reinit') {
                   5487:         $text = &mt('Checking Course Update Blocked');
1.1062    raeburn  5488:     }
1.1061    raeburn  5489:     $output .= <<"END_BLOCK";
1.1217    raeburn  5490: <div class='$class'>
1.869     kalberla 5491:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5492:   title='$text'>
                   5493:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5494:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5495:   title='$text'>$text</a>
1.867     kalberla 5496: </div>
                   5497: 
                   5498: END_BLOCK
1.474     raeburn  5499: 
1.1061    raeburn  5500:     return ($blocked, $output);
1.854     kalberla 5501: }
1.490     raeburn  5502: 
1.60      matthew  5503: ###############################################
                   5504: 
1.682     raeburn  5505: sub check_ip_acc {
1.1201    raeburn  5506:     my ($acc,$clientip)=@_;
1.682     raeburn  5507:     &Apache::lonxml::debug("acc is $acc");
                   5508:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5509:         return 1;
                   5510:     }
1.1219    raeburn  5511:     my $allowed;
1.1252    raeburn  5512:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
1.682     raeburn  5513: 
                   5514:     my $name;
1.1219    raeburn  5515:     my %access = (
                   5516:                      allowfrom => 1,
                   5517:                      denyfrom  => 0,
                   5518:                  );
                   5519:     my @allows;
                   5520:     my @denies;
                   5521:     foreach my $item (split(',',$acc)) {
                   5522:         $item =~ s/^\s*//;
                   5523:         $item =~ s/\s*$//;
                   5524:         my $pattern;
                   5525:         if ($item =~ /^\!(.+)$/) {
                   5526:             push(@denies,$1);
                   5527:         } else {
                   5528:             push(@allows,$item);
                   5529:         }
                   5530:    }
                   5531:    my $numdenies = scalar(@denies);
                   5532:    my $numallows = scalar(@allows);
                   5533:    my $count = 0;
                   5534:    foreach my $pattern (@denies,@allows) {
                   5535:         $count ++; 
                   5536:         my $acctype = 'allowfrom';
                   5537:         if ($count <= $numdenies) {
                   5538:             $acctype = 'denyfrom';
                   5539:         }
1.682     raeburn  5540:         if ($pattern =~ /\*$/) {
                   5541:             #35.8.*
                   5542:             $pattern=~s/\*//;
1.1219    raeburn  5543:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5544:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5545:             #35.8.3.[34-56]
                   5546:             my $low=$2;
                   5547:             my $high=$3;
                   5548:             $pattern=$1;
                   5549:             if ($ip =~ /^\Q$pattern\E/) {
                   5550:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5551:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5552:             }
                   5553:         } elsif ($pattern =~ /^\*/) {
                   5554:             #*.msu.edu
                   5555:             $pattern=~s/\*//;
                   5556:             if (!defined($name)) {
                   5557:                 use Socket;
                   5558:                 my $netaddr=inet_aton($ip);
                   5559:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5560:             }
1.1219    raeburn  5561:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5562:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5563:             #127.0.0.1
1.1219    raeburn  5564:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5565:         } else {
                   5566:             #some.name.com
                   5567:             if (!defined($name)) {
                   5568:                 use Socket;
                   5569:                 my $netaddr=inet_aton($ip);
                   5570:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5571:             }
1.1219    raeburn  5572:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5573:         }
                   5574:         if ($allowed =~ /^(0|1)$/) { last; }
                   5575:     }
                   5576:     if ($allowed eq '') {
                   5577:         if ($numdenies && !$numallows) {
                   5578:             $allowed = 1;
                   5579:         } else {
                   5580:             $allowed = 0;
1.682     raeburn  5581:         }
                   5582:     }
                   5583:     return $allowed;
                   5584: }
                   5585: 
                   5586: ###############################################
                   5587: 
1.60      matthew  5588: =pod
                   5589: 
1.112     bowersj2 5590: =head1 Domain Template Functions
                   5591: 
                   5592: =over 4
                   5593: 
                   5594: =item * &determinedomain()
1.60      matthew  5595: 
                   5596: Inputs: $domain (usually will be undef)
                   5597: 
1.63      www      5598: Returns: Determines which domain should be used for designs
1.60      matthew  5599: 
                   5600: =cut
1.54      www      5601: 
1.60      matthew  5602: ###############################################
1.63      www      5603: sub determinedomain {
                   5604:     my $domain=shift;
1.531     albertel 5605:     if (! $domain) {
1.60      matthew  5606:         # Determine domain if we have not been given one
1.893     raeburn  5607:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5608:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5609:         if ($env{'request.role.domain'}) { 
                   5610:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5611:         }
                   5612:     }
1.63      www      5613:     return $domain;
                   5614: }
                   5615: ###############################################
1.517     raeburn  5616: 
1.518     albertel 5617: sub devalidate_domconfig_cache {
                   5618:     my ($udom)=@_;
                   5619:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5620: }
                   5621: 
                   5622: # ---------------------- Get domain configuration for a domain
                   5623: sub get_domainconf {
                   5624:     my ($udom) = @_;
                   5625:     my $cachetime=1800;
                   5626:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5627:     if (defined($cached)) { return %{$result}; }
                   5628: 
                   5629:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5630: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5631:     my (%designhash,%legacy);
1.518     albertel 5632:     if (keys(%domconfig) > 0) {
                   5633:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5634:             if (keys(%{$domconfig{'login'}})) {
                   5635:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5636:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5637:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5638:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5639:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5640:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5641:                                         if ($key eq 'loginvia') {
                   5642:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5643:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5644:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5645:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5646: 
                   5647:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5648:                                                 } else {
                   5649:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5650:                                                 }
1.948     raeburn  5651:                                             }
1.1208    raeburn  5652:                                         } elsif ($key eq 'headtag') {
                   5653:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5654:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5655:                                             }
1.946     raeburn  5656:                                         }
1.1208    raeburn  5657:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5658:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5659:                                         }
1.946     raeburn  5660:                                     }
                   5661:                                 }
                   5662:                             }
                   5663:                         } else {
                   5664:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5665:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5666:                                     $domconfig{'login'}{$key}{$img};
                   5667:                             }
1.699     raeburn  5668:                         }
                   5669:                     } else {
                   5670:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5671:                     }
1.632     raeburn  5672:                 }
                   5673:             } else {
                   5674:                 $legacy{'login'} = 1;
1.518     albertel 5675:             }
1.632     raeburn  5676:         } else {
                   5677:             $legacy{'login'} = 1;
1.518     albertel 5678:         }
                   5679:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5680:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5681:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5682:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5683:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5684:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5685:                         }
1.518     albertel 5686:                     }
                   5687:                 }
1.632     raeburn  5688:             } else {
                   5689:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5690:             }
1.632     raeburn  5691:         } else {
                   5692:             $legacy{'rolecolors'} = 1;
1.518     albertel 5693:         }
1.948     raeburn  5694:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5695:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5696:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5697:             }
                   5698:         }
1.632     raeburn  5699:         if (keys(%legacy) > 0) {
                   5700:             my %legacyhash = &get_legacy_domconf($udom);
                   5701:             foreach my $item (keys(%legacyhash)) {
                   5702:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5703:                     if ($legacy{'login'}) { 
                   5704:                         $designhash{$item} = $legacyhash{$item};
                   5705:                     }
                   5706:                 } else {
                   5707:                     if ($legacy{'rolecolors'}) {
                   5708:                         $designhash{$item} = $legacyhash{$item};
                   5709:                     }
1.518     albertel 5710:                 }
                   5711:             }
                   5712:         }
1.632     raeburn  5713:     } else {
                   5714:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5715:     }
                   5716:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5717: 				  $cachetime);
                   5718:     return %designhash;
                   5719: }
                   5720: 
1.632     raeburn  5721: sub get_legacy_domconf {
                   5722:     my ($udom) = @_;
                   5723:     my %legacyhash;
                   5724:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5725:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5726:     if (-e $designfile) {
1.1317    raeburn  5727:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5728:             while (my $line = <$fh>) {
                   5729:                 next if ($line =~ /^\#/);
                   5730:                 chomp($line);
                   5731:                 my ($key,$val)=(split(/\=/,$line));
                   5732:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5733:             }
                   5734:             close($fh);
                   5735:         }
                   5736:     }
1.1026    raeburn  5737:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5738:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5739:     }
                   5740:     return %legacyhash;
                   5741: }
                   5742: 
1.63      www      5743: =pod
                   5744: 
1.112     bowersj2 5745: =item * &domainlogo()
1.63      www      5746: 
                   5747: Inputs: $domain (usually will be undef)
                   5748: 
                   5749: Returns: A link to a domain logo, if the domain logo exists.
                   5750: If the domain logo does not exist, a description of the domain.
                   5751: 
                   5752: =cut
1.112     bowersj2 5753: 
1.63      www      5754: ###############################################
                   5755: sub domainlogo {
1.517     raeburn  5756:     my $domain = &determinedomain(shift);
1.518     albertel 5757:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5758:     # See if there is a logo
                   5759:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5760:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5761:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5762: 	    if ($imgsrc =~ m{^/res/}) {
                   5763: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5764: 		&Apache::lonnet::repcopy($local_name);
                   5765: 	    }
                   5766: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5767:         } 
                   5768:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5769:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5770:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5771:     } else {
1.60      matthew  5772:         return '';
1.59      www      5773:     }
                   5774: }
1.63      www      5775: ##############################################
                   5776: 
                   5777: =pod
                   5778: 
1.112     bowersj2 5779: =item * &designparm()
1.63      www      5780: 
                   5781: Inputs: $which parameter; $domain (usually will be undef)
                   5782: 
                   5783: Returns: value of designparamter $which
                   5784: 
                   5785: =cut
1.112     bowersj2 5786: 
1.397     albertel 5787: 
1.400     albertel 5788: ##############################################
1.397     albertel 5789: sub designparm {
                   5790:     my ($which,$domain)=@_;
                   5791:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5792:         return $env{'environment.color.'.$which};
1.96      www      5793:     }
1.63      www      5794:     $domain=&determinedomain($domain);
1.1016    raeburn  5795:     my %domdesign;
                   5796:     unless ($domain eq 'public') {
                   5797:         %domdesign = &get_domainconf($domain);
                   5798:     }
1.520     raeburn  5799:     my $output;
1.517     raeburn  5800:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5801:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5802:     } else {
1.520     raeburn  5803:         $output = $defaultdesign{$which};
                   5804:     }
                   5805:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5806:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5807:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5808:             if ($output =~ m{^/res/}) {
                   5809:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5810:                 &Apache::lonnet::repcopy($local_name);
                   5811:             }
1.520     raeburn  5812:             $output = &lonhttpdurl($output);
                   5813:         }
1.63      www      5814:     }
1.520     raeburn  5815:     return $output;
1.63      www      5816: }
1.59      www      5817: 
1.822     bisitz   5818: ##############################################
                   5819: =pod
                   5820: 
1.832     bisitz   5821: =item * &authorspace()
                   5822: 
1.1028    raeburn  5823: Inputs: $url (usually will be undef).
1.832     bisitz   5824: 
1.1132    raeburn  5825: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5826:          directory being viewed (or for which action is being taken). 
                   5827:          If $url is provided, and begins /priv/<domain>/<uname>
                   5828:          the path will be that portion of the $context argument.
                   5829:          Otherwise the path will be for the author space of the current
                   5830:          user when the current role is author, or for that of the 
                   5831:          co-author/assistant co-author space when the current role 
                   5832:          is co-author or assistant co-author.
1.832     bisitz   5833: 
                   5834: =cut
                   5835: 
                   5836: sub authorspace {
1.1028    raeburn  5837:     my ($url) = @_;
                   5838:     if ($url ne '') {
                   5839:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5840:            return $1;
                   5841:         }
                   5842:     }
1.832     bisitz   5843:     my $caname = '';
1.1024    www      5844:     my $cadom = '';
1.1028    raeburn  5845:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5846:         ($cadom,$caname) =
1.832     bisitz   5847:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5848:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5849:         $caname = $env{'user.name'};
1.1024    www      5850:         $cadom = $env{'user.domain'};
1.832     bisitz   5851:     }
1.1028    raeburn  5852:     if (($caname ne '') && ($cadom ne '')) {
                   5853:         return "/priv/$cadom/$caname/";
                   5854:     }
                   5855:     return;
1.832     bisitz   5856: }
                   5857: 
                   5858: ##############################################
                   5859: =pod
                   5860: 
1.822     bisitz   5861: =item * &head_subbox()
                   5862: 
                   5863: Inputs: $content (contains HTML code with page functions, etc.)
                   5864: 
                   5865: Returns: HTML div with $content
                   5866:          To be included in page header
                   5867: 
                   5868: =cut
                   5869: 
                   5870: sub head_subbox {
                   5871:     my ($content)=@_;
                   5872:     my $output =
1.993     raeburn  5873:         '<div class="LC_head_subbox">'
1.822     bisitz   5874:        .$content
                   5875:        .'</div>'
                   5876: }
                   5877: 
                   5878: ##############################################
                   5879: =pod
                   5880: 
                   5881: =item * &CSTR_pageheader()
                   5882: 
1.1026    raeburn  5883: Input: (optional) filename from which breadcrumb trail is built.
                   5884:        In most cases no input as needed, as $env{'request.filename'}
                   5885:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5886: 
                   5887: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5888:          To be included on Authoring Space pages
1.822     bisitz   5889: 
                   5890: =cut
                   5891: 
                   5892: sub CSTR_pageheader {
1.1026    raeburn  5893:     my ($trailfile) = @_;
                   5894:     if ($trailfile eq '') {
                   5895:         $trailfile = $env{'request.filename'};
                   5896:     }
                   5897: 
                   5898: # this is for resources; directories have customtitle, and crumbs
                   5899: # and select recent are created in lonpubdir.pm
                   5900: 
                   5901:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5902:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5903:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5904:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5905:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5906: 
                   5907:     my $parentpath = '';
                   5908:     my $lastitem = '';
                   5909:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5910:         $parentpath = $1;
                   5911:         $lastitem = $2;
                   5912:     } else {
                   5913:         $lastitem = $thisdisfn;
                   5914:     }
1.921     bisitz   5915: 
1.1246    raeburn  5916:     my ($crsauthor,$title);
                   5917:     if (($env{'request.course.id'}) &&
                   5918:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  5919:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  5920:         $crsauthor = 1;
                   5921:         $title = &mt('Course Authoring Space');
                   5922:     } else {
                   5923:         $title = &mt('Authoring Space');
                   5924:     }
                   5925: 
1.1314    raeburn  5926:     my ($target,$crumbtarget) = (' target="_top"','_top'); #FIXME lonpubdir: target="_parent"
1.1313    raeburn  5927:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  5928:         $target = '';
                   5929:         $crumbtarget = '';
1.1313    raeburn  5930:     }
                   5931: 
1.921     bisitz   5932:     my $output =
1.822     bisitz   5933:          '<div>'
                   5934:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  5935:         .'<b>'.$title.'</b> '
1.1314    raeburn  5936:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   5937:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   5938: 
                   5939:     if ($lastitem) {
                   5940:         $output .=
                   5941:              '<span class="LC_filename">'
                   5942:             .$lastitem
                   5943:             .'</span>';
                   5944:     }
1.1245    raeburn  5945: 
1.1246    raeburn  5946:     if ($crsauthor) {
                   5947:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
                   5948:     } else {
                   5949:         $output .=
                   5950:              '<br />'
1.1314    raeburn  5951:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  5952:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5953:             .'</form>'
                   5954:             .&Apache::lonmenu::constspaceform();
                   5955:     }
                   5956:     $output .= '</div>';
1.921     bisitz   5957: 
                   5958:     return $output;
1.822     bisitz   5959: }
                   5960: 
1.60      matthew  5961: ###############################################
                   5962: ###############################################
                   5963: 
                   5964: =pod
                   5965: 
1.112     bowersj2 5966: =back
                   5967: 
1.549     albertel 5968: =head1 HTML Helpers
1.112     bowersj2 5969: 
                   5970: =over 4
                   5971: 
                   5972: =item * &bodytag()
1.60      matthew  5973: 
                   5974: Returns a uniform header for LON-CAPA web pages.
                   5975: 
                   5976: Inputs: 
                   5977: 
1.112     bowersj2 5978: =over 4
                   5979: 
                   5980: =item * $title, A title to be displayed on the page.
                   5981: 
                   5982: =item * $function, the current role (can be undef).
                   5983: 
                   5984: =item * $addentries, extra parameters for the <body> tag.
                   5985: 
                   5986: =item * $bodyonly, if defined, only return the <body> tag.
                   5987: 
                   5988: =item * $domain, if defined, force a given domain.
                   5989: 
                   5990: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5991:             text interface only)
1.60      matthew  5992: 
1.814     bisitz   5993: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5994:                      navigational links
1.317     albertel 5995: 
1.338     albertel 5996: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5997: 
1.460     albertel 5998: =item * $args, optional argument valid values are
                   5999:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6000:             use_absolute     -> for external resource or syllabus, this will
                   6001:                                 contain https://<hostname> if server uses
                   6002:                                 https (as per hosts.tab), but request is for http
                   6003:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6004: 
1.1096    raeburn  6005: =item * $advtoolsref, optional argument, ref to an array containing
                   6006:             inlineremote items to be added in "Functions" menu below
                   6007:             breadcrumbs.
                   6008: 
1.1316    raeburn  6009: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6010:             course, if LON-CAPA is in LTI Provider context. Value is
                   6011:             the scope of use, i.e., launch was for access to a single, a map
                   6012:             or the entire course.
                   6013: 
                   6014: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6015:             context, this will contain the URL for the landing item in
                   6016:             the course, after launch from an LTI Consumer
                   6017: 
1.1318    raeburn  6018: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6019:             context, this will contain a reference to hash of items
                   6020:             to be included in the page header and/or inline menu.
                   6021: 
1.112     bowersj2 6022: =back
                   6023: 
1.60      matthew  6024: Returns: A uniform header for LON-CAPA web pages.  
                   6025: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6026: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6027: other decorations will be returned.
                   6028: 
                   6029: =cut
                   6030: 
1.54      www      6031: sub bodytag {
1.831     bisitz   6032:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1318    raeburn  6033:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,$ltimenu)=@_;
1.339     albertel 6034: 
1.954     raeburn  6035:     my $public;
                   6036:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6037:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6038:         $public = 1;
                   6039:     }
1.460     albertel 6040:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6041:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6042:     my $hostname = $args->{'hostname'};
1.339     albertel 6043: 
1.183     matthew  6044:     $function = &get_users_function() if (!$function);
1.339     albertel 6045:     my $img =    &designparm($function.'.img',$domain);
                   6046:     my $font =   &designparm($function.'.font',$domain);
                   6047:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6048: 
1.803     bisitz   6049:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6050: 		   'bgcolor' => $pgbg,
1.339     albertel 6051: 		   'text'    => $font,
                   6052:                    'alink'   => &designparm($function.'.alink',$domain),
                   6053: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6054: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6055:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6056: 
1.63      www      6057:  # role and realm
1.1178    raeburn  6058:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6059:     if ($realm) {
                   6060:         $realm = '/'.$realm;
                   6061:     }
1.378     raeburn  6062:     if ($role  eq 'ca') {
1.479     albertel 6063:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6064:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6065:     } 
1.55      www      6066: # realm
1.258     albertel 6067:     if ($env{'request.course.id'}) {
1.378     raeburn  6068:         if ($env{'request.role'} !~ /^cr/) {
                   6069:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6070:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6071:             if ($env{'request.role.desc'}) {
                   6072:                 $role = $env{'request.role.desc'};
                   6073:             } else {
                   6074:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6075:             }
1.1257    raeburn  6076:         } else {
                   6077:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6078:         }
1.898     raeburn  6079:         if ($env{'request.course.sec'}) {
                   6080:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   6081:         }   
1.359     albertel 6082: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  6083:     } else {
                   6084:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6085:     }
1.433     albertel 6086: 
1.359     albertel 6087:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6088: 
1.438     albertel 6089:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6090: 
1.101     www      6091: # construct main body tag
1.359     albertel 6092:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6093: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6094: 
1.1131    raeburn  6095:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6096: 
1.1130    raeburn  6097:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6098:         return $bodytag;
1.1130    raeburn  6099:     }
1.359     albertel 6100: 
1.954     raeburn  6101:     if ($public) {
1.433     albertel 6102: 	undef($role);
                   6103:     }
1.1318    raeburn  6104: 
                   6105:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
                   6106:         if (ref($ltimenu) eq 'HASH') {
                   6107:             unless ($ltimenu->{'role'}) {
                   6108:                 undef($role);
                   6109:             }
                   6110:             unless ($ltimenu->{'coursetitle'}) {
                   6111:                 $realm='&nbsp;';
                   6112:             }
                   6113:         }
                   6114:     }
                   6115: 
1.762     bisitz   6116:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6117:     #
                   6118:     # Extra info if you are the DC
                   6119:     my $dc_info = '';
                   6120:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   6121:                         $env{'course.'.$env{'request.course.id'}.
                   6122:                                  '.domain'}.'/'})) {
                   6123:         my $cid = $env{'request.course.id'};
1.917     raeburn  6124:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6125:         $dc_info =~ s/\s+$//;
1.359     albertel 6126:     }
                   6127: 
1.1237    raeburn  6128:     my $crstype;
                   6129:     if ($env{'request.course.id'}) {
                   6130:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
                   6131:     } elsif ($args->{'crstype'}) {
                   6132:         $crstype = $args->{'crstype'};
                   6133:     }
                   6134:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6135:         undef($role);
                   6136:     } else {
1.1242    raeburn  6137:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6138:     }
1.853     droeschl 6139: 
1.903     droeschl 6140:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6141: 
                   6142:         #    if ($env{'request.state'} eq 'construct') {
                   6143:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6144:         #    }
                   6145: 
1.1130    raeburn  6146:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6147:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6148: 
1.1318    raeburn  6149:         unless ($args->{'no_primary_menu'}) {
                   6150:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu);
1.359     albertel 6151: 
1.1318    raeburn  6152:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6153:                 if ($dc_info) {
                   6154:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6155:                 }
                   6156:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6157:                                <em>$realm</em> $dc_info</div>|;
                   6158:                 return $bodytag;
                   6159:             }
1.894     droeschl 6160: 
1.1318    raeburn  6161:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6162:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6163:             }
1.916     droeschl 6164: 
1.1318    raeburn  6165:             $bodytag .= $right;
1.852     droeschl 6166: 
1.1318    raeburn  6167:             if ($dc_info) {
                   6168:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6169:             }
                   6170:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6171:         }
1.916     droeschl 6172: 
1.1169    raeburn  6173:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6174:         if ($args->{'no_secondary_menu'}) {
                   6175:             return $bodytag;
                   6176:         }
1.1169    raeburn  6177:         #don't show menus for public users
1.954     raeburn  6178:         if (!$public){
1.1318    raeburn  6179:             unless ($args->{'no_inline_menu'}) {
                   6180:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
                   6181:                                                             $args->{'no_primary_menu'});
                   6182:             }
1.903     droeschl 6183:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6184:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6185:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6186:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1316    raeburn  6187:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6188:             } elsif ($forcereg) {
                   6189:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  6190:                                                             $args->{'group'},
1.1274    raeburn  6191:                                                             $args->{'hide_buttons'},
1.1316    raeburn  6192:                                                             $hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6193:             } else {
                   6194:                 $bodytag .= 
                   6195:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6196:                                                         $forcereg,$args->{'group'},
                   6197:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6198:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6199:             }
1.903     droeschl 6200:         }else{
                   6201:             # this is to seperate menu from content when there's no secondary
                   6202:             # menu. Especially needed for public accessible ressources.
                   6203:             $bodytag .= '<hr style="clear:both" />';
                   6204:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6205:         }
1.903     droeschl 6206: 
1.235     raeburn  6207:         return $bodytag;
1.182     matthew  6208: }
                   6209: 
1.917     raeburn  6210: sub dc_courseid_toggle {
                   6211:     my ($dc_info) = @_;
1.980     raeburn  6212:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6213:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6214:            &mt('(More ...)').'</a></span>'.
                   6215:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6216: }
                   6217: 
1.330     albertel 6218: sub make_attr_string {
                   6219:     my ($register,$attr_ref) = @_;
                   6220: 
                   6221:     if ($attr_ref && !ref($attr_ref)) {
                   6222: 	die("addentries Must be a hash ref ".
                   6223: 	    join(':',caller(1))." ".
                   6224: 	    join(':',caller(0))." ");
                   6225:     }
                   6226: 
                   6227:     if ($register) {
1.339     albertel 6228: 	my ($on_load,$on_unload);
                   6229: 	foreach my $key (keys(%{$attr_ref})) {
                   6230: 	    if      (lc($key) eq 'onload') {
                   6231: 		$on_load.=$attr_ref->{$key}.';';
                   6232: 		delete($attr_ref->{$key});
                   6233: 
                   6234: 	    } elsif (lc($key) eq 'onunload') {
                   6235: 		$on_unload.=$attr_ref->{$key}.';';
                   6236: 		delete($attr_ref->{$key});
                   6237: 	    }
                   6238: 	}
1.953     droeschl 6239: 	$attr_ref->{'onload'}  = $on_load;
                   6240: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6241:     }
1.339     albertel 6242: 
1.330     albertel 6243:     my $attr_string;
1.1159    raeburn  6244:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6245: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6246:     }
                   6247:     return $attr_string;
                   6248: }
                   6249: 
                   6250: 
1.182     matthew  6251: ###############################################
1.251     albertel 6252: ###############################################
                   6253: 
                   6254: =pod
                   6255: 
                   6256: =item * &endbodytag()
                   6257: 
                   6258: Returns a uniform footer for LON-CAPA web pages.
                   6259: 
1.635     raeburn  6260: Inputs: 1 - optional reference to an args hash
                   6261: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6262: a 'Continue' link is not displayed if the page contains an
                   6263: internal redirect in the <head></head> section,
                   6264: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6265: 
                   6266: =cut
                   6267: 
                   6268: sub endbodytag {
1.635     raeburn  6269:     my ($args) = @_;
1.1080    raeburn  6270:     my $endbodytag;
                   6271:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6272:         $endbodytag='</body>';
                   6273:     }
1.315     albertel 6274:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6275:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6276: 	    $endbodytag=
                   6277: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6278: 	        &mt('Continue').'</a>'.
                   6279: 	        $endbodytag;
                   6280:         }
1.315     albertel 6281:     }
1.251     albertel 6282:     return $endbodytag;
                   6283: }
                   6284: 
1.352     albertel 6285: =pod
                   6286: 
                   6287: =item * &standard_css()
                   6288: 
                   6289: Returns a style sheet
                   6290: 
                   6291: Inputs: (all optional)
                   6292:             domain         -> force to color decorate a page for a specific
                   6293:                                domain
                   6294:             function       -> force usage of a specific rolish color scheme
                   6295:             bgcolor        -> override the default page bgcolor
                   6296: 
                   6297: =cut
                   6298: 
1.343     albertel 6299: sub standard_css {
1.345     albertel 6300:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6301:     $function  = &get_users_function() if (!$function);
                   6302:     my $img    = &designparm($function.'.img',   $domain);
                   6303:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6304:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6305:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6306: #second colour for later usage
1.345     albertel 6307:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6308:     my $pgbg_or_bgcolor =
                   6309: 	         $bgcolor ||
1.352     albertel 6310: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6311:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6312:     my $alink  = &designparm($function.'.alink', $domain);
                   6313:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6314:     my $link   = &designparm($function.'.link',  $domain);
                   6315: 
1.602     albertel 6316:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6317:     my $mono                 = 'monospace';
1.850     bisitz   6318:     my $data_table_head      = $sidebg;
                   6319:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6320:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6321:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6322:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6323:     my $mail_new             = '#FFBB77';
                   6324:     my $mail_new_hover       = '#DD9955';
                   6325:     my $mail_read            = '#BBBB77';
                   6326:     my $mail_read_hover      = '#999944';
                   6327:     my $mail_replied         = '#AAAA88';
                   6328:     my $mail_replied_hover   = '#888855';
                   6329:     my $mail_other           = '#99BBBB';
                   6330:     my $mail_other_hover     = '#669999';
1.391     albertel 6331:     my $table_header         = '#DDDDDD';
1.489     raeburn  6332:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6333:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6334:     my $button_hover         = '#BF2317';
1.392     albertel 6335: 
1.608     albertel 6336:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6337:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6338:                                              : '0 3px 0 4px';
1.448     albertel 6339: 
1.523     albertel 6340: 
1.343     albertel 6341:     return <<END;
1.947     droeschl 6342: 
                   6343: /* needed for iframe to allow 100% height in FF */
                   6344: body, html { 
                   6345:     margin: 0;
                   6346:     padding: 0 0.5%;
                   6347:     height: 99%; /* to avoid scrollbars */
                   6348: }
                   6349: 
1.795     www      6350: body {
1.911     bisitz   6351:   font-family: $sans;
                   6352:   line-height:130%;
                   6353:   font-size:0.83em;
                   6354:   color:$font;
1.795     www      6355: }
                   6356: 
1.959     onken    6357: a:focus,
                   6358: a:focus img {
1.795     www      6359:   color: red;
                   6360: }
1.698     harmsja  6361: 
1.911     bisitz   6362: form, .inline {
                   6363:   display: inline;
1.795     www      6364: }
1.721     harmsja  6365: 
1.795     www      6366: .LC_right {
1.911     bisitz   6367:   text-align:right;
1.795     www      6368: }
                   6369: 
                   6370: .LC_middle {
1.911     bisitz   6371:   vertical-align:middle;
1.795     www      6372: }
1.721     harmsja  6373: 
1.1130    raeburn  6374: .LC_floatleft {
                   6375:   float: left;
                   6376: }
                   6377: 
                   6378: .LC_floatright {
                   6379:   float: right;
                   6380: }
                   6381: 
1.911     bisitz   6382: .LC_400Box {
                   6383:   width:400px;
                   6384: }
1.721     harmsja  6385: 
1.947     droeschl 6386: .LC_iframecontainer {
                   6387:     width: 98%;
                   6388:     margin: 0;
                   6389:     position: fixed;
                   6390:     top: 8.5em;
                   6391:     bottom: 0;
                   6392: }
                   6393: 
                   6394: .LC_iframecontainer iframe{
                   6395:     border: none;
                   6396:     width: 100%;
                   6397:     height: 100%;
                   6398: }
                   6399: 
1.778     bisitz   6400: .LC_filename {
                   6401:   font-family: $mono;
                   6402:   white-space:pre;
1.921     bisitz   6403:   font-size: 120%;
1.778     bisitz   6404: }
                   6405: 
                   6406: .LC_fileicon {
                   6407:   border: none;
                   6408:   height: 1.3em;
                   6409:   vertical-align: text-bottom;
                   6410:   margin-right: 0.3em;
                   6411:   text-decoration:none;
                   6412: }
                   6413: 
1.1008    www      6414: .LC_setting {
                   6415:   text-decoration:underline;
                   6416: }
                   6417: 
1.350     albertel 6418: .LC_error {
                   6419:   color: red;
                   6420: }
1.795     www      6421: 
1.1097    bisitz   6422: .LC_warning {
                   6423:   color: darkorange;
                   6424: }
                   6425: 
1.457     albertel 6426: .LC_diff_removed {
1.733     bisitz   6427:   color: red;
1.394     albertel 6428: }
1.532     albertel 6429: 
                   6430: .LC_info,
1.457     albertel 6431: .LC_success,
                   6432: .LC_diff_added {
1.350     albertel 6433:   color: green;
                   6434: }
1.795     www      6435: 
1.802     bisitz   6436: div.LC_confirm_box {
                   6437:   background-color: #FAFAFA;
                   6438:   border: 1px solid $lg_border_color;
                   6439:   margin-right: 0;
                   6440:   padding: 5px;
                   6441: }
                   6442: 
                   6443: div.LC_confirm_box .LC_error img,
                   6444: div.LC_confirm_box .LC_success img {
                   6445:   vertical-align: middle;
                   6446: }
                   6447: 
1.1242    raeburn  6448: .LC_maxwidth {
                   6449:   max-width: 100%;
                   6450:   height: auto;
                   6451: }
                   6452: 
1.1243    raeburn  6453: .LC_textsize_mobile {
                   6454:   \@media only screen and (max-device-width: 480px) {
                   6455:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6456:   }
                   6457: }
                   6458: 
1.440     albertel 6459: .LC_icon {
1.771     droeschl 6460:   border: none;
1.790     droeschl 6461:   vertical-align: middle;
1.771     droeschl 6462: }
                   6463: 
1.543     albertel 6464: .LC_docs_spacer {
                   6465:   width: 25px;
                   6466:   height: 1px;
1.771     droeschl 6467:   border: none;
1.543     albertel 6468: }
1.346     albertel 6469: 
1.532     albertel 6470: .LC_internal_info {
1.735     bisitz   6471:   color: #999999;
1.532     albertel 6472: }
                   6473: 
1.794     www      6474: .LC_discussion {
1.1050    www      6475:   background: $data_table_dark;
1.911     bisitz   6476:   border: 1px solid black;
                   6477:   margin: 2px;
1.794     www      6478: }
                   6479: 
                   6480: .LC_disc_action_left {
1.1050    www      6481:   background: $sidebg;
1.911     bisitz   6482:   text-align: left;
1.1050    www      6483:   padding: 4px;
                   6484:   margin: 2px;
1.794     www      6485: }
                   6486: 
                   6487: .LC_disc_action_right {
1.1050    www      6488:   background: $sidebg;
1.911     bisitz   6489:   text-align: right;
1.1050    www      6490:   padding: 4px;
                   6491:   margin: 2px;
1.794     www      6492: }
                   6493: 
                   6494: .LC_disc_new_item {
1.911     bisitz   6495:   background: white;
                   6496:   border: 2px solid red;
1.1050    www      6497:   margin: 4px;
                   6498:   padding: 4px;
1.794     www      6499: }
                   6500: 
                   6501: .LC_disc_old_item {
1.911     bisitz   6502:   background: white;
1.1050    www      6503:   margin: 4px;
                   6504:   padding: 4px;
1.794     www      6505: }
                   6506: 
1.458     albertel 6507: table.LC_pastsubmission {
                   6508:   border: 1px solid black;
                   6509:   margin: 2px;
                   6510: }
                   6511: 
1.924     bisitz   6512: table#LC_menubuttons {
1.345     albertel 6513:   width: 100%;
                   6514:   background: $pgbg;
1.392     albertel 6515:   border: 2px;
1.402     albertel 6516:   border-collapse: separate;
1.803     bisitz   6517:   padding: 0;
1.345     albertel 6518: }
1.392     albertel 6519: 
1.801     tempelho 6520: table#LC_title_bar a {
                   6521:   color: $fontmenu;
                   6522: }
1.836     bisitz   6523: 
1.807     droeschl 6524: table#LC_title_bar {
1.819     tempelho 6525:   clear: both;
1.836     bisitz   6526:   display: none;
1.807     droeschl 6527: }
                   6528: 
1.795     www      6529: table#LC_title_bar,
1.933     droeschl 6530: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6531: table#LC_title_bar.LC_with_remote {
1.359     albertel 6532:   width: 100%;
1.392     albertel 6533:   border-color: $pgbg;
                   6534:   border-style: solid;
                   6535:   border-width: $border;
1.379     albertel 6536:   background: $pgbg;
1.801     tempelho 6537:   color: $fontmenu;
1.392     albertel 6538:   border-collapse: collapse;
1.803     bisitz   6539:   padding: 0;
1.819     tempelho 6540:   margin: 0;
1.359     albertel 6541: }
1.795     www      6542: 
1.933     droeschl 6543: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6544:     margin: 0;
                   6545:     padding: 0;
1.933     droeschl 6546:     position: relative;
                   6547:     list-style: none;
1.913     droeschl 6548: }
1.933     droeschl 6549: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6550:     display: inline;
                   6551: }
1.933     droeschl 6552: 
                   6553: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6554:     padding: 0;
1.933     droeschl 6555:     margin: 0;
                   6556:     float: left;
1.913     droeschl 6557: }
1.933     droeschl 6558: .LC_breadcrumb_tools_tools {
                   6559:     padding: 0;
                   6560:     margin: 0;
1.913     droeschl 6561:     float: right;
                   6562: }
                   6563: 
1.1240    raeburn  6564: .LC_placement_prog {
                   6565:     padding-right: 20px;
                   6566:     font-weight: bold;
                   6567:     font-size: 90%;
                   6568: }
                   6569: 
1.359     albertel 6570: table#LC_title_bar td {
                   6571:   background: $tabbg;
                   6572: }
1.795     www      6573: 
1.911     bisitz   6574: table#LC_menubuttons img {
1.803     bisitz   6575:   border: none;
1.346     albertel 6576: }
1.795     www      6577: 
1.842     droeschl 6578: .LC_breadcrumbs_component {
1.911     bisitz   6579:   float: right;
                   6580:   margin: 0 1em;
1.357     albertel 6581: }
1.842     droeschl 6582: .LC_breadcrumbs_component img {
1.911     bisitz   6583:   vertical-align: middle;
1.777     tempelho 6584: }
1.795     www      6585: 
1.1243    raeburn  6586: .LC_breadcrumbs_hoverable {
                   6587:   background: $sidebg;
                   6588: }
                   6589: 
1.383     albertel 6590: td.LC_table_cell_checkbox {
                   6591:   text-align: center;
                   6592: }
1.795     www      6593: 
                   6594: .LC_fontsize_small {
1.911     bisitz   6595:   font-size: 70%;
1.705     tempelho 6596: }
                   6597: 
1.844     bisitz   6598: #LC_breadcrumbs {
1.911     bisitz   6599:   clear:both;
                   6600:   background: $sidebg;
                   6601:   border-bottom: 1px solid $lg_border_color;
                   6602:   line-height: 2.5em;
1.933     droeschl 6603:   overflow: hidden;
1.911     bisitz   6604:   margin: 0;
                   6605:   padding: 0;
1.995     raeburn  6606:   text-align: left;
1.819     tempelho 6607: }
1.862     bisitz   6608: 
1.1098    bisitz   6609: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6610:   clear:both;
                   6611:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6612:   border: 1px solid $sidebg;
1.1098    bisitz   6613:   margin: 0 0 10px 0;
1.966     bisitz   6614:   padding: 3px;
1.995     raeburn  6615:   text-align: left;
1.822     bisitz   6616: }
                   6617: 
1.795     www      6618: .LC_fontsize_medium {
1.911     bisitz   6619:   font-size: 85%;
1.705     tempelho 6620: }
                   6621: 
1.795     www      6622: .LC_fontsize_large {
1.911     bisitz   6623:   font-size: 120%;
1.705     tempelho 6624: }
                   6625: 
1.346     albertel 6626: .LC_menubuttons_inline_text {
                   6627:   color: $font;
1.698     harmsja  6628:   font-size: 90%;
1.701     harmsja  6629:   padding-left:3px;
1.346     albertel 6630: }
                   6631: 
1.934     droeschl 6632: .LC_menubuttons_inline_text img{
                   6633:   vertical-align: middle;
                   6634: }
                   6635: 
1.1051    www      6636: li.LC_menubuttons_inline_text img {
1.951     onken    6637:   cursor:pointer;
1.1002    droeschl 6638:   text-decoration: none;
1.951     onken    6639: }
                   6640: 
1.526     www      6641: .LC_menubuttons_link {
                   6642:   text-decoration: none;
                   6643: }
1.795     www      6644: 
1.522     albertel 6645: .LC_menubuttons_category {
1.521     www      6646:   color: $font;
1.526     www      6647:   background: $pgbg;
1.521     www      6648:   font-size: larger;
                   6649:   font-weight: bold;
                   6650: }
                   6651: 
1.346     albertel 6652: td.LC_menubuttons_text {
1.911     bisitz   6653:   color: $font;
1.346     albertel 6654: }
1.706     harmsja  6655: 
1.346     albertel 6656: .LC_current_location {
                   6657:   background: $tabbg;
                   6658: }
1.795     www      6659: 
1.1286    raeburn  6660: td.LC_zero_height {
                   6661:   line-height: 0; 
                   6662:   cellpadding: 0;
                   6663: }
                   6664: 
1.938     bisitz   6665: table.LC_data_table {
1.347     albertel 6666:   border: 1px solid #000000;
1.402     albertel 6667:   border-collapse: separate;
1.426     albertel 6668:   border-spacing: 1px;
1.610     albertel 6669:   background: $pgbg;
1.347     albertel 6670: }
1.795     www      6671: 
1.422     albertel 6672: .LC_data_table_dense {
                   6673:   font-size: small;
                   6674: }
1.795     www      6675: 
1.507     raeburn  6676: table.LC_nested_outer {
                   6677:   border: 1px solid #000000;
1.589     raeburn  6678:   border-collapse: collapse;
1.803     bisitz   6679:   border-spacing: 0;
1.507     raeburn  6680:   width: 100%;
                   6681: }
1.795     www      6682: 
1.879     raeburn  6683: table.LC_innerpickbox,
1.507     raeburn  6684: table.LC_nested {
1.803     bisitz   6685:   border: none;
1.589     raeburn  6686:   border-collapse: collapse;
1.803     bisitz   6687:   border-spacing: 0;
1.507     raeburn  6688:   width: 100%;
                   6689: }
1.795     www      6690: 
1.911     bisitz   6691: table.LC_data_table tr th,
                   6692: table.LC_calendar tr th,
1.879     raeburn  6693: table.LC_prior_tries tr th,
                   6694: table.LC_innerpickbox tr th {
1.349     albertel 6695:   font-weight: bold;
                   6696:   background-color: $data_table_head;
1.801     tempelho 6697:   color:$fontmenu;
1.701     harmsja  6698:   font-size:90%;
1.347     albertel 6699: }
1.795     www      6700: 
1.879     raeburn  6701: table.LC_innerpickbox tr th,
                   6702: table.LC_innerpickbox tr td {
                   6703:   vertical-align: top;
                   6704: }
                   6705: 
1.711     raeburn  6706: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6707:   background-color: #CCCCCC;
1.711     raeburn  6708:   font-weight: bold;
                   6709:   text-align: left;
                   6710: }
1.795     www      6711: 
1.912     bisitz   6712: table.LC_data_table tr.LC_odd_row > td {
                   6713:   background-color: $data_table_light;
                   6714:   padding: 2px;
                   6715:   vertical-align: top;
                   6716: }
                   6717: 
1.809     bisitz   6718: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6719:   background-color: $data_table_light;
1.912     bisitz   6720:   vertical-align: top;
                   6721: }
                   6722: 
                   6723: table.LC_data_table tr.LC_even_row > td {
                   6724:   background-color: $data_table_dark;
1.425     albertel 6725:   padding: 2px;
1.900     bisitz   6726:   vertical-align: top;
1.347     albertel 6727: }
1.795     www      6728: 
1.809     bisitz   6729: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6730:   background-color: $data_table_dark;
1.900     bisitz   6731:   vertical-align: top;
1.347     albertel 6732: }
1.795     www      6733: 
1.425     albertel 6734: table.LC_data_table tr.LC_data_table_highlight td {
                   6735:   background-color: $data_table_darker;
                   6736: }
1.795     www      6737: 
1.639     raeburn  6738: table.LC_data_table tr td.LC_leftcol_header {
                   6739:   background-color: $data_table_head;
                   6740:   font-weight: bold;
                   6741: }
1.795     www      6742: 
1.451     albertel 6743: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6744: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6745:   font-weight: bold;
                   6746:   font-style: italic;
                   6747:   text-align: center;
                   6748:   padding: 8px;
1.347     albertel 6749: }
1.795     www      6750: 
1.1114    raeburn  6751: table.LC_data_table tr.LC_empty_row td,
                   6752: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6753:   background-color: $sidebg;
                   6754: }
                   6755: 
                   6756: table.LC_nested tr.LC_empty_row td {
                   6757:   background-color: #FFFFFF;
                   6758: }
                   6759: 
1.890     droeschl 6760: table.LC_caption {
                   6761: }
                   6762: 
1.507     raeburn  6763: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6764:   padding: 4ex
                   6765: }
1.795     www      6766: 
1.507     raeburn  6767: table.LC_nested_outer tr th {
                   6768:   font-weight: bold;
1.801     tempelho 6769:   color:$fontmenu;
1.507     raeburn  6770:   background-color: $data_table_head;
1.701     harmsja  6771:   font-size: small;
1.507     raeburn  6772:   border-bottom: 1px solid #000000;
                   6773: }
1.795     www      6774: 
1.507     raeburn  6775: table.LC_nested_outer tr td.LC_subheader {
                   6776:   background-color: $data_table_head;
                   6777:   font-weight: bold;
                   6778:   font-size: small;
                   6779:   border-bottom: 1px solid #000000;
                   6780:   text-align: right;
1.451     albertel 6781: }
1.795     www      6782: 
1.507     raeburn  6783: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6784:   background-color: #CCCCCC;
1.451     albertel 6785:   font-weight: bold;
                   6786:   font-size: small;
1.507     raeburn  6787:   text-align: center;
                   6788: }
1.795     www      6789: 
1.589     raeburn  6790: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6791: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6792:   text-align: left;
1.451     albertel 6793: }
1.795     www      6794: 
1.507     raeburn  6795: table.LC_nested td {
1.735     bisitz   6796:   background-color: #FFFFFF;
1.451     albertel 6797:   font-size: small;
1.507     raeburn  6798: }
1.795     www      6799: 
1.507     raeburn  6800: table.LC_nested_outer tr th.LC_right_item,
                   6801: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6802: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6803: table.LC_nested tr td.LC_right_item {
1.451     albertel 6804:   text-align: right;
                   6805: }
                   6806: 
1.507     raeburn  6807: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6808:   background-color: #EEEEEE;
1.451     albertel 6809: }
                   6810: 
1.473     raeburn  6811: table.LC_createuser {
                   6812: }
                   6813: 
                   6814: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6815:   font-size: small;
1.473     raeburn  6816: }
                   6817: 
                   6818: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6819:   background-color: #CCCCCC;
1.473     raeburn  6820:   font-weight: bold;
                   6821:   text-align: center;
                   6822: }
                   6823: 
1.349     albertel 6824: table.LC_calendar {
                   6825:   border: 1px solid #000000;
                   6826:   border-collapse: collapse;
1.917     raeburn  6827:   width: 98%;
1.349     albertel 6828: }
1.795     www      6829: 
1.349     albertel 6830: table.LC_calendar_pickdate {
                   6831:   font-size: xx-small;
                   6832: }
1.795     www      6833: 
1.349     albertel 6834: table.LC_calendar tr td {
                   6835:   border: 1px solid #000000;
                   6836:   vertical-align: top;
1.917     raeburn  6837:   width: 14%;
1.349     albertel 6838: }
1.795     www      6839: 
1.349     albertel 6840: table.LC_calendar tr td.LC_calendar_day_empty {
                   6841:   background-color: $data_table_dark;
                   6842: }
1.795     www      6843: 
1.779     bisitz   6844: table.LC_calendar tr td.LC_calendar_day_current {
                   6845:   background-color: $data_table_highlight;
1.777     tempelho 6846: }
1.795     www      6847: 
1.938     bisitz   6848: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6849:   background-color: $mail_new;
                   6850: }
1.795     www      6851: 
1.938     bisitz   6852: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6853:   background-color: $mail_new_hover;
                   6854: }
1.795     www      6855: 
1.938     bisitz   6856: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6857:   background-color: $mail_read;
                   6858: }
1.795     www      6859: 
1.938     bisitz   6860: /*
                   6861: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6862:   background-color: $mail_read_hover;
                   6863: }
1.938     bisitz   6864: */
1.795     www      6865: 
1.938     bisitz   6866: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6867:   background-color: $mail_replied;
                   6868: }
1.795     www      6869: 
1.938     bisitz   6870: /*
                   6871: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6872:   background-color: $mail_replied_hover;
                   6873: }
1.938     bisitz   6874: */
1.795     www      6875: 
1.938     bisitz   6876: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6877:   background-color: $mail_other;
                   6878: }
1.795     www      6879: 
1.938     bisitz   6880: /*
                   6881: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6882:   background-color: $mail_other_hover;
                   6883: }
1.938     bisitz   6884: */
1.494     raeburn  6885: 
1.777     tempelho 6886: table.LC_data_table tr > td.LC_browser_file,
                   6887: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6888:   background: #AAEE77;
1.389     albertel 6889: }
1.795     www      6890: 
1.777     tempelho 6891: table.LC_data_table tr > td.LC_browser_file_locked,
                   6892: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6893:   background: #FFAA99;
1.387     albertel 6894: }
1.795     www      6895: 
1.777     tempelho 6896: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6897:   background: #888888;
1.779     bisitz   6898: }
1.795     www      6899: 
1.777     tempelho 6900: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6901: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6902:   background: #F8F866;
1.777     tempelho 6903: }
1.795     www      6904: 
1.696     bisitz   6905: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6906:   background: #E0E8FF;
1.387     albertel 6907: }
1.696     bisitz   6908: 
1.707     bisitz   6909: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6910:   /* background: #77FF77; */
1.707     bisitz   6911: }
1.795     www      6912: 
1.707     bisitz   6913: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6914:   border-right: 8px solid #FFFF77;
1.707     bisitz   6915: }
1.795     www      6916: 
1.707     bisitz   6917: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6918:   border-right: 8px solid #FFAA77;
1.707     bisitz   6919: }
1.795     www      6920: 
1.707     bisitz   6921: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6922:   border-right: 8px solid #FF7777;
1.707     bisitz   6923: }
1.795     www      6924: 
1.707     bisitz   6925: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6926:   border-right: 8px solid #AAFF77;
1.707     bisitz   6927: }
1.795     www      6928: 
1.707     bisitz   6929: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6930:   border-right: 8px solid #11CC55;
1.707     bisitz   6931: }
                   6932: 
1.388     albertel 6933: span.LC_current_location {
1.701     harmsja  6934:   font-size:larger;
1.388     albertel 6935:   background: $pgbg;
                   6936: }
1.387     albertel 6937: 
1.1029    www      6938: span.LC_current_nav_location {
                   6939:   font-weight:bold;
                   6940:   background: $sidebg;
                   6941: }
                   6942: 
1.395     albertel 6943: span.LC_parm_menu_item {
                   6944:   font-size: larger;
                   6945: }
1.795     www      6946: 
1.395     albertel 6947: span.LC_parm_scope_all {
                   6948:   color: red;
                   6949: }
1.795     www      6950: 
1.395     albertel 6951: span.LC_parm_scope_folder {
                   6952:   color: green;
                   6953: }
1.795     www      6954: 
1.395     albertel 6955: span.LC_parm_scope_resource {
                   6956:   color: orange;
                   6957: }
1.795     www      6958: 
1.395     albertel 6959: span.LC_parm_part {
                   6960:   color: blue;
                   6961: }
1.795     www      6962: 
1.911     bisitz   6963: span.LC_parm_folder,
                   6964: span.LC_parm_symb {
1.395     albertel 6965:   font-size: x-small;
                   6966:   font-family: $mono;
                   6967:   color: #AAAAAA;
                   6968: }
                   6969: 
1.977     bisitz   6970: ul.LC_parm_parmlist li {
                   6971:   display: inline-block;
                   6972:   padding: 0.3em 0.8em;
                   6973:   vertical-align: top;
                   6974:   width: 150px;
                   6975:   border-top:1px solid $lg_border_color;
                   6976: }
                   6977: 
1.795     www      6978: td.LC_parm_overview_level_menu,
                   6979: td.LC_parm_overview_map_menu,
                   6980: td.LC_parm_overview_parm_selectors,
                   6981: td.LC_parm_overview_restrictions  {
1.396     albertel 6982:   border: 1px solid black;
                   6983:   border-collapse: collapse;
                   6984: }
1.795     www      6985: 
1.1285    raeburn  6986: span.LC_parm_recursive,
                   6987: td.LC_parm_recursive {
                   6988:   font-weight: bold;
                   6989:   font-size: smaller;
                   6990: }
                   6991: 
1.396     albertel 6992: table.LC_parm_overview_restrictions td {
                   6993:   border-width: 1px 4px 1px 4px;
                   6994:   border-style: solid;
                   6995:   border-color: $pgbg;
                   6996:   text-align: center;
                   6997: }
1.795     www      6998: 
1.396     albertel 6999: table.LC_parm_overview_restrictions th {
                   7000:   background: $tabbg;
                   7001:   border-width: 1px 4px 1px 4px;
                   7002:   border-style: solid;
                   7003:   border-color: $pgbg;
                   7004: }
1.795     www      7005: 
1.398     albertel 7006: table#LC_helpmenu {
1.803     bisitz   7007:   border: none;
1.398     albertel 7008:   height: 55px;
1.803     bisitz   7009:   border-spacing: 0;
1.398     albertel 7010: }
                   7011: 
                   7012: table#LC_helpmenu fieldset legend {
                   7013:   font-size: larger;
                   7014: }
1.795     www      7015: 
1.397     albertel 7016: table#LC_helpmenu_links {
                   7017:   width: 100%;
                   7018:   border: 1px solid black;
                   7019:   background: $pgbg;
1.803     bisitz   7020:   padding: 0;
1.397     albertel 7021:   border-spacing: 1px;
                   7022: }
1.795     www      7023: 
1.397     albertel 7024: table#LC_helpmenu_links tr td {
                   7025:   padding: 1px;
                   7026:   background: $tabbg;
1.399     albertel 7027:   text-align: center;
                   7028:   font-weight: bold;
1.397     albertel 7029: }
1.396     albertel 7030: 
1.795     www      7031: table#LC_helpmenu_links a:link,
                   7032: table#LC_helpmenu_links a:visited,
1.397     albertel 7033: table#LC_helpmenu_links a:active {
                   7034:   text-decoration: none;
                   7035:   color: $font;
                   7036: }
1.795     www      7037: 
1.397     albertel 7038: table#LC_helpmenu_links a:hover {
                   7039:   text-decoration: underline;
                   7040:   color: $vlink;
                   7041: }
1.396     albertel 7042: 
1.417     albertel 7043: .LC_chrt_popup_exists {
                   7044:   border: 1px solid #339933;
                   7045:   margin: -1px;
                   7046: }
1.795     www      7047: 
1.417     albertel 7048: .LC_chrt_popup_up {
                   7049:   border: 1px solid yellow;
                   7050:   margin: -1px;
                   7051: }
1.795     www      7052: 
1.417     albertel 7053: .LC_chrt_popup {
                   7054:   border: 1px solid #8888FF;
                   7055:   background: #CCCCFF;
                   7056: }
1.795     www      7057: 
1.421     albertel 7058: table.LC_pick_box {
                   7059:   border-collapse: separate;
                   7060:   background: white;
                   7061:   border: 1px solid black;
                   7062:   border-spacing: 1px;
                   7063: }
1.795     www      7064: 
1.421     albertel 7065: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7066:   background: $sidebg;
1.421     albertel 7067:   font-weight: bold;
1.900     bisitz   7068:   text-align: left;
1.740     bisitz   7069:   vertical-align: top;
1.421     albertel 7070:   width: 184px;
                   7071:   padding: 8px;
                   7072: }
1.795     www      7073: 
1.579     raeburn  7074: table.LC_pick_box td.LC_pick_box_value {
                   7075:   text-align: left;
                   7076:   padding: 8px;
                   7077: }
1.795     www      7078: 
1.579     raeburn  7079: table.LC_pick_box td.LC_pick_box_select {
                   7080:   text-align: left;
                   7081:   padding: 8px;
                   7082: }
1.795     www      7083: 
1.424     albertel 7084: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7085:   padding: 0;
1.421     albertel 7086:   height: 1px;
                   7087:   background: black;
                   7088: }
1.795     www      7089: 
1.421     albertel 7090: table.LC_pick_box td.LC_pick_box_submit {
                   7091:   text-align: right;
                   7092: }
1.795     www      7093: 
1.579     raeburn  7094: table.LC_pick_box td.LC_evenrow_value {
                   7095:   text-align: left;
                   7096:   padding: 8px;
                   7097:   background-color: $data_table_light;
                   7098: }
1.795     www      7099: 
1.579     raeburn  7100: table.LC_pick_box td.LC_oddrow_value {
                   7101:   text-align: left;
                   7102:   padding: 8px;
                   7103:   background-color: $data_table_light;
                   7104: }
1.795     www      7105: 
1.579     raeburn  7106: span.LC_helpform_receipt_cat {
                   7107:   font-weight: bold;
                   7108: }
1.795     www      7109: 
1.424     albertel 7110: table.LC_group_priv_box {
                   7111:   background: white;
                   7112:   border: 1px solid black;
                   7113:   border-spacing: 1px;
                   7114: }
1.795     www      7115: 
1.424     albertel 7116: table.LC_group_priv_box td.LC_pick_box_title {
                   7117:   background: $tabbg;
                   7118:   font-weight: bold;
                   7119:   text-align: right;
                   7120:   width: 184px;
                   7121: }
1.795     www      7122: 
1.424     albertel 7123: table.LC_group_priv_box td.LC_groups_fixed {
                   7124:   background: $data_table_light;
                   7125:   text-align: center;
                   7126: }
1.795     www      7127: 
1.424     albertel 7128: table.LC_group_priv_box td.LC_groups_optional {
                   7129:   background: $data_table_dark;
                   7130:   text-align: center;
                   7131: }
1.795     www      7132: 
1.424     albertel 7133: table.LC_group_priv_box td.LC_groups_functionality {
                   7134:   background: $data_table_darker;
                   7135:   text-align: center;
                   7136:   font-weight: bold;
                   7137: }
1.795     www      7138: 
1.424     albertel 7139: table.LC_group_priv td {
                   7140:   text-align: left;
1.803     bisitz   7141:   padding: 0;
1.424     albertel 7142: }
                   7143: 
                   7144: .LC_navbuttons {
                   7145:   margin: 2ex 0ex 2ex 0ex;
                   7146: }
1.795     www      7147: 
1.423     albertel 7148: .LC_topic_bar {
                   7149:   font-weight: bold;
                   7150:   background: $tabbg;
1.918     wenzelju 7151:   margin: 1em 0em 1em 2em;
1.805     bisitz   7152:   padding: 3px;
1.918     wenzelju 7153:   font-size: 1.2em;
1.423     albertel 7154: }
1.795     www      7155: 
1.423     albertel 7156: .LC_topic_bar span {
1.918     wenzelju 7157:   left: 0.5em;
                   7158:   position: absolute;
1.423     albertel 7159:   vertical-align: middle;
1.918     wenzelju 7160:   font-size: 1.2em;
1.423     albertel 7161: }
1.795     www      7162: 
1.423     albertel 7163: table.LC_course_group_status {
                   7164:   margin: 20px;
                   7165: }
1.795     www      7166: 
1.423     albertel 7167: table.LC_status_selector td {
                   7168:   vertical-align: top;
                   7169:   text-align: center;
1.424     albertel 7170:   padding: 4px;
                   7171: }
1.795     www      7172: 
1.599     albertel 7173: div.LC_feedback_link {
1.616     albertel 7174:   clear: both;
1.829     kalberla 7175:   background: $sidebg;
1.779     bisitz   7176:   width: 100%;
1.829     kalberla 7177:   padding-bottom: 10px;
                   7178:   border: 1px $tabbg solid;
1.833     kalberla 7179:   height: 22px;
                   7180:   line-height: 22px;
                   7181:   padding-top: 5px;
                   7182: }
                   7183: 
                   7184: div.LC_feedback_link img {
                   7185:   height: 22px;
1.867     kalberla 7186:   vertical-align:middle;
1.829     kalberla 7187: }
                   7188: 
1.911     bisitz   7189: div.LC_feedback_link a {
1.829     kalberla 7190:   text-decoration: none;
1.489     raeburn  7191: }
1.795     www      7192: 
1.867     kalberla 7193: div.LC_comblock {
1.911     bisitz   7194:   display:inline;
1.867     kalberla 7195:   color:$font;
                   7196:   font-size:90%;
                   7197: }
                   7198: 
                   7199: div.LC_feedback_link div.LC_comblock {
                   7200:   padding-left:5px;
                   7201: }
                   7202: 
                   7203: div.LC_feedback_link div.LC_comblock a {
                   7204:   color:$font;
                   7205: }
                   7206: 
1.489     raeburn  7207: span.LC_feedback_link {
1.858     bisitz   7208:   /* background: $feedback_link_bg; */
1.599     albertel 7209:   font-size: larger;
                   7210: }
1.795     www      7211: 
1.599     albertel 7212: span.LC_message_link {
1.858     bisitz   7213:   /* background: $feedback_link_bg; */
1.599     albertel 7214:   font-size: larger;
                   7215:   position: absolute;
                   7216:   right: 1em;
1.489     raeburn  7217: }
1.421     albertel 7218: 
1.515     albertel 7219: table.LC_prior_tries {
1.524     albertel 7220:   border: 1px solid #000000;
                   7221:   border-collapse: separate;
                   7222:   border-spacing: 1px;
1.515     albertel 7223: }
1.523     albertel 7224: 
1.515     albertel 7225: table.LC_prior_tries td {
1.524     albertel 7226:   padding: 2px;
1.515     albertel 7227: }
1.523     albertel 7228: 
                   7229: .LC_answer_correct {
1.795     www      7230:   background: lightgreen;
                   7231:   color: darkgreen;
                   7232:   padding: 6px;
1.523     albertel 7233: }
1.795     www      7234: 
1.523     albertel 7235: .LC_answer_charged_try {
1.797     www      7236:   background: #FFAAAA;
1.795     www      7237:   color: darkred;
                   7238:   padding: 6px;
1.523     albertel 7239: }
1.795     www      7240: 
1.779     bisitz   7241: .LC_answer_not_charged_try,
1.523     albertel 7242: .LC_answer_no_grade,
                   7243: .LC_answer_late {
1.795     www      7244:   background: lightyellow;
1.523     albertel 7245:   color: black;
1.795     www      7246:   padding: 6px;
1.523     albertel 7247: }
1.795     www      7248: 
1.523     albertel 7249: .LC_answer_previous {
1.795     www      7250:   background: lightblue;
                   7251:   color: darkblue;
                   7252:   padding: 6px;
1.523     albertel 7253: }
1.795     www      7254: 
1.779     bisitz   7255: .LC_answer_no_message {
1.777     tempelho 7256:   background: #FFFFFF;
                   7257:   color: black;
1.795     www      7258:   padding: 6px;
1.779     bisitz   7259: }
1.795     www      7260: 
1.1334    raeburn  7261: .LC_answer_unknown,
                   7262: .LC_answer_warning {
1.779     bisitz   7263:   background: orange;
                   7264:   color: black;
1.795     www      7265:   padding: 6px;
1.777     tempelho 7266: }
1.795     www      7267: 
1.529     albertel 7268: span.LC_prior_numerical,
                   7269: span.LC_prior_string,
                   7270: span.LC_prior_custom,
                   7271: span.LC_prior_reaction,
                   7272: span.LC_prior_math {
1.925     bisitz   7273:   font-family: $mono;
1.523     albertel 7274:   white-space: pre;
                   7275: }
                   7276: 
1.525     albertel 7277: span.LC_prior_string {
1.925     bisitz   7278:   font-family: $mono;
1.525     albertel 7279:   white-space: pre;
                   7280: }
                   7281: 
1.523     albertel 7282: table.LC_prior_option {
                   7283:   width: 100%;
                   7284:   border-collapse: collapse;
                   7285: }
1.795     www      7286: 
1.911     bisitz   7287: table.LC_prior_rank,
1.795     www      7288: table.LC_prior_match {
1.528     albertel 7289:   border-collapse: collapse;
                   7290: }
1.795     www      7291: 
1.528     albertel 7292: table.LC_prior_option tr td,
                   7293: table.LC_prior_rank tr td,
                   7294: table.LC_prior_match tr td {
1.524     albertel 7295:   border: 1px solid #000000;
1.515     albertel 7296: }
                   7297: 
1.855     bisitz   7298: .LC_nobreak {
1.544     albertel 7299:   white-space: nowrap;
1.519     raeburn  7300: }
                   7301: 
1.576     raeburn  7302: span.LC_cusr_emph {
                   7303:   font-style: italic;
                   7304: }
                   7305: 
1.633     raeburn  7306: span.LC_cusr_subheading {
                   7307:   font-weight: normal;
                   7308:   font-size: 85%;
                   7309: }
                   7310: 
1.861     bisitz   7311: div.LC_docs_entry_move {
1.859     bisitz   7312:   border: 1px solid #BBBBBB;
1.545     albertel 7313:   background: #DDDDDD;
1.861     bisitz   7314:   width: 22px;
1.859     bisitz   7315:   padding: 1px;
                   7316:   margin: 0;
1.545     albertel 7317: }
                   7318: 
1.861     bisitz   7319: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7320: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7321:   font-size: x-small;
                   7322: }
1.795     www      7323: 
1.861     bisitz   7324: .LC_docs_entry_parameter {
                   7325:   white-space: nowrap;
                   7326: }
                   7327: 
1.544     albertel 7328: .LC_docs_copy {
1.545     albertel 7329:   color: #000099;
1.544     albertel 7330: }
1.795     www      7331: 
1.544     albertel 7332: .LC_docs_cut {
1.545     albertel 7333:   color: #550044;
1.544     albertel 7334: }
1.795     www      7335: 
1.544     albertel 7336: .LC_docs_rename {
1.545     albertel 7337:   color: #009900;
1.544     albertel 7338: }
1.795     www      7339: 
1.544     albertel 7340: .LC_docs_remove {
1.545     albertel 7341:   color: #990000;
                   7342: }
                   7343: 
1.1284    raeburn  7344: .LC_docs_alias {
                   7345:   color: #440055;  
                   7346: }
                   7347: 
1.1286    raeburn  7348: .LC_domprefs_email,
1.1284    raeburn  7349: .LC_docs_alias_name,
1.547     albertel 7350: .LC_docs_reinit_warn,
                   7351: .LC_docs_ext_edit {
                   7352:   font-size: x-small;
                   7353: }
                   7354: 
1.545     albertel 7355: table.LC_docs_adddocs td,
                   7356: table.LC_docs_adddocs th {
                   7357:   border: 1px solid #BBBBBB;
                   7358:   padding: 4px;
                   7359:   background: #DDDDDD;
1.543     albertel 7360: }
                   7361: 
1.584     albertel 7362: table.LC_sty_begin {
                   7363:   background: #BBFFBB;
                   7364: }
1.795     www      7365: 
1.584     albertel 7366: table.LC_sty_end {
                   7367:   background: #FFBBBB;
                   7368: }
                   7369: 
1.589     raeburn  7370: table.LC_double_column {
1.803     bisitz   7371:   border-width: 0;
1.589     raeburn  7372:   border-collapse: collapse;
                   7373:   width: 100%;
                   7374:   padding: 2px;
                   7375: }
                   7376: 
                   7377: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7378:   top: 2px;
1.589     raeburn  7379:   left: 2px;
                   7380:   width: 47%;
                   7381:   vertical-align: top;
                   7382: }
                   7383: 
                   7384: table.LC_double_column tr td.LC_right_col {
                   7385:   top: 2px;
1.779     bisitz   7386:   right: 2px;
1.589     raeburn  7387:   width: 47%;
                   7388:   vertical-align: top;
                   7389: }
                   7390: 
1.591     raeburn  7391: div.LC_left_float {
                   7392:   float: left;
                   7393:   padding-right: 5%;
1.597     albertel 7394:   padding-bottom: 4px;
1.591     raeburn  7395: }
                   7396: 
                   7397: div.LC_clear_float_header {
1.597     albertel 7398:   padding-bottom: 2px;
1.591     raeburn  7399: }
                   7400: 
                   7401: div.LC_clear_float_footer {
1.597     albertel 7402:   padding-top: 10px;
1.591     raeburn  7403:   clear: both;
                   7404: }
                   7405: 
1.597     albertel 7406: div.LC_grade_show_user {
1.941     bisitz   7407: /*  border-left: 5px solid $sidebg; */
                   7408:   border-top: 5px solid #000000;
                   7409:   margin: 50px 0 0 0;
1.936     bisitz   7410:   padding: 15px 0 5px 10px;
1.597     albertel 7411: }
1.795     www      7412: 
1.936     bisitz   7413: div.LC_grade_show_user_odd_row {
1.941     bisitz   7414: /*  border-left: 5px solid #000000; */
                   7415: }
                   7416: 
                   7417: div.LC_grade_show_user div.LC_Box {
                   7418:   margin-right: 50px;
1.597     albertel 7419: }
                   7420: 
                   7421: div.LC_grade_submissions,
                   7422: div.LC_grade_message_center,
1.936     bisitz   7423: div.LC_grade_info_links {
1.597     albertel 7424:   margin: 5px;
                   7425:   width: 99%;
                   7426:   background: #FFFFFF;
                   7427: }
1.795     www      7428: 
1.597     albertel 7429: div.LC_grade_submissions_header,
1.936     bisitz   7430: div.LC_grade_message_center_header {
1.705     tempelho 7431:   font-weight: bold;
                   7432:   font-size: large;
1.597     albertel 7433: }
1.795     www      7434: 
1.597     albertel 7435: div.LC_grade_submissions_body,
1.936     bisitz   7436: div.LC_grade_message_center_body {
1.597     albertel 7437:   border: 1px solid black;
                   7438:   width: 99%;
                   7439:   background: #FFFFFF;
                   7440: }
1.795     www      7441: 
1.613     albertel 7442: table.LC_scantron_action {
                   7443:   width: 100%;
                   7444: }
1.795     www      7445: 
1.613     albertel 7446: table.LC_scantron_action tr th {
1.698     harmsja  7447:   font-weight:bold;
                   7448:   font-style:normal;
1.613     albertel 7449: }
1.795     www      7450: 
1.779     bisitz   7451: .LC_edit_problem_header,
1.614     albertel 7452: div.LC_edit_problem_footer {
1.705     tempelho 7453:   font-weight: normal;
                   7454:   font-size:  medium;
1.602     albertel 7455:   margin: 2px;
1.1060    bisitz   7456:   background-color: $sidebg;
1.600     albertel 7457: }
1.795     www      7458: 
1.600     albertel 7459: div.LC_edit_problem_header,
1.602     albertel 7460: div.LC_edit_problem_header div,
1.614     albertel 7461: div.LC_edit_problem_footer,
                   7462: div.LC_edit_problem_footer div,
1.602     albertel 7463: div.LC_edit_problem_editxml_header,
                   7464: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7465:   z-index: 100;
1.600     albertel 7466: }
1.795     www      7467: 
1.600     albertel 7468: div.LC_edit_problem_header_title {
1.705     tempelho 7469:   font-weight: bold;
                   7470:   font-size: larger;
1.602     albertel 7471:   background: $tabbg;
                   7472:   padding: 3px;
1.1060    bisitz   7473:   margin: 0 0 5px 0;
1.602     albertel 7474: }
1.795     www      7475: 
1.602     albertel 7476: table.LC_edit_problem_header_title {
                   7477:   width: 100%;
1.600     albertel 7478:   background: $tabbg;
1.602     albertel 7479: }
                   7480: 
1.1205    golterma 7481: div.LC_edit_actionbar {
                   7482:     background-color: $sidebg;
1.1218    droeschl 7483:     margin: 0;
                   7484:     padding: 0;
                   7485:     line-height: 200%;
1.602     albertel 7486: }
1.795     www      7487: 
1.1218    droeschl 7488: div.LC_edit_actionbar div{
                   7489:     padding: 0;
                   7490:     margin: 0;
                   7491:     display: inline-block;
1.600     albertel 7492: }
1.795     www      7493: 
1.1124    bisitz   7494: .LC_edit_opt {
                   7495:   padding-left: 1em;
                   7496:   white-space: nowrap;
                   7497: }
                   7498: 
1.1152    golterma 7499: .LC_edit_problem_latexhelper{
                   7500:     text-align: right;
                   7501: }
                   7502: 
                   7503: #LC_edit_problem_colorful div{
                   7504:     margin-left: 40px;
                   7505: }
                   7506: 
1.1205    golterma 7507: #LC_edit_problem_codemirror div{
                   7508:     margin-left: 0px;
                   7509: }
                   7510: 
1.911     bisitz   7511: img.stift {
1.803     bisitz   7512:   border-width: 0;
                   7513:   vertical-align: middle;
1.677     riegler  7514: }
1.680     riegler  7515: 
1.923     bisitz   7516: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7517:   vertical-align: top;
1.777     tempelho 7518: }
1.795     www      7519: 
1.716     raeburn  7520: div.LC_createcourse {
1.911     bisitz   7521:   margin: 10px 10px 10px 10px;
1.716     raeburn  7522: }
                   7523: 
1.917     raeburn  7524: .LC_dccid {
1.1130    raeburn  7525:   float: right;
1.917     raeburn  7526:   margin: 0.2em 0 0 0;
                   7527:   padding: 0;
                   7528:   font-size: 90%;
                   7529:   display:none;
                   7530: }
                   7531: 
1.897     wenzelju 7532: ol.LC_primary_menu a:hover,
1.721     harmsja  7533: ol#LC_MenuBreadcrumbs a:hover,
                   7534: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7535: ul#LC_secondary_menu a:hover,
1.721     harmsja  7536: .LC_FormSectionClearButton input:hover
1.795     www      7537: ul.LC_TabContent   li:hover a {
1.952     onken    7538:   color:$button_hover;
1.911     bisitz   7539:   text-decoration:none;
1.693     droeschl 7540: }
                   7541: 
1.779     bisitz   7542: h1 {
1.911     bisitz   7543:   padding: 0;
                   7544:   line-height:130%;
1.693     droeschl 7545: }
1.698     harmsja  7546: 
1.911     bisitz   7547: h2,
                   7548: h3,
                   7549: h4,
                   7550: h5,
                   7551: h6 {
                   7552:   margin: 5px 0 5px 0;
                   7553:   padding: 0;
                   7554:   line-height:130%;
1.693     droeschl 7555: }
1.795     www      7556: 
                   7557: .LC_hcell {
1.911     bisitz   7558:   padding:3px 15px 3px 15px;
                   7559:   margin: 0;
                   7560:   background-color:$tabbg;
                   7561:   color:$fontmenu;
                   7562:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7563: }
1.795     www      7564: 
1.840     bisitz   7565: .LC_Box > .LC_hcell {
1.911     bisitz   7566:   margin: 0 -10px 10px -10px;
1.835     bisitz   7567: }
                   7568: 
1.721     harmsja  7569: .LC_noBorder {
1.911     bisitz   7570:   border: 0;
1.698     harmsja  7571: }
1.693     droeschl 7572: 
1.721     harmsja  7573: .LC_FormSectionClearButton input {
1.911     bisitz   7574:   background-color:transparent;
                   7575:   border: none;
                   7576:   cursor:pointer;
                   7577:   text-decoration:underline;
1.693     droeschl 7578: }
1.763     bisitz   7579: 
                   7580: .LC_help_open_topic {
1.911     bisitz   7581:   color: #FFFFFF;
                   7582:   background-color: #EEEEFF;
                   7583:   margin: 1px;
                   7584:   padding: 4px;
                   7585:   border: 1px solid #000033;
                   7586:   white-space: nowrap;
                   7587:   /* vertical-align: middle; */
1.759     neumanie 7588: }
1.693     droeschl 7589: 
1.911     bisitz   7590: dl,
                   7591: ul,
                   7592: div,
                   7593: fieldset {
                   7594:   margin: 10px 10px 10px 0;
                   7595:   /* overflow: hidden; */
1.693     droeschl 7596: }
1.795     www      7597: 
1.1211    raeburn  7598: article.geogebraweb div {
                   7599:     margin: 0;
                   7600: }
                   7601: 
1.838     bisitz   7602: fieldset > legend {
1.911     bisitz   7603:   font-weight: bold;
                   7604:   padding: 0 5px 0 5px;
1.838     bisitz   7605: }
                   7606: 
1.813     bisitz   7607: #LC_nav_bar {
1.911     bisitz   7608:   float: left;
1.995     raeburn  7609:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7610:   margin: 0 0 2px 0;
1.807     droeschl 7611: }
                   7612: 
1.916     droeschl 7613: #LC_realm {
                   7614:   margin: 0.2em 0 0 0;
                   7615:   padding: 0;
                   7616:   font-weight: bold;
                   7617:   text-align: center;
1.995     raeburn  7618:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7619: }
                   7620: 
1.911     bisitz   7621: #LC_nav_bar em {
                   7622:   font-weight: bold;
                   7623:   font-style: normal;
1.807     droeschl 7624: }
                   7625: 
1.897     wenzelju 7626: ol.LC_primary_menu {
1.934     droeschl 7627:   margin: 0;
1.1076    raeburn  7628:   padding: 0;
1.807     droeschl 7629: }
                   7630: 
1.852     droeschl 7631: ol#LC_PathBreadcrumbs {
1.911     bisitz   7632:   margin: 0;
1.693     droeschl 7633: }
                   7634: 
1.897     wenzelju 7635: ol.LC_primary_menu li {
1.1076    raeburn  7636:   color: RGB(80, 80, 80);
                   7637:   vertical-align: middle;
                   7638:   text-align: left;
                   7639:   list-style: none;
1.1205    golterma 7640:   position: relative;
1.1076    raeburn  7641:   float: left;
1.1205    golterma 7642:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7643:   line-height: 1.5em;
1.1076    raeburn  7644: }
                   7645: 
1.1205    golterma 7646: ol.LC_primary_menu li a,
                   7647: ol.LC_primary_menu li p {
1.1076    raeburn  7648:   display: block;
                   7649:   margin: 0;
                   7650:   padding: 0 5px 0 10px;
                   7651:   text-decoration: none;
                   7652: }
                   7653: 
1.1205    golterma 7654: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7655:   display: inline-block;
                   7656:   width: 95%;
                   7657:   text-align: left;
                   7658: }
                   7659: 
                   7660: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7661:   display: inline-block;	
                   7662:   width: 5%;
                   7663:   float: right;
                   7664:   text-align: right;
                   7665:   font-size: 70%;
                   7666: }
                   7667: 
                   7668: ol.LC_primary_menu ul {
1.1076    raeburn  7669:   display: none;
1.1205    golterma 7670:   width: 15em;
1.1076    raeburn  7671:   background-color: $data_table_light;
1.1205    golterma 7672:   position: absolute;
                   7673:   top: 100%;
1.1076    raeburn  7674: }
                   7675: 
1.1205    golterma 7676: ol.LC_primary_menu ul ul {
                   7677:   left: 100%;
                   7678:   top: 0;
                   7679: }
                   7680: 
                   7681: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7682:   display: block;
                   7683:   position: absolute;
                   7684:   margin: 0;
                   7685:   padding: 0;
1.1078    raeburn  7686:   z-index: 2;
1.1076    raeburn  7687: }
                   7688: 
                   7689: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7690: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7691:   font-size: 90%;
1.911     bisitz   7692:   vertical-align: top;
1.1076    raeburn  7693:   float: none;
1.1079    raeburn  7694:   border-left: 1px solid black;
                   7695:   border-right: 1px solid black;
1.1205    golterma 7696: /* A dark bottom border to visualize different menu options; 
                   7697: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7698:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7699: }
                   7700: 
1.1205    golterma 7701: ol.LC_primary_menu li li p:hover {
                   7702:   color:$button_hover;
                   7703:   text-decoration:none;
                   7704:   background-color:$data_table_dark;
1.1076    raeburn  7705: }
                   7706: 
                   7707: ol.LC_primary_menu li li a:hover {
                   7708:    color:$button_hover;
                   7709:    background-color:$data_table_dark;
1.693     droeschl 7710: }
                   7711: 
1.1205    golterma 7712: /* Font-size equal to the size of the predecessors*/
                   7713: ol.LC_primary_menu li:hover li li {
                   7714:   font-size: 100%;
                   7715: }
                   7716: 
1.897     wenzelju 7717: ol.LC_primary_menu li img {
1.911     bisitz   7718:   vertical-align: bottom;
1.934     droeschl 7719:   height: 1.1em;
1.1077    raeburn  7720:   margin: 0.2em 0 0 0;
1.693     droeschl 7721: }
                   7722: 
1.897     wenzelju 7723: ol.LC_primary_menu a {
1.911     bisitz   7724:   color: RGB(80, 80, 80);
                   7725:   text-decoration: none;
1.693     droeschl 7726: }
1.795     www      7727: 
1.949     droeschl 7728: ol.LC_primary_menu a.LC_new_message {
                   7729:   font-weight:bold;
                   7730:   color: darkred;
                   7731: }
                   7732: 
1.975     raeburn  7733: ol.LC_docs_parameters {
                   7734:   margin-left: 0;
                   7735:   padding: 0;
                   7736:   list-style: none;
                   7737: }
                   7738: 
                   7739: ol.LC_docs_parameters li {
                   7740:   margin: 0;
                   7741:   padding-right: 20px;
                   7742:   display: inline;
                   7743: }
                   7744: 
1.976     raeburn  7745: ol.LC_docs_parameters li:before {
                   7746:   content: "\\002022 \\0020";
                   7747: }
                   7748: 
                   7749: li.LC_docs_parameters_title {
                   7750:   font-weight: bold;
                   7751: }
                   7752: 
                   7753: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7754:   content: "";
                   7755: }
                   7756: 
1.897     wenzelju 7757: ul#LC_secondary_menu {
1.1107    raeburn  7758:   clear: right;
1.911     bisitz   7759:   color: $fontmenu;
                   7760:   background: $tabbg;
                   7761:   list-style: none;
                   7762:   padding: 0;
                   7763:   margin: 0;
                   7764:   width: 100%;
1.995     raeburn  7765:   text-align: left;
1.1107    raeburn  7766:   float: left;
1.808     droeschl 7767: }
                   7768: 
1.897     wenzelju 7769: ul#LC_secondary_menu li {
1.911     bisitz   7770:   font-weight: bold;
                   7771:   line-height: 1.8em;
1.1107    raeburn  7772:   border-right: 1px solid black;
                   7773:   float: left;
                   7774: }
                   7775: 
                   7776: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7777:   background-color: $data_table_light;
                   7778: }
                   7779: 
                   7780: ul#LC_secondary_menu li a {
1.911     bisitz   7781:   padding: 0 0.8em;
1.1107    raeburn  7782: }
                   7783: 
                   7784: ul#LC_secondary_menu li ul {
                   7785:   display: none;
                   7786: }
                   7787: 
                   7788: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7789:   display: block;
                   7790:   position: absolute;
                   7791:   margin: 0;
                   7792:   padding: 0;
                   7793:   list-style:none;
                   7794:   float: none;
                   7795:   background-color: $data_table_light;
                   7796:   z-index: 2;
                   7797:   margin-left: -1px;
                   7798: }
                   7799: 
                   7800: ul#LC_secondary_menu li ul li {
                   7801:   font-size: 90%;
                   7802:   vertical-align: top;
                   7803:   border-left: 1px solid black;
1.911     bisitz   7804:   border-right: 1px solid black;
1.1119    raeburn  7805:   background-color: $data_table_light;
1.1107    raeburn  7806:   list-style:none;
                   7807:   float: none;
                   7808: }
                   7809: 
                   7810: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7811:   background-color: $data_table_dark;
1.807     droeschl 7812: }
                   7813: 
1.847     tempelho 7814: ul.LC_TabContent {
1.911     bisitz   7815:   display:block;
                   7816:   background: $sidebg;
                   7817:   border-bottom: solid 1px $lg_border_color;
                   7818:   list-style:none;
1.1020    raeburn  7819:   margin: -1px -10px 0 -10px;
1.911     bisitz   7820:   padding: 0;
1.693     droeschl 7821: }
                   7822: 
1.795     www      7823: ul.LC_TabContent li,
                   7824: ul.LC_TabContentBigger li {
1.911     bisitz   7825:   float:left;
1.741     harmsja  7826: }
1.795     www      7827: 
1.897     wenzelju 7828: ul#LC_secondary_menu li a {
1.911     bisitz   7829:   color: $fontmenu;
                   7830:   text-decoration: none;
1.693     droeschl 7831: }
1.795     www      7832: 
1.721     harmsja  7833: ul.LC_TabContent {
1.952     onken    7834:   min-height:20px;
1.721     harmsja  7835: }
1.795     www      7836: 
                   7837: ul.LC_TabContent li {
1.911     bisitz   7838:   vertical-align:middle;
1.959     onken    7839:   padding: 0 16px 0 10px;
1.911     bisitz   7840:   background-color:$tabbg;
                   7841:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7842:   border-left: solid 1px $font;
1.721     harmsja  7843: }
1.795     www      7844: 
1.847     tempelho 7845: ul.LC_TabContent .right {
1.911     bisitz   7846:   float:right;
1.847     tempelho 7847: }
                   7848: 
1.911     bisitz   7849: ul.LC_TabContent li a,
                   7850: ul.LC_TabContent li {
                   7851:   color:rgb(47,47,47);
                   7852:   text-decoration:none;
                   7853:   font-size:95%;
                   7854:   font-weight:bold;
1.952     onken    7855:   min-height:20px;
                   7856: }
                   7857: 
1.959     onken    7858: ul.LC_TabContent li a:hover,
                   7859: ul.LC_TabContent li a:focus {
1.952     onken    7860:   color: $button_hover;
1.959     onken    7861:   background:none;
                   7862:   outline:none;
1.952     onken    7863: }
                   7864: 
                   7865: ul.LC_TabContent li:hover {
                   7866:   color: $button_hover;
                   7867:   cursor:pointer;
1.721     harmsja  7868: }
1.795     www      7869: 
1.911     bisitz   7870: ul.LC_TabContent li.active {
1.952     onken    7871:   color: $font;
1.911     bisitz   7872:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7873:   border-bottom:solid 1px #FFFFFF;
                   7874:   cursor: default;
1.744     ehlerst  7875: }
1.795     www      7876: 
1.959     onken    7877: ul.LC_TabContent li.active a {
                   7878:   color:$font;
                   7879:   background:#FFFFFF;
                   7880:   outline: none;
                   7881: }
1.1047    raeburn  7882: 
                   7883: ul.LC_TabContent li.goback {
                   7884:   float: left;
                   7885:   border-left: none;
                   7886: }
                   7887: 
1.870     tempelho 7888: #maincoursedoc {
1.911     bisitz   7889:   clear:both;
1.870     tempelho 7890: }
                   7891: 
                   7892: ul.LC_TabContentBigger {
1.911     bisitz   7893:   display:block;
                   7894:   list-style:none;
                   7895:   padding: 0;
1.870     tempelho 7896: }
                   7897: 
1.795     www      7898: ul.LC_TabContentBigger li {
1.911     bisitz   7899:   vertical-align:bottom;
                   7900:   height: 30px;
                   7901:   font-size:110%;
                   7902:   font-weight:bold;
                   7903:   color: #737373;
1.841     tempelho 7904: }
                   7905: 
1.957     onken    7906: ul.LC_TabContentBigger li.active {
                   7907:   position: relative;
                   7908:   top: 1px;
                   7909: }
                   7910: 
1.870     tempelho 7911: ul.LC_TabContentBigger li a {
1.911     bisitz   7912:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7913:   height: 30px;
                   7914:   line-height: 30px;
                   7915:   text-align: center;
                   7916:   display: block;
                   7917:   text-decoration: none;
1.958     onken    7918:   outline: none;  
1.741     harmsja  7919: }
1.795     www      7920: 
1.870     tempelho 7921: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7922:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7923:   color:$font;
1.744     ehlerst  7924: }
1.795     www      7925: 
1.870     tempelho 7926: ul.LC_TabContentBigger li b {
1.911     bisitz   7927:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7928:   display: block;
                   7929:   float: left;
                   7930:   padding: 0 30px;
1.957     onken    7931:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7932: }
                   7933: 
1.956     onken    7934: ul.LC_TabContentBigger li:hover b {
                   7935:   color:$button_hover;
                   7936: }
                   7937: 
1.870     tempelho 7938: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7939:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7940:   color:$font;
1.957     onken    7941:   border: 0;
1.741     harmsja  7942: }
1.693     droeschl 7943: 
1.870     tempelho 7944: 
1.862     bisitz   7945: ul.LC_CourseBreadcrumbs {
                   7946:   background: $sidebg;
1.1020    raeburn  7947:   height: 2em;
1.862     bisitz   7948:   padding-left: 10px;
1.1020    raeburn  7949:   margin: 0;
1.862     bisitz   7950:   list-style-position: inside;
                   7951: }
                   7952: 
1.911     bisitz   7953: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7954: ol#LC_PathBreadcrumbs {
1.911     bisitz   7955:   padding-left: 10px;
                   7956:   margin: 0;
1.933     droeschl 7957:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7958: }
                   7959: 
1.911     bisitz   7960: ol#LC_MenuBreadcrumbs li,
                   7961: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7962: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7963:   display: inline;
1.933     droeschl 7964:   white-space: normal;  
1.693     droeschl 7965: }
                   7966: 
1.823     bisitz   7967: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7968: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7969:   text-decoration: none;
                   7970:   font-size:90%;
1.693     droeschl 7971: }
1.795     www      7972: 
1.969     droeschl 7973: ol#LC_MenuBreadcrumbs h1 {
                   7974:   display: inline;
                   7975:   font-size: 90%;
                   7976:   line-height: 2.5em;
                   7977:   margin: 0;
                   7978:   padding: 0;
                   7979: }
                   7980: 
1.795     www      7981: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7982:   text-decoration:none;
                   7983:   font-size:100%;
                   7984:   font-weight:bold;
1.693     droeschl 7985: }
1.795     www      7986: 
1.840     bisitz   7987: .LC_Box {
1.911     bisitz   7988:   border: solid 1px $lg_border_color;
                   7989:   padding: 0 10px 10px 10px;
1.746     neumanie 7990: }
1.795     www      7991: 
1.1020    raeburn  7992: .LC_DocsBox {
                   7993:   border: solid 1px $lg_border_color;
                   7994:   padding: 0 0 10px 10px;
                   7995: }
                   7996: 
1.795     www      7997: .LC_AboutMe_Image {
1.911     bisitz   7998:   float:left;
                   7999:   margin-right:10px;
1.747     neumanie 8000: }
1.795     www      8001: 
                   8002: .LC_Clear_AboutMe_Image {
1.911     bisitz   8003:   clear:left;
1.747     neumanie 8004: }
1.795     www      8005: 
1.721     harmsja  8006: dl.LC_ListStyleClean dt {
1.911     bisitz   8007:   padding-right: 5px;
                   8008:   display: table-header-group;
1.693     droeschl 8009: }
                   8010: 
1.721     harmsja  8011: dl.LC_ListStyleClean dd {
1.911     bisitz   8012:   display: table-row;
1.693     droeschl 8013: }
                   8014: 
1.721     harmsja  8015: .LC_ListStyleClean,
                   8016: .LC_ListStyleSimple,
                   8017: .LC_ListStyleNormal,
1.795     www      8018: .LC_ListStyleSpecial {
1.911     bisitz   8019:   /* display:block; */
                   8020:   list-style-position: inside;
                   8021:   list-style-type: none;
                   8022:   overflow: hidden;
                   8023:   padding: 0;
1.693     droeschl 8024: }
                   8025: 
1.721     harmsja  8026: .LC_ListStyleSimple li,
                   8027: .LC_ListStyleSimple dd,
                   8028: .LC_ListStyleNormal li,
                   8029: .LC_ListStyleNormal dd,
                   8030: .LC_ListStyleSpecial li,
1.795     www      8031: .LC_ListStyleSpecial dd {
1.911     bisitz   8032:   margin: 0;
                   8033:   padding: 5px 5px 5px 10px;
                   8034:   clear: both;
1.693     droeschl 8035: }
                   8036: 
1.721     harmsja  8037: .LC_ListStyleClean li,
                   8038: .LC_ListStyleClean dd {
1.911     bisitz   8039:   padding-top: 0;
                   8040:   padding-bottom: 0;
1.693     droeschl 8041: }
                   8042: 
1.721     harmsja  8043: .LC_ListStyleSimple dd,
1.795     www      8044: .LC_ListStyleSimple li {
1.911     bisitz   8045:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8046: }
                   8047: 
1.721     harmsja  8048: .LC_ListStyleSpecial li,
                   8049: .LC_ListStyleSpecial dd {
1.911     bisitz   8050:   list-style-type: none;
                   8051:   background-color: RGB(220, 220, 220);
                   8052:   margin-bottom: 4px;
1.693     droeschl 8053: }
                   8054: 
1.721     harmsja  8055: table.LC_SimpleTable {
1.911     bisitz   8056:   margin:5px;
                   8057:   border:solid 1px $lg_border_color;
1.795     www      8058: }
1.693     droeschl 8059: 
1.721     harmsja  8060: table.LC_SimpleTable tr {
1.911     bisitz   8061:   padding: 0;
                   8062:   border:solid 1px $lg_border_color;
1.693     droeschl 8063: }
1.795     www      8064: 
                   8065: table.LC_SimpleTable thead {
1.911     bisitz   8066:   background:rgb(220,220,220);
1.693     droeschl 8067: }
                   8068: 
1.721     harmsja  8069: div.LC_columnSection {
1.911     bisitz   8070:   display: block;
                   8071:   clear: both;
                   8072:   overflow: hidden;
                   8073:   margin: 0;
1.693     droeschl 8074: }
                   8075: 
1.721     harmsja  8076: div.LC_columnSection>* {
1.911     bisitz   8077:   float: left;
                   8078:   margin: 10px 20px 10px 0;
                   8079:   overflow:hidden;
1.693     droeschl 8080: }
1.721     harmsja  8081: 
1.795     www      8082: table em {
1.911     bisitz   8083:   font-weight: bold;
                   8084:   font-style: normal;
1.748     schulted 8085: }
1.795     www      8086: 
1.779     bisitz   8087: table.LC_tableBrowseRes,
1.795     www      8088: table.LC_tableOfContent {
1.911     bisitz   8089:   border:none;
                   8090:   border-spacing: 1px;
                   8091:   padding: 3px;
                   8092:   background-color: #FFFFFF;
                   8093:   font-size: 90%;
1.753     droeschl 8094: }
1.789     droeschl 8095: 
1.911     bisitz   8096: table.LC_tableOfContent {
                   8097:   border-collapse: collapse;
1.789     droeschl 8098: }
                   8099: 
1.771     droeschl 8100: table.LC_tableBrowseRes a,
1.768     schulted 8101: table.LC_tableOfContent a {
1.911     bisitz   8102:   background-color: transparent;
                   8103:   text-decoration: none;
1.753     droeschl 8104: }
                   8105: 
1.795     www      8106: table.LC_tableOfContent img {
1.911     bisitz   8107:   border: none;
                   8108:   height: 1.3em;
                   8109:   vertical-align: text-bottom;
                   8110:   margin-right: 0.3em;
1.753     droeschl 8111: }
1.757     schulted 8112: 
1.795     www      8113: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8114:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8115: }
                   8116: 
1.795     www      8117: a#LC_content_toolbar_everything {
1.911     bisitz   8118:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8119: }
                   8120: 
1.795     www      8121: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8122:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8123: }
                   8124: 
1.795     www      8125: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8126:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8127: }
                   8128: 
1.795     www      8129: a#LC_content_toolbar_changefolder {
1.911     bisitz   8130:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8131: }
                   8132: 
1.795     www      8133: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8134:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8135: }
                   8136: 
1.1043    raeburn  8137: a#LC_content_toolbar_edittoplevel {
                   8138:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8139: }
                   8140: 
1.795     www      8141: ul#LC_toolbar li a:hover {
1.911     bisitz   8142:   background-position: bottom center;
1.757     schulted 8143: }
                   8144: 
1.795     www      8145: ul#LC_toolbar {
1.911     bisitz   8146:   padding: 0;
                   8147:   margin: 2px;
                   8148:   list-style:none;
                   8149:   position:relative;
                   8150:   background-color:white;
1.1082    raeburn  8151:   overflow: auto;
1.757     schulted 8152: }
                   8153: 
1.795     www      8154: ul#LC_toolbar li {
1.911     bisitz   8155:   border:1px solid white;
                   8156:   padding: 0;
                   8157:   margin: 0;
                   8158:   float: left;
                   8159:   display:inline;
                   8160:   vertical-align:middle;
1.1082    raeburn  8161:   white-space: nowrap;
1.911     bisitz   8162: }
1.757     schulted 8163: 
1.783     amueller 8164: 
1.795     www      8165: a.LC_toolbarItem {
1.911     bisitz   8166:   display:block;
                   8167:   padding: 0;
                   8168:   margin: 0;
                   8169:   height: 32px;
                   8170:   width: 32px;
                   8171:   color:white;
                   8172:   border: none;
                   8173:   background-repeat:no-repeat;
                   8174:   background-color:transparent;
1.757     schulted 8175: }
                   8176: 
1.915     droeschl 8177: ul.LC_funclist {
                   8178:     margin: 0;
                   8179:     padding: 0.5em 1em 0.5em 0;
                   8180: }
                   8181: 
1.933     droeschl 8182: ul.LC_funclist > li:first-child {
                   8183:     font-weight:bold; 
                   8184:     margin-left:0.8em;
                   8185: }
                   8186: 
1.915     droeschl 8187: ul.LC_funclist + ul.LC_funclist {
                   8188:     /* 
                   8189:        left border as a seperator if we have more than
                   8190:        one list 
                   8191:     */
                   8192:     border-left: 1px solid $sidebg;
                   8193:     /* 
                   8194:        this hides the left border behind the border of the 
                   8195:        outer box if element is wrapped to the next 'line' 
                   8196:     */
                   8197:     margin-left: -1px;
                   8198: }
                   8199: 
1.843     bisitz   8200: ul.LC_funclist li {
1.915     droeschl 8201:   display: inline;
1.782     bisitz   8202:   white-space: nowrap;
1.915     droeschl 8203:   margin: 0 0 0 25px;
                   8204:   line-height: 150%;
1.782     bisitz   8205: }
                   8206: 
1.974     wenzelju 8207: .LC_hidden {
                   8208:   display: none;
                   8209: }
                   8210: 
1.1030    www      8211: .LCmodal-overlay {
                   8212: 		position:fixed;
                   8213: 		top:0;
                   8214: 		right:0;
                   8215: 		bottom:0;
                   8216: 		left:0;
                   8217: 		height:100%;
                   8218: 		width:100%;
                   8219: 		margin:0;
                   8220: 		padding:0;
                   8221: 		background:#999;
                   8222: 		opacity:.75;
                   8223: 		filter: alpha(opacity=75);
                   8224: 		-moz-opacity: 0.75;
                   8225: 		z-index:101;
                   8226: }
                   8227: 
                   8228: * html .LCmodal-overlay {   
                   8229: 		position: absolute;
                   8230: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8231: }
                   8232: 
                   8233: .LCmodal-window {
                   8234: 		position:fixed;
                   8235: 		top:50%;
                   8236: 		left:50%;
                   8237: 		margin:0;
                   8238: 		padding:0;
                   8239: 		z-index:102;
                   8240: 	}
                   8241: 
                   8242: * html .LCmodal-window {
                   8243: 		position:absolute;
                   8244: }
                   8245: 
                   8246: .LCclose-window {
                   8247: 		position:absolute;
                   8248: 		width:32px;
                   8249: 		height:32px;
                   8250: 		right:8px;
                   8251: 		top:8px;
                   8252: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8253: 		text-indent:-99999px;
                   8254: 		overflow:hidden;
                   8255: 		cursor:pointer;
                   8256: }
                   8257: 
1.1335    raeburn  8258: pre.LC_wordwrap {
                   8259:   white-space: pre-wrap;
                   8260:   white-space: -moz-pre-wrap;
                   8261:   white-space: -pre-wrap;
                   8262:   white-space: -o-pre-wrap;
                   8263:   word-wrap: break-word;
                   8264: }
                   8265: 
1.1100    raeburn  8266: /*
1.1231    damieng  8267:   styles used for response display
                   8268: */
                   8269: div.LC_radiofoil, div.LC_rankfoil {
                   8270:   margin: .5em 0em .5em 0em;
                   8271: }
                   8272: table.LC_itemgroup {
                   8273:   margin-top: 1em;
                   8274: }
                   8275: 
                   8276: /*
1.1100    raeburn  8277:   styles used by TTH when "Default set of options to pass to tth/m
                   8278:   when converting TeX" in course settings has been set
                   8279: 
                   8280:   option passed: -t
                   8281: 
                   8282: */
                   8283: 
                   8284: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8285: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8286: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8287: td div.norm {line-height:normal;}
                   8288: 
                   8289: /*
                   8290:   option passed -y3
                   8291: */
                   8292: 
                   8293: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8294: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8295: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8296: 
1.1230    damieng  8297: /*
                   8298:   sections with roles, for content only
                   8299: */
                   8300: section[class^="role-"] {
                   8301:   padding-left: 10px;
                   8302:   padding-right: 5px;
                   8303:   margin-top: 8px;
                   8304:   margin-bottom: 8px;
                   8305:   border: 1px solid #2A4;
                   8306:   border-radius: 5px;
                   8307:   box-shadow: 0px 1px 1px #BBB;
                   8308: }
                   8309: section[class^="role-"]>h1 {
                   8310:   position: relative;
                   8311:   margin: 0px;
                   8312:   padding-top: 10px;
                   8313:   padding-left: 40px;
                   8314: }
                   8315: section[class^="role-"]>h1:before {
                   8316:   position: absolute;
                   8317:   left: -5px;
                   8318:   top: 5px;
                   8319: }
                   8320: section.role-activity>h1:before {
                   8321:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8322: }
                   8323: section.role-advice>h1:before {
                   8324:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8325: }
                   8326: section.role-bibliography>h1:before {
                   8327:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8328: }
                   8329: section.role-citation>h1:before {
                   8330:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8331: }
                   8332: section.role-conclusion>h1:before {
                   8333:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8334: }
                   8335: section.role-definition>h1:before {
                   8336:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8337: }
                   8338: section.role-demonstration>h1:before {
                   8339:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8340: }
                   8341: section.role-example>h1:before {
                   8342:   content:url('/adm/daxe/images/section_icons/example.png');
                   8343: }
                   8344: section.role-explanation>h1:before {
                   8345:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8346: }
                   8347: section.role-introduction>h1:before {
                   8348:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8349: }
                   8350: section.role-method>h1:before {
                   8351:   content:url('/adm/daxe/images/section_icons/method.png');
                   8352: }
                   8353: section.role-more_information>h1:before {
                   8354:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8355: }
                   8356: section.role-objectives>h1:before {
                   8357:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8358: }
                   8359: section.role-prerequisites>h1:before {
                   8360:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8361: }
                   8362: section.role-remark>h1:before {
                   8363:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8364: }
                   8365: section.role-reminder>h1:before {
                   8366:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8367: }
                   8368: section.role-summary>h1:before {
                   8369:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8370: }
                   8371: section.role-syntax>h1:before {
                   8372:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8373: }
                   8374: section.role-warning>h1:before {
                   8375:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8376: }
                   8377: 
1.1269    raeburn  8378: #LC_minitab_header {
                   8379:   float:left;
                   8380:   width:100%;
                   8381:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8382:   font-size:93%;
                   8383:   line-height:normal;
                   8384:   margin: 0.5em 0 0.5em 0;
                   8385: }
                   8386: #LC_minitab_header ul {
                   8387:   margin:0;
                   8388:   padding:10px 10px 0;
                   8389:   list-style:none;
                   8390: }
                   8391: #LC_minitab_header li {
                   8392:   float:left;
                   8393:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8394:   margin:0;
                   8395:   padding:0 0 0 9px;
                   8396: }
                   8397: #LC_minitab_header a {
                   8398:   display:block;
                   8399:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8400:   padding:5px 15px 4px 6px;
                   8401: }
                   8402: #LC_minitab_header #LC_current_minitab {
                   8403:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8404: }
                   8405: #LC_minitab_header #LC_current_minitab a {
                   8406:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8407:   padding-bottom:5px;
                   8408: }
                   8409: 
                   8410: 
1.343     albertel 8411: END
                   8412: }
                   8413: 
1.306     albertel 8414: =pod
                   8415: 
                   8416: =item * &headtag()
                   8417: 
                   8418: Returns a uniform footer for LON-CAPA web pages.
                   8419: 
1.307     albertel 8420: Inputs: $title - optional title for the head
                   8421:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8422:         $args - optional arguments
1.319     albertel 8423:             force_register - if is true call registerurl so the remote is 
                   8424:                              informed
1.415     albertel 8425:             redirect       -> array ref of
                   8426:                                    1- seconds before redirect occurs
                   8427:                                    2- url to redirect to
                   8428:                                    3- whether the side effect should occur
1.315     albertel 8429:                            (side effect of setting 
                   8430:                                $env{'internal.head.redirect'} to the url 
                   8431:                                redirected too)
1.352     albertel 8432:             domain         -> force to color decorate a page for a specific
                   8433:                                domain
                   8434:             function       -> force usage of a specific rolish color scheme
                   8435:             bgcolor        -> override the default page bgcolor
1.460     albertel 8436:             no_auto_mt_title
                   8437:                            -> prevent &mt()ing the title arg
1.464     albertel 8438: 
1.306     albertel 8439: =cut
                   8440: 
                   8441: sub headtag {
1.313     albertel 8442:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8443:     
1.363     albertel 8444:     my $function = $args->{'function'} || &get_users_function();
                   8445:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8446:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8447:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8448:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8449: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8450: 		   #time(),
1.418     albertel 8451: 		   $env{'environment.color.timestamp'},
1.363     albertel 8452: 		   $function,$domain,$bgcolor);
                   8453: 
1.369     www      8454:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8455: 
1.308     albertel 8456:     my $result =
                   8457: 	'<head>'.
1.1160    raeburn  8458: 	&font_settings($args);
1.319     albertel 8459: 
1.1188    raeburn  8460:     my $inhibitprint;
                   8461:     if ($args->{'print_suppress'}) {
                   8462:         $inhibitprint = &print_suppression();
                   8463:     }
1.1064    raeburn  8464: 
1.461     albertel 8465:     if (!$args->{'frameset'}) {
                   8466: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8467:     }
1.962     droeschl 8468:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8469:         $result .= Apache::lonxml::display_title();
1.319     albertel 8470:     }
1.436     albertel 8471:     if (!$args->{'no_nav_bar'} 
                   8472: 	&& !$args->{'only_body'}
                   8473: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8474: 	$result .= &help_menu_js($httphost);
1.1032    www      8475:         $result.=&modal_window();
1.1038    www      8476:         $result.=&togglebox_script();
1.1034    www      8477:         $result.=&wishlist_window();
1.1041    www      8478:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8479:     } else {
                   8480:         if ($args->{'add_modal'}) {
                   8481:            $result.=&modal_window();
                   8482:         }
                   8483:         if ($args->{'add_wishlist'}) {
                   8484:            $result.=&wishlist_window();
                   8485:         }
1.1038    www      8486:         if ($args->{'add_togglebox'}) {
                   8487:            $result.=&togglebox_script();
                   8488:         }
1.1041    www      8489:         if ($args->{'add_progressbar'}) {
                   8490:            $result.=&LCprogressbarUpdate_script();
                   8491:         }
1.436     albertel 8492:     }
1.314     albertel 8493:     if (ref($args->{'redirect'})) {
1.414     albertel 8494: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8495: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8496: 	if (!$inhibit_continue) {
                   8497: 	    $env{'internal.head.redirect'} = $url;
                   8498: 	}
1.313     albertel 8499: 	$result.=<<ADDMETA
                   8500: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8501: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8502: ADDMETA
1.1210    raeburn  8503:     } else {
                   8504:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8505:             my $requrl = $env{'request.uri'};
                   8506:             if ($requrl eq '') {
                   8507:                 $requrl = $ENV{'REQUEST_URI'};
                   8508:                 $requrl =~ s/\?.+$//;
                   8509:             }
                   8510:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8511:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8512:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8513:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8514:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8515:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   8516:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8517:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   8518:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   8519:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   8520:                             if (($newserver) && ($newserver ne $lonhost)) {
                   8521:                                 my $numsec = 5;
                   8522:                                 my $timeout = $numsec * 1000;
                   8523:                                 my ($newurl,$locknum,%locks,$msg);
                   8524:                                 if ($env{'request.role.adv'}) {
                   8525:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8526:                                 }
                   8527:                                 my $disable_submit = 0;
                   8528:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   8529:                                     $disable_submit = 1;
                   8530:                                 }
                   8531:                                 if ($locknum) {
                   8532:                                     my @lockinfo = sort(values(%locks));
                   8533:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   8534:                                            join(", ",sort(values(%locks)))."\\n".
                   8535:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   8536:                                 } else {
                   8537:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8538:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   8539:                                     }
                   8540:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8541:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8542:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8543:                                         $newurl .= '&role='.$env{'request.role'};
                   8544:                                     }
                   8545:                                     if ($env{'request.symb'}) {
                   8546:                                         $newurl .= '&symb='.$env{'request.symb'};
                   8547:                                     } else {
                   8548:                                         $newurl .= '&origurl='.$requrl;
                   8549:                                     }
                   8550:                                 }
1.1222    damieng  8551:                                 &js_escape(\$msg);
1.1210    raeburn  8552:                                 $result.=<<OFFLOAD
                   8553: <meta http-equiv="pragma" content="no-cache" />
                   8554: <script type="text/javascript">
1.1215    raeburn  8555: // <![CDATA[
1.1210    raeburn  8556: function LC_Offload_Now() {
                   8557:     var dest = "$newurl";
                   8558:     if (dest != '') {
                   8559:         window.location.href="$newurl";
                   8560:     }
                   8561: }
1.1214    raeburn  8562: \$(document).ready(function () {
                   8563:     window.alert('$msg');
                   8564:     if ($disable_submit) {
1.1210    raeburn  8565:         \$(".LC_hwk_submit").prop("disabled", true);
                   8566:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  8567:     }
                   8568:     setTimeout('LC_Offload_Now()', $timeout);
                   8569: });
1.1215    raeburn  8570: // ]]>
1.1210    raeburn  8571: </script>
                   8572: OFFLOAD
                   8573:                             }
                   8574:                         }
                   8575:                     }
                   8576:                 }
                   8577:             }
                   8578:         }
1.313     albertel 8579:     }
1.306     albertel 8580:     if (!defined($title)) {
                   8581: 	$title = 'The LearningOnline Network with CAPA';
                   8582:     }
1.460     albertel 8583:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8584:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  8585: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8586:     if (!$args->{'frameset'}) {
                   8587:         $result .= ' /';
                   8588:     }
                   8589:     $result .= '>' 
1.1064    raeburn  8590:         .$inhibitprint
1.414     albertel 8591: 	.$head_extra;
1.1242    raeburn  8592:     my $clientmobile;
                   8593:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8594:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8595:     } else {
                   8596:         $clientmobile = $env{'browser.mobile'};
                   8597:     }
                   8598:     if ($clientmobile) {
1.1137    raeburn  8599:         $result .= '
                   8600: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8601: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8602:     }
1.1278    raeburn  8603:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8604:     return $result.'</head>';
1.306     albertel 8605: }
                   8606: 
                   8607: =pod
                   8608: 
1.340     albertel 8609: =item * &font_settings()
                   8610: 
                   8611: Returns neccessary <meta> to set the proper encoding
                   8612: 
1.1160    raeburn  8613: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8614: 
                   8615: =cut
                   8616: 
                   8617: sub font_settings {
1.1160    raeburn  8618:     my ($args) = @_;
1.340     albertel 8619:     my $headerstring='';
1.1160    raeburn  8620:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8621:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  8622:         $headerstring.=
                   8623:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8624:         if (!$args->{'frameset'}) {
                   8625: 	    $headerstring.= ' /';
                   8626:         }
                   8627: 	$headerstring .= '>'."\n";
1.340     albertel 8628:     }
                   8629:     return $headerstring;
                   8630: }
                   8631: 
1.341     albertel 8632: =pod
                   8633: 
1.1064    raeburn  8634: =item * &print_suppression()
                   8635: 
                   8636: In course context returns css which causes the body to be blank when media="print",
                   8637: if printout generation is unavailable for the current resource.
                   8638: 
                   8639: This could be because:
                   8640: 
                   8641: (a) printstartdate is in the future
                   8642: 
                   8643: (b) printenddate is in the past
                   8644: 
                   8645: (c) there is an active exam block with "printout"
                   8646: functionality blocked
                   8647: 
                   8648: Users with pav, pfo or evb privileges are exempt.
                   8649: 
                   8650: Inputs: none
                   8651: 
                   8652: =cut
                   8653: 
                   8654: 
                   8655: sub print_suppression {
                   8656:     my $noprint;
                   8657:     if ($env{'request.course.id'}) {
                   8658:         my $scope = $env{'request.course.id'};
                   8659:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8660:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8661:             return;
                   8662:         }
                   8663:         if ($env{'request.course.sec'} ne '') {
                   8664:             $scope .= "/$env{'request.course.sec'}";
                   8665:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8666:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8667:                 return;
1.1064    raeburn  8668:             }
                   8669:         }
                   8670:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8671:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8672:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8673:         if ($blocked) {
                   8674:             my $checkrole = "cm./$cdom/$cnum";
                   8675:             if ($env{'request.course.sec'} ne '') {
                   8676:                 $checkrole .= "/$env{'request.course.sec'}";
                   8677:             }
                   8678:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8679:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8680:                 $noprint = 1;
                   8681:             }
                   8682:         }
                   8683:         unless ($noprint) {
                   8684:             my $symb = &Apache::lonnet::symbread();
                   8685:             if ($symb ne '') {
                   8686:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8687:                 if (ref($navmap)) {
                   8688:                     my $res = $navmap->getBySymb($symb);
                   8689:                     if (ref($res)) {
                   8690:                         if (!$res->resprintable()) {
                   8691:                             $noprint = 1;
                   8692:                         }
                   8693:                     }
                   8694:                 }
                   8695:             }
                   8696:         }
                   8697:         if ($noprint) {
                   8698:             return <<"ENDSTYLE";
                   8699: <style type="text/css" media="print">
                   8700:     body { display:none }
                   8701: </style>
                   8702: ENDSTYLE
                   8703:         }
                   8704:     }
                   8705:     return;
                   8706: }
                   8707: 
                   8708: =pod
                   8709: 
1.341     albertel 8710: =item * &xml_begin()
                   8711: 
                   8712: Returns the needed doctype and <html>
                   8713: 
                   8714: Inputs: none
                   8715: 
                   8716: =cut
                   8717: 
                   8718: sub xml_begin {
1.1168    raeburn  8719:     my ($is_frameset) = @_;
1.341     albertel 8720:     my $output='';
                   8721: 
                   8722:     if ($env{'browser.mathml'}) {
                   8723: 	$output='<?xml version="1.0"?>'
                   8724:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8725: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8726:             
                   8727: #	    .'<!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">] >'
                   8728: 	    .'<!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">'
                   8729:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8730: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8731:     } elsif ($is_frameset) {
                   8732:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8733:                 '<html>'."\n";
1.341     albertel 8734:     } else {
1.1168    raeburn  8735: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8736:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8737:     }
                   8738:     return $output;
                   8739: }
1.340     albertel 8740: 
                   8741: =pod
                   8742: 
1.306     albertel 8743: =item * &start_page()
                   8744: 
                   8745: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8746: 
1.648     raeburn  8747: Inputs:
                   8748: 
                   8749: =over 4
                   8750: 
                   8751: $title - optional title for the page
                   8752: 
                   8753: $head_extra - optional extra HTML to incude inside the <head>
                   8754: 
                   8755: $args - additional optional args supported are:
                   8756: 
                   8757: =over 8
                   8758: 
                   8759:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8760:                                     arg on
1.814     bisitz   8761:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8762:              add_entries    -> additional attributes to add to the  <body>
                   8763:              domain         -> force to color decorate a page for a 
1.317     albertel 8764:                                     specific domain
1.648     raeburn  8765:              function       -> force usage of a specific rolish color
1.317     albertel 8766:                                     scheme
1.648     raeburn  8767:              redirect       -> see &headtag()
                   8768:              bgcolor        -> override the default page bg color
                   8769:              js_ready       -> return a string ready for being used in 
1.317     albertel 8770:                                     a javascript writeln
1.648     raeburn  8771:              html_encode    -> return a string ready for being used in 
1.320     albertel 8772:                                     a html attribute
1.648     raeburn  8773:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8774:                                     $forcereg arg
1.648     raeburn  8775:              frameset       -> if true will start with a <frameset>
1.330     albertel 8776:                                     rather than <body>
1.648     raeburn  8777:              skip_phases    -> hash ref of 
1.338     albertel 8778:                                     head -> skip the <html><head> generation
                   8779:                                     body -> skip all <body> generation
1.648     raeburn  8780:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8781:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8782:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  8783:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8784:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  8785:              group          -> includes the current group, if page is for a 
1.1274    raeburn  8786:                                specific group
                   8787:              use_absolute   -> for request for external resource or syllabus, this
                   8788:                                will contain https://<hostname> if server uses
                   8789:                                https (as per hosts.tab), but request is for http
                   8790:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8791: 
1.648     raeburn  8792: =back
1.460     albertel 8793: 
1.648     raeburn  8794: =back
1.562     albertel 8795: 
1.306     albertel 8796: =cut
                   8797: 
                   8798: sub start_page {
1.309     albertel 8799:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8800:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8801: 
1.315     albertel 8802:     $env{'internal.start_page'}++;
1.1318    raeburn  8803:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu);
1.964     droeschl 8804: 
1.338     albertel 8805:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8806:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8807:     }
1.1316    raeburn  8808: 
                   8809:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  8810:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   8811:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   8812:                 $args->{'no_primary_menu'} = 1;
                   8813:             }
                   8814:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   8815:                 $args->{'no_inline_menu'} = 1;
                   8816:             }
                   8817:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   8818:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   8819:             }
                   8820:         } else {
                   8821:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8822:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   8823:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   8824:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   8825:                     $args->{'no_primary_menu'} = 1;
                   8826:                 }
                   8827:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   8828:                     $args->{'no_inline_menu'} = 1;
                   8829:                 }
                   8830:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   8831:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   8832:                 }
                   8833:             }
                   8834:         }
1.1316    raeburn  8835:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   8836:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   8837:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
                   8838:     }
1.338     albertel 8839:     
                   8840:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8841: 	if ($args->{'frameset'}) {
                   8842: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8843: 						$args->{'add_entries'});
                   8844: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8845:         } else {
                   8846:             $result .=
                   8847:                 &bodytag($title, 
                   8848:                          $args->{'function'},       $args->{'add_entries'},
                   8849:                          $args->{'only_body'},      $args->{'domain'},
                   8850:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8851:                          $args->{'bgcolor'},        $args,
1.1318    raeburn  8852:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu);
1.831     bisitz   8853:         }
1.330     albertel 8854:     }
1.338     albertel 8855: 
1.315     albertel 8856:     if ($args->{'js_ready'}) {
1.713     kaisler  8857: 		$result = &js_ready($result);
1.315     albertel 8858:     }
1.320     albertel 8859:     if ($args->{'html_encode'}) {
1.713     kaisler  8860: 		$result = &html_encode($result);
                   8861:     }
                   8862: 
1.813     bisitz   8863:     # Preparation for new and consistent functionlist at top of screen
                   8864:     # if ($args->{'functionlist'}) {
                   8865:     #            $result .= &build_functionlist();
                   8866:     #}
                   8867: 
1.964     droeschl 8868:     # Don't add anything more if only_body wanted or in const space
                   8869:     return $result if    $args->{'only_body'} 
                   8870:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8871: 
                   8872:     #Breadcrumbs
1.758     kaisler  8873:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8874: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8875: 		#if any br links exists, add them to the breadcrumbs
                   8876: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8877: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8878: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8879: 			}
                   8880: 		}
1.1096    raeburn  8881:                 # if @advtools array contains items add then to the breadcrumbs
                   8882:                 if (@advtools > 0) {
                   8883:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8884:                 }
1.1272    raeburn  8885:                 my $menulink;
                   8886:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8887:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  8888:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  8889:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   8890:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   8891:                      (!$env{'request.role.adv'}))) {
                   8892:                     $menulink = 0;
                   8893:                 } else {
                   8894:                     undef($menulink);
                   8895:                 }
1.758     kaisler  8896: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8897: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  8898: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  8899:                 } else {
1.1272    raeburn  8900: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8901: 		}
1.320     albertel 8902:     }
1.315     albertel 8903:     return $result;
1.306     albertel 8904: }
                   8905: 
                   8906: sub end_page {
1.315     albertel 8907:     my ($args) = @_;
                   8908:     $env{'internal.end_page'}++;
1.330     albertel 8909:     my $result;
1.335     albertel 8910:     if ($args->{'discussion'}) {
                   8911: 	my ($target,$parser);
                   8912: 	if (ref($args->{'discussion'})) {
                   8913: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8914: 				$args->{'discussion'}{'parser'});
                   8915: 	}
                   8916: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8917:     }
1.330     albertel 8918:     if ($args->{'frameset'}) {
                   8919: 	$result .= '</frameset>';
                   8920:     } else {
1.635     raeburn  8921: 	$result .= &endbodytag($args);
1.330     albertel 8922:     }
1.1080    raeburn  8923:     unless ($args->{'notbody'}) {
                   8924:         $result .= "\n</html>";
                   8925:     }
1.330     albertel 8926: 
1.315     albertel 8927:     if ($args->{'js_ready'}) {
1.317     albertel 8928: 	$result = &js_ready($result);
1.315     albertel 8929:     }
1.335     albertel 8930: 
1.320     albertel 8931:     if ($args->{'html_encode'}) {
                   8932: 	$result = &html_encode($result);
                   8933:     }
1.335     albertel 8934: 
1.315     albertel 8935:     return $result;
                   8936: }
                   8937: 
1.1034    www      8938: sub wishlist_window {
                   8939:     return(<<'ENDWISHLIST');
1.1046    raeburn  8940: <script type="text/javascript">
1.1034    www      8941: // <![CDATA[
                   8942: // <!-- BEGIN LON-CAPA Internal
                   8943: function set_wishlistlink(title, path) {
                   8944:     if (!title) {
                   8945:         title = document.title;
                   8946:         title = title.replace(/^LON-CAPA /,'');
                   8947:     }
1.1175    raeburn  8948:     title = encodeURIComponent(title);
1.1203    raeburn  8949:     title = title.replace("'","\\\'");
1.1034    www      8950:     if (!path) {
                   8951:         path = location.pathname;
                   8952:     }
1.1175    raeburn  8953:     path = encodeURIComponent(path);
1.1203    raeburn  8954:     path = path.replace("'","\\\'");
1.1034    www      8955:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8956:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8957: }
                   8958: // END LON-CAPA Internal -->
                   8959: // ]]>
                   8960: </script>
                   8961: ENDWISHLIST
                   8962: }
                   8963: 
1.1030    www      8964: sub modal_window {
                   8965:     return(<<'ENDMODAL');
1.1046    raeburn  8966: <script type="text/javascript">
1.1030    www      8967: // <![CDATA[
                   8968: // <!-- BEGIN LON-CAPA Internal
                   8969: var modalWindow = {
                   8970: 	parent:"body",
                   8971: 	windowId:null,
                   8972: 	content:null,
                   8973: 	width:null,
                   8974: 	height:null,
                   8975: 	close:function()
                   8976: 	{
                   8977: 	        $(".LCmodal-window").remove();
                   8978: 	        $(".LCmodal-overlay").remove();
                   8979: 	},
                   8980: 	open:function()
                   8981: 	{
                   8982: 		var modal = "";
                   8983: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8984: 		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;\">";
                   8985: 		modal += this.content;
                   8986: 		modal += "</div>";	
                   8987: 
                   8988: 		$(this.parent).append(modal);
                   8989: 
                   8990: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8991: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8992: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8993: 	}
                   8994: };
1.1140    raeburn  8995: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8996: 	{
1.1266    raeburn  8997:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8998: 		modalWindow.windowId = "myModal";
                   8999: 		modalWindow.width = width;
                   9000: 		modalWindow.height = height;
1.1196    raeburn  9001: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9002: 		modalWindow.open();
1.1208    raeburn  9003: 	};
1.1030    www      9004: // END LON-CAPA Internal -->
                   9005: // ]]>
                   9006: </script>
                   9007: ENDMODAL
                   9008: }
                   9009: 
                   9010: sub modal_link {
1.1140    raeburn  9011:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9012:     unless ($width) { $width=480; }
                   9013:     unless ($height) { $height=400; }
1.1031    www      9014:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  9015:     unless ($transparency) { $transparency='true'; }
                   9016: 
1.1074    raeburn  9017:     my $target_attr;
                   9018:     if (defined($target)) {
                   9019:         $target_attr = 'target="'.$target.'"';
                   9020:     }
                   9021:     return <<"ENDLINK";
1.1336  ! raeburn  9022: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9023: ENDLINK
1.1030    www      9024: }
                   9025: 
1.1032    www      9026: sub modal_adhoc_script {
                   9027:     my ($funcname,$width,$height,$content)=@_;
                   9028:     return (<<ENDADHOC);
1.1046    raeburn  9029: <script type="text/javascript">
1.1032    www      9030: // <![CDATA[
                   9031:         var $funcname = function()
                   9032:         {
                   9033:                 modalWindow.windowId = "myModal";
                   9034:                 modalWindow.width = $width;
                   9035:                 modalWindow.height = $height;
                   9036:                 modalWindow.content = '$content';
                   9037:                 modalWindow.open();
                   9038:         };  
                   9039: // ]]>
                   9040: </script>
                   9041: ENDADHOC
                   9042: }
                   9043: 
1.1041    www      9044: sub modal_adhoc_inner {
                   9045:     my ($funcname,$width,$height,$content)=@_;
                   9046:     my $innerwidth=$width-20;
                   9047:     $content=&js_ready(
1.1140    raeburn  9048:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   9049:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9050:                  $content.
1.1041    www      9051:                  &end_scrollbox().
1.1140    raeburn  9052:                  &end_page()
1.1041    www      9053:              );
                   9054:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   9055: }
                   9056: 
                   9057: sub modal_adhoc_window {
                   9058:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   9059:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   9060:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9061: }
                   9062: 
                   9063: sub modal_adhoc_launch {
                   9064:     my ($funcname,$width,$height,$content)=@_;
                   9065:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9066: <script type="text/javascript">
                   9067: // <![CDATA[
                   9068: $funcname();
                   9069: // ]]>
                   9070: </script>
                   9071: ENDLAUNCH
                   9072: }
                   9073: 
                   9074: sub modal_adhoc_close {
                   9075:     return (<<ENDCLOSE);
                   9076: <script type="text/javascript">
                   9077: // <![CDATA[
                   9078: modalWindow.close();
                   9079: // ]]>
                   9080: </script>
                   9081: ENDCLOSE
                   9082: }
                   9083: 
1.1038    www      9084: sub togglebox_script {
                   9085:    return(<<ENDTOGGLE);
                   9086: <script type="text/javascript"> 
                   9087: // <![CDATA[
                   9088: function LCtoggleDisplay(id,hidetext,showtext) {
                   9089:    link = document.getElementById(id + "link").childNodes[0];
                   9090:    with (document.getElementById(id).style) {
                   9091:       if (display == "none" ) {
                   9092:           display = "inline";
                   9093:           link.nodeValue = hidetext;
                   9094:         } else {
                   9095:           display = "none";
                   9096:           link.nodeValue = showtext;
                   9097:        }
                   9098:    }
                   9099: }
                   9100: // ]]>
                   9101: </script>
                   9102: ENDTOGGLE
                   9103: }
                   9104: 
1.1039    www      9105: sub start_togglebox {
                   9106:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9107:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9108:     unless ($showtext) { $showtext=&mt('show'); }
                   9109:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9110:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9111:     return &start_data_table().
                   9112:            &start_data_table_header_row().
                   9113:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9114:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9115:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9116:            &end_data_table_header_row().
                   9117:            '<tr id="'.$id.'" style="display:none""><td>';
                   9118: }
                   9119: 
                   9120: sub end_togglebox {
                   9121:     return '</td></tr>'.&end_data_table();
                   9122: }
                   9123: 
1.1041    www      9124: sub LCprogressbar_script {
1.1302    raeburn  9125:    my ($id,$number_to_do)=@_;
                   9126:    if ($number_to_do) {
                   9127:        return(<<ENDPROGRESS);
1.1041    www      9128: <script type="text/javascript">
                   9129: // <![CDATA[
1.1045    www      9130: \$('#progressbar$id').progressbar({
1.1041    www      9131:   value: 0,
                   9132:   change: function(event, ui) {
                   9133:     var newVal = \$(this).progressbar('option', 'value');
                   9134:     \$('.pblabel', this).text(LCprogressTxt);
                   9135:   }
                   9136: });
                   9137: // ]]>
                   9138: </script>
                   9139: ENDPROGRESS
1.1302    raeburn  9140:    } else {
                   9141:        return(<<ENDPROGRESS);
                   9142: <script type="text/javascript">
                   9143: // <![CDATA[
                   9144: \$('#progressbar$id').progressbar({
                   9145:   value: false,
                   9146:   create: function(event, ui) {
                   9147:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9148:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9149:   }
                   9150: });
                   9151: // ]]>
                   9152: </script>
                   9153: ENDPROGRESS
                   9154:    }
1.1041    www      9155: }
                   9156: 
                   9157: sub LCprogressbarUpdate_script {
                   9158:    return(<<ENDPROGRESSUPDATE);
                   9159: <style type="text/css">
                   9160: .ui-progressbar { position:relative; }
1.1302    raeburn  9161: .progress-label {position: absolute; width: 100%; text-align: center; top: 1px; font-weight: bold; text-shadow: 1px 1px 0 #fff;margin: 0; line-height: 200%; }
1.1041    www      9162: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9163: </style>
                   9164: <script type="text/javascript">
                   9165: // <![CDATA[
1.1045    www      9166: var LCprogressTxt='---';
                   9167: 
1.1302    raeburn  9168: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9169:    LCprogressTxt=progresstext;
1.1302    raeburn  9170:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9171:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9172:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  9173:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9174:    } else {
                   9175:        \$('#progressbar'+id).progressbar('value',percent);
                   9176:    }
1.1041    www      9177: }
                   9178: // ]]>
                   9179: </script>
                   9180: ENDPROGRESSUPDATE
                   9181: }
                   9182: 
1.1042    www      9183: my $LClastpercent;
1.1045    www      9184: my $LCidcnt;
                   9185: my $LCcurrentid;
1.1042    www      9186: 
1.1041    www      9187: sub LCprogressbar {
1.1302    raeburn  9188:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9189:     $LClastpercent=0;
1.1045    www      9190:     $LCidcnt++;
                   9191:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  9192:     my ($starting,$content);
                   9193:     if ($number_to_do) {
                   9194:         $starting=&mt('Starting');
                   9195:         $content=(<<ENDPROGBAR);
                   9196: $preamble
1.1045    www      9197:   <div id="progressbar$LCcurrentid">
1.1041    www      9198:     <span class="pblabel">$starting</span>
                   9199:   </div>
                   9200: ENDPROGBAR
1.1302    raeburn  9201:     } else {
                   9202:         $starting=&mt('Loading...');
                   9203:         $LClastpercent='false';
                   9204:         $content=(<<ENDPROGBAR);
                   9205: $preamble
                   9206:   <div id="progressbar$LCcurrentid">
                   9207:       <div class="progress-label">$starting</div>
                   9208:   </div>
                   9209: ENDPROGBAR
                   9210:     }
                   9211:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9212: }
                   9213: 
                   9214: sub LCprogressbarUpdate {
1.1302    raeburn  9215:     my ($r,$val,$text,$number_to_do)=@_;
                   9216:     if ($number_to_do) {
                   9217:         unless ($val) { 
                   9218:             if ($LClastpercent) {
                   9219:                 $val=$LClastpercent;
                   9220:             } else {
                   9221:                 $val=0;
                   9222:             }
                   9223:         }
                   9224:         if ($val<0) { $val=0; }
                   9225:         if ($val>100) { $val=0; }
                   9226:         $LClastpercent=$val;
                   9227:         unless ($text) { $text=$val.'%'; }
                   9228:     } else {
                   9229:         $val = 'false';
1.1042    www      9230:     }
1.1041    www      9231:     $text=&js_ready($text);
1.1044    www      9232:     &r_print($r,<<ENDUPDATE);
1.1041    www      9233: <script type="text/javascript">
                   9234: // <![CDATA[
1.1302    raeburn  9235: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9236: // ]]>
                   9237: </script>
                   9238: ENDUPDATE
1.1035    www      9239: }
                   9240: 
1.1042    www      9241: sub LCprogressbarClose {
                   9242:     my ($r)=@_;
                   9243:     $LClastpercent=0;
1.1044    www      9244:     &r_print($r,<<ENDCLOSE);
1.1042    www      9245: <script type="text/javascript">
                   9246: // <![CDATA[
1.1045    www      9247: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9248: // ]]>
                   9249: </script>
                   9250: ENDCLOSE
1.1044    www      9251: }
                   9252: 
                   9253: sub r_print {
                   9254:     my ($r,$to_print)=@_;
                   9255:     if ($r) {
                   9256:       $r->print($to_print);
                   9257:       $r->rflush();
                   9258:     } else {
                   9259:       print($to_print);
                   9260:     }
1.1042    www      9261: }
                   9262: 
1.320     albertel 9263: sub html_encode {
                   9264:     my ($result) = @_;
                   9265: 
1.322     albertel 9266:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9267:     
                   9268:     return $result;
                   9269: }
1.1044    www      9270: 
1.317     albertel 9271: sub js_ready {
                   9272:     my ($result) = @_;
                   9273: 
1.323     albertel 9274:     $result =~ s/[\n\r]/ /xmsg;
                   9275:     $result =~ s/\\/\\\\/xmsg;
                   9276:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9277:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9278:     
                   9279:     return $result;
                   9280: }
                   9281: 
1.315     albertel 9282: sub validate_page {
                   9283:     if (  exists($env{'internal.start_page'})
1.316     albertel 9284: 	  &&     $env{'internal.start_page'} > 1) {
                   9285: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9286: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9287: 				 $ENV{'request.filename'});
1.315     albertel 9288:     }
                   9289:     if (  exists($env{'internal.end_page'})
1.316     albertel 9290: 	  &&     $env{'internal.end_page'} > 1) {
                   9291: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9292: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9293: 				 $env{'request.filename'});
1.315     albertel 9294:     }
                   9295:     if (     exists($env{'internal.start_page'})
                   9296: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9297: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9298: 				 $env{'request.filename'});
1.315     albertel 9299:     }
                   9300:     if (   ! exists($env{'internal.start_page'})
                   9301: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9302: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9303: 				 $env{'request.filename'});
1.315     albertel 9304:     }
1.306     albertel 9305: }
1.315     albertel 9306: 
1.996     www      9307: 
                   9308: sub start_scrollbox {
1.1140    raeburn  9309:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9310:     unless ($outerwidth) { $outerwidth='520px'; }
                   9311:     unless ($width) { $width='500px'; }
                   9312:     unless ($height) { $height='200px'; }
1.1075    raeburn  9313:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9314:     if ($id ne '') {
1.1140    raeburn  9315:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  9316:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9317:     }
1.1075    raeburn  9318:     if ($bgcolor ne '') {
                   9319:         $tdcol = "background-color: $bgcolor;";
                   9320:     }
1.1137    raeburn  9321:     my $nicescroll_js;
                   9322:     if ($env{'browser.mobile'}) {
1.1140    raeburn  9323:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9324:     }
                   9325:     return <<"END";
                   9326: $nicescroll_js
                   9327: 
                   9328: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   9329: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   9330: END
                   9331: }
                   9332: 
                   9333: sub end_scrollbox {
                   9334:     return '</div></td></tr></table>';
                   9335: }
                   9336: 
                   9337: sub nicescroll_javascript {
                   9338:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9339:     my %options;
                   9340:     if (ref($cursor) eq 'HASH') {
                   9341:         %options = %{$cursor};
                   9342:     }
                   9343:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9344:         $options{'railalign'} = 'left';
                   9345:     }
                   9346:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9347:         my $function  = &get_users_function();
                   9348:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9349:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9350:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9351:         }
1.1140    raeburn  9352:     }
                   9353:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9354:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9355:             $options{'cursoropacity'}='1.0';
                   9356:         }
1.1140    raeburn  9357:     } else {
                   9358:         $options{'cursoropacity'}='1.0';
                   9359:     }
                   9360:     if ($options{'cursorfixedheight'} eq 'none') {
                   9361:         delete($options{'cursorfixedheight'});
                   9362:     } else {
                   9363:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9364:     }
                   9365:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9366:         delete($options{'railoffset'});
                   9367:     }
                   9368:     my @niceoptions;
                   9369:     while (my($key,$value) = each(%options)) {
                   9370:         if ($value =~ /^\{.+\}$/) {
                   9371:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9372:         } else {
1.1140    raeburn  9373:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9374:         }
1.1140    raeburn  9375:     }
                   9376:     my $nicescroll_js = '
1.1137    raeburn  9377: $(document).ready(
1.1140    raeburn  9378:       function() {
                   9379:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9380:       }
1.1137    raeburn  9381: );
                   9382: ';
1.1140    raeburn  9383:     if ($framecheck) {
                   9384:         $nicescroll_js .= '
                   9385: function expand_div(caller) {
                   9386:     if (top === self) {
                   9387:         document.getElementById("'.$id.'").style.width = "auto";
                   9388:         document.getElementById("'.$id.'").style.height = "auto";
                   9389:     } else {
                   9390:         try {
                   9391:             if (parent.frames) {
                   9392:                 if (parent.frames.length > 1) {
                   9393:                     var framesrc = parent.frames[1].location.href;
                   9394:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9395:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9396:                         document.getElementById("'.$id.'").style.width = "auto";
                   9397:                         document.getElementById("'.$id.'").style.height = "auto";
                   9398:                     }
                   9399:                 }
                   9400:             }
                   9401:         } catch (e) {
                   9402:             return;
                   9403:         }
1.1137    raeburn  9404:     }
1.1140    raeburn  9405:     return;
1.996     www      9406: }
1.1140    raeburn  9407: ';
                   9408:     }
                   9409:     if ($needjsready) {
                   9410:         $nicescroll_js = '
                   9411: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9412:     } else {
                   9413:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9414:     }
                   9415:     return $nicescroll_js;
1.996     www      9416: }
                   9417: 
1.318     albertel 9418: sub simple_error_page {
1.1150    bisitz   9419:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  9420:     my %displayargs;
1.1151    raeburn  9421:     if (ref($args) eq 'HASH') {
                   9422:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  9423:         if ($args->{'only_body'}) {
                   9424:             $displayargs{'only_body'} = 1;
                   9425:         }
                   9426:         if ($args->{'no_nav_bar'}) {
                   9427:             $displayargs{'no_nav_bar'} = 1;
                   9428:         }
1.1151    raeburn  9429:     } else {
                   9430:         $msg = &mt($msg);
                   9431:     }
1.1150    bisitz   9432: 
1.318     albertel 9433:     my $page =
1.1304    raeburn  9434: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   9435: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9436: 	&Apache::loncommon::end_page();
                   9437:     if (ref($r)) {
                   9438: 	$r->print($page);
1.327     albertel 9439: 	return;
1.318     albertel 9440:     }
                   9441:     return $page;
                   9442: }
1.347     albertel 9443: 
                   9444: {
1.610     albertel 9445:     my @row_count;
1.961     onken    9446: 
                   9447:     sub start_data_table_count {
                   9448:         unshift(@row_count, 0);
                   9449:         return;
                   9450:     }
                   9451: 
                   9452:     sub end_data_table_count {
                   9453:         shift(@row_count);
                   9454:         return;
                   9455:     }
                   9456: 
1.347     albertel 9457:     sub start_data_table {
1.1018    raeburn  9458: 	my ($add_class,$id) = @_;
1.422     albertel 9459: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9460:         my $table_id;
                   9461:         if (defined($id)) {
                   9462:             $table_id = ' id="'.$id.'"';
                   9463:         }
1.961     onken    9464: 	&start_data_table_count();
1.1018    raeburn  9465: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9466:     }
                   9467: 
                   9468:     sub end_data_table {
1.961     onken    9469: 	&end_data_table_count();
1.389     albertel 9470: 	return '</table>'."\n";;
1.347     albertel 9471:     }
                   9472: 
                   9473:     sub start_data_table_row {
1.974     wenzelju 9474: 	my ($add_class, $id) = @_;
1.610     albertel 9475: 	$row_count[0]++;
                   9476: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9477: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9478:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9479:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9480:     }
1.471     banghart 9481:     
                   9482:     sub continue_data_table_row {
1.974     wenzelju 9483: 	my ($add_class, $id) = @_;
1.610     albertel 9484: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9485: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9486:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9487:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9488:     }
1.347     albertel 9489: 
                   9490:     sub end_data_table_row {
1.389     albertel 9491: 	return '</tr>'."\n";;
1.347     albertel 9492:     }
1.367     www      9493: 
1.421     albertel 9494:     sub start_data_table_empty_row {
1.707     bisitz   9495: #	$row_count[0]++;
1.421     albertel 9496: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9497:     }
                   9498: 
                   9499:     sub end_data_table_empty_row {
                   9500: 	return '</tr>'."\n";;
                   9501:     }
                   9502: 
1.367     www      9503:     sub start_data_table_header_row {
1.389     albertel 9504: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9505:     }
                   9506: 
                   9507:     sub end_data_table_header_row {
1.389     albertel 9508: 	return '</tr>'."\n";;
1.367     www      9509:     }
1.890     droeschl 9510: 
                   9511:     sub data_table_caption {
                   9512:         my $caption = shift;
                   9513:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9514:     }
1.347     albertel 9515: }
                   9516: 
1.548     albertel 9517: =pod
                   9518: 
                   9519: =item * &inhibit_menu_check($arg)
                   9520: 
                   9521: Checks for a inhibitmenu state and generates output to preserve it
                   9522: 
                   9523: Inputs:         $arg - can be any of
                   9524:                      - undef - in which case the return value is a string 
                   9525:                                to add  into arguments list of a uri
                   9526:                      - 'input' - in which case the return value is a HTML
                   9527:                                  <form> <input> field of type hidden to
                   9528:                                  preserve the value
                   9529:                      - a url - in which case the return value is the url with
                   9530:                                the neccesary cgi args added to preserve the
                   9531:                                inhibitmenu state
                   9532:                      - a ref to a url - no return value, but the string is
                   9533:                                         updated to include the neccessary cgi
                   9534:                                         args to preserve the inhibitmenu state
                   9535: 
                   9536: =cut
                   9537: 
                   9538: sub inhibit_menu_check {
                   9539:     my ($arg) = @_;
                   9540:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9541:     if ($arg eq 'input') {
                   9542: 	if ($env{'form.inhibitmenu'}) {
                   9543: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9544: 	} else {
                   9545: 	    return
                   9546: 	}
                   9547:     }
                   9548:     if ($env{'form.inhibitmenu'}) {
                   9549: 	if (ref($arg)) {
                   9550: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9551: 	} elsif ($arg eq '') {
                   9552: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9553: 	} else {
                   9554: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9555: 	}
                   9556:     }
                   9557:     if (!ref($arg)) {
                   9558: 	return $arg;
                   9559:     }
                   9560: }
                   9561: 
1.251     albertel 9562: ###############################################
1.182     matthew  9563: 
                   9564: =pod
                   9565: 
1.549     albertel 9566: =back
                   9567: 
                   9568: =head1 User Information Routines
                   9569: 
                   9570: =over 4
                   9571: 
1.405     albertel 9572: =item * &get_users_function()
1.182     matthew  9573: 
                   9574: Used by &bodytag to determine the current users primary role.
                   9575: Returns either 'student','coordinator','admin', or 'author'.
                   9576: 
                   9577: =cut
                   9578: 
                   9579: ###############################################
                   9580: sub get_users_function {
1.815     tempelho 9581:     my $function = 'norole';
1.818     tempelho 9582:     if ($env{'request.role'}=~/^(st)/) {
                   9583:         $function='student';
                   9584:     }
1.907     raeburn  9585:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9586:         $function='coordinator';
                   9587:     }
1.258     albertel 9588:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9589:         $function='admin';
                   9590:     }
1.826     bisitz   9591:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9592:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9593:         $function='author';
                   9594:     }
                   9595:     return $function;
1.54      www      9596: }
1.99      www      9597: 
                   9598: ###############################################
                   9599: 
1.233     raeburn  9600: =pod
                   9601: 
1.821     raeburn  9602: =item * &show_course()
                   9603: 
                   9604: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9605: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9606: 
                   9607: Inputs:
                   9608: None
                   9609: 
                   9610: Outputs:
                   9611: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9612: 
                   9613: =cut
                   9614: 
                   9615: ###############################################
                   9616: sub show_course {
                   9617:     my $course = !$env{'user.adv'};
                   9618:     if (!$env{'user.adv'}) {
                   9619:         foreach my $env (keys(%env)) {
                   9620:             next if ($env !~ m/^user\.priv\./);
                   9621:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9622:                 $course = 0;
                   9623:                 last;
                   9624:             }
                   9625:         }
                   9626:     }
                   9627:     return $course;
                   9628: }
                   9629: 
                   9630: ###############################################
                   9631: 
                   9632: =pod
                   9633: 
1.542     raeburn  9634: =item * &check_user_status()
1.274     raeburn  9635: 
                   9636: Determines current status of supplied role for a
                   9637: specific user. Roles can be active, previous or future.
                   9638: 
                   9639: Inputs: 
                   9640: user's domain, user's username, course's domain,
1.375     raeburn  9641: course's number, optional section ID.
1.274     raeburn  9642: 
                   9643: Outputs:
                   9644: role status: active, previous or future. 
                   9645: 
                   9646: =cut
                   9647: 
                   9648: sub check_user_status {
1.412     raeburn  9649:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9650:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  9651:     my @uroles = keys(%userinfo);
1.274     raeburn  9652:     my $srchstr;
                   9653:     my $active_chk = 'none';
1.412     raeburn  9654:     my $now = time;
1.274     raeburn  9655:     if (@uroles > 0) {
1.908     raeburn  9656:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9657:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9658:         } else {
1.412     raeburn  9659:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9660:         }
                   9661:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9662:             my $role_end = 0;
                   9663:             my $role_start = 0;
                   9664:             $active_chk = 'active';
1.412     raeburn  9665:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9666:                 $role_end = $1;
                   9667:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9668:                     $role_start = $1;
1.274     raeburn  9669:                 }
                   9670:             }
                   9671:             if ($role_start > 0) {
1.412     raeburn  9672:                 if ($now < $role_start) {
1.274     raeburn  9673:                     $active_chk = 'future';
                   9674:                 }
                   9675:             }
                   9676:             if ($role_end > 0) {
1.412     raeburn  9677:                 if ($now > $role_end) {
1.274     raeburn  9678:                     $active_chk = 'previous';
                   9679:                 }
                   9680:             }
                   9681:         }
                   9682:     }
                   9683:     return $active_chk;
                   9684: }
                   9685: 
                   9686: ###############################################
                   9687: 
                   9688: =pod
                   9689: 
1.405     albertel 9690: =item * &get_sections()
1.233     raeburn  9691: 
                   9692: Determines all the sections for a course including
                   9693: sections with students and sections containing other roles.
1.419     raeburn  9694: Incoming parameters: 
                   9695: 
                   9696: 1. domain
                   9697: 2. course number 
                   9698: 3. reference to array containing roles for which sections should 
                   9699: be gathered (optional).
                   9700: 4. reference to array containing status types for which sections 
                   9701: should be gathered (optional).
                   9702: 
                   9703: If the third argument is undefined, sections are gathered for any role. 
                   9704: If the fourth argument is undefined, sections are gathered for any status.
                   9705: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9706:  
1.374     raeburn  9707: Returns section hash (keys are section IDs, values are
                   9708: number of users in each section), subject to the
1.419     raeburn  9709: optional roles filter, optional status filter 
1.233     raeburn  9710: 
                   9711: =cut
                   9712: 
                   9713: ###############################################
                   9714: sub get_sections {
1.419     raeburn  9715:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9716:     if (!defined($cdom) || !defined($cnum)) {
                   9717:         my $cid =  $env{'request.course.id'};
                   9718: 
                   9719: 	return if (!defined($cid));
                   9720: 
                   9721:         $cdom = $env{'course.'.$cid.'.domain'};
                   9722:         $cnum = $env{'course.'.$cid.'.num'};
                   9723:     }
                   9724: 
                   9725:     my %sectioncount;
1.419     raeburn  9726:     my $now = time;
1.240     albertel 9727: 
1.1118    raeburn  9728:     my $check_students = 1;
                   9729:     my $only_students = 0;
                   9730:     if (ref($possible_roles) eq 'ARRAY') {
                   9731:         if (grep(/^st$/,@{$possible_roles})) {
                   9732:             if (@{$possible_roles} == 1) {
                   9733:                 $only_students = 1;
                   9734:             }
                   9735:         } else {
                   9736:             $check_students = 0;
                   9737:         }
                   9738:     }
                   9739: 
                   9740:     if ($check_students) { 
1.276     albertel 9741: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9742: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9743: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9744:         my $start_index = &Apache::loncoursedata::CL_START();
                   9745:         my $end_index = &Apache::loncoursedata::CL_END();
                   9746:         my $status;
1.366     albertel 9747: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9748: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9749: 				                     $data->[$status_index],
                   9750:                                                      $data->[$start_index],
                   9751:                                                      $data->[$end_index]);
                   9752:             if ($stu_status eq 'Active') {
                   9753:                 $status = 'active';
                   9754:             } elsif ($end < $now) {
                   9755:                 $status = 'previous';
                   9756:             } elsif ($start > $now) {
                   9757:                 $status = 'future';
                   9758:             } 
                   9759: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9760:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9761:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9762: 		    $sectioncount{$section}++;
                   9763:                 }
1.240     albertel 9764: 	    }
                   9765: 	}
                   9766:     }
1.1118    raeburn  9767:     if ($only_students) {
                   9768:         return %sectioncount;
                   9769:     }
1.240     albertel 9770:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9771:     foreach my $user (sort(keys(%courseroles))) {
                   9772: 	if ($user !~ /^(\w{2})/) { next; }
                   9773: 	my ($role) = ($user =~ /^(\w{2})/);
                   9774: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9775: 	my ($section,$status);
1.240     albertel 9776: 	if ($role eq 'cr' &&
                   9777: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9778: 	    $section=$1;
                   9779: 	}
                   9780: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9781: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9782:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9783:         if ($end == -1 && $start == -1) {
                   9784:             next; #deleted role
                   9785:         }
                   9786:         if (!defined($possible_status)) { 
                   9787:             $sectioncount{$section}++;
                   9788:         } else {
                   9789:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9790:                 $status = 'active';
                   9791:             } elsif ($end < $now) {
                   9792:                 $status = 'future';
                   9793:             } elsif ($start > $now) {
                   9794:                 $status = 'previous';
                   9795:             }
                   9796:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9797:                 $sectioncount{$section}++;
                   9798:             }
                   9799:         }
1.233     raeburn  9800:     }
1.366     albertel 9801:     return %sectioncount;
1.233     raeburn  9802: }
                   9803: 
1.274     raeburn  9804: ###############################################
1.294     raeburn  9805: 
                   9806: =pod
1.405     albertel 9807: 
                   9808: =item * &get_course_users()
                   9809: 
1.275     raeburn  9810: Retrieves usernames:domains for users in the specified course
                   9811: with specific role(s), and access status. 
                   9812: 
                   9813: Incoming parameters:
1.277     albertel 9814: 1. course domain
                   9815: 2. course number
                   9816: 3. access status: users must have - either active, 
1.275     raeburn  9817: previous, future, or all.
1.277     albertel 9818: 4. reference to array of permissible roles
1.288     raeburn  9819: 5. reference to array of section restrictions (optional)
                   9820: 6. reference to results object (hash of hashes).
                   9821: 7. reference to optional userdata hash
1.609     raeburn  9822: 8. reference to optional statushash
1.630     raeburn  9823: 9. flag if privileged users (except those set to unhide in
                   9824:    course settings) should be excluded    
1.609     raeburn  9825: Keys of top level results hash are roles.
1.275     raeburn  9826: Keys of inner hashes are username:domain, with 
                   9827: values set to access type.
1.288     raeburn  9828: Optional userdata hash returns an array with arguments in the 
                   9829: same order as loncoursedata::get_classlist() for student data.
                   9830: 
1.609     raeburn  9831: Optional statushash returns
                   9832: 
1.288     raeburn  9833: Entries for end, start, section and status are blank because
                   9834: of the possibility of multiple values for non-student roles.
                   9835: 
1.275     raeburn  9836: =cut
1.405     albertel 9837: 
1.275     raeburn  9838: ###############################################
1.405     albertel 9839: 
1.275     raeburn  9840: sub get_course_users {
1.630     raeburn  9841:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9842:     my %idx = ();
1.419     raeburn  9843:     my %seclists;
1.288     raeburn  9844: 
                   9845:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9846:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9847:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9848:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9849:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9850:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9851:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9852:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9853: 
1.290     albertel 9854:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9855:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9856:         my $now = time;
1.277     albertel 9857:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9858:             my $match = 0;
1.412     raeburn  9859:             my $secmatch = 0;
1.419     raeburn  9860:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9861:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9862:             if ($section eq '') {
                   9863:                 $section = 'none';
                   9864:             }
1.291     albertel 9865:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9866:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9867:                     $secmatch = 1;
                   9868:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9869:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9870:                         $secmatch = 1;
                   9871:                     }
                   9872:                 } else {  
1.419     raeburn  9873: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9874: 		        $secmatch = 1;
                   9875:                     }
1.290     albertel 9876: 		}
1.412     raeburn  9877:                 if (!$secmatch) {
                   9878:                     next;
                   9879:                 }
1.419     raeburn  9880:             }
1.275     raeburn  9881:             if (defined($$types{'active'})) {
1.288     raeburn  9882:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9883:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9884:                     $match = 1;
1.275     raeburn  9885:                 }
                   9886:             }
                   9887:             if (defined($$types{'previous'})) {
1.609     raeburn  9888:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9889:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9890:                     $match = 1;
1.275     raeburn  9891:                 }
                   9892:             }
                   9893:             if (defined($$types{'future'})) {
1.609     raeburn  9894:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9895:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9896:                     $match = 1;
1.275     raeburn  9897:                 }
                   9898:             }
1.609     raeburn  9899:             if ($match) {
                   9900:                 push(@{$seclists{$student}},$section);
                   9901:                 if (ref($userdata) eq 'HASH') {
                   9902:                     $$userdata{$student} = $$classlist{$student};
                   9903:                 }
                   9904:                 if (ref($statushash) eq 'HASH') {
                   9905:                     $statushash->{$student}{'st'}{$section} = $status;
                   9906:                 }
1.288     raeburn  9907:             }
1.275     raeburn  9908:         }
                   9909:     }
1.412     raeburn  9910:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9911:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9912:         my $now = time;
1.609     raeburn  9913:         my %displaystatus = ( previous => 'Expired',
                   9914:                               active   => 'Active',
                   9915:                               future   => 'Future',
                   9916:                             );
1.1121    raeburn  9917:         my (%nothide,@possdoms);
1.630     raeburn  9918:         if ($hidepriv) {
                   9919:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9920:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9921:                 if ($user !~ /:/) {
                   9922:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9923:                 } else {
                   9924:                     $nothide{$user} = 1;
                   9925:                 }
                   9926:             }
1.1121    raeburn  9927:             my @possdoms = ($cdom);
                   9928:             if ($coursehash{'checkforpriv'}) {
                   9929:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9930:             }
1.630     raeburn  9931:         }
1.439     raeburn  9932:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9933:             my $match = 0;
1.412     raeburn  9934:             my $secmatch = 0;
1.439     raeburn  9935:             my $status;
1.412     raeburn  9936:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9937:             $user =~ s/:$//;
1.439     raeburn  9938:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9939:             if ($end == -1 || $start == -1) {
                   9940:                 next;
                   9941:             }
                   9942:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9943:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9944:                 my ($uname,$udom) = split(/:/,$user);
                   9945:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9946:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9947:                         $secmatch = 1;
                   9948:                     } elsif ($usec eq '') {
1.420     albertel 9949:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9950:                             $secmatch = 1;
                   9951:                         }
                   9952:                     } else {
                   9953:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9954:                             $secmatch = 1;
                   9955:                         }
                   9956:                     }
                   9957:                     if (!$secmatch) {
                   9958:                         next;
                   9959:                     }
1.288     raeburn  9960:                 }
1.419     raeburn  9961:                 if ($usec eq '') {
                   9962:                     $usec = 'none';
                   9963:                 }
1.275     raeburn  9964:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9965:                     if ($hidepriv) {
1.1121    raeburn  9966:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9967:                             (!$nothide{$uname.':'.$udom})) {
                   9968:                             next;
                   9969:                         }
                   9970:                     }
1.503     raeburn  9971:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9972:                         $status = 'previous';
                   9973:                     } elsif ($start > $now) {
                   9974:                         $status = 'future';
                   9975:                     } else {
                   9976:                         $status = 'active';
                   9977:                     }
1.277     albertel 9978:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9979:                         if ($status eq $type) {
1.420     albertel 9980:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9981:                                 push(@{$$users{$role}{$user}},$type);
                   9982:                             }
1.288     raeburn  9983:                             $match = 1;
                   9984:                         }
                   9985:                     }
1.419     raeburn  9986:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9987:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9988: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9989:                         }
1.420     albertel 9990:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9991:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9992:                         }
1.609     raeburn  9993:                         if (ref($statushash) eq 'HASH') {
                   9994:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9995:                         }
1.275     raeburn  9996:                     }
                   9997:                 }
                   9998:             }
                   9999:         }
1.290     albertel 10000:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10001:             if ((defined($cdom)) && (defined($cnum))) {
                   10002:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10003:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10004:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10005:                     next if ($owner eq '');
                   10006:                     my ($ownername,$ownerdom);
                   10007:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10008:                         $ownername = $1;
                   10009:                         $ownerdom = $2;
                   10010:                     } else {
                   10011:                         $ownername = $owner;
                   10012:                         $ownerdom = $cdom;
                   10013:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10014:                     }
                   10015:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10016:                     if (defined($userdata) && 
1.609     raeburn  10017: 			!exists($$userdata{$owner})) {
                   10018: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10019:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10020:                             push(@{$seclists{$owner}},'none');
                   10021:                         }
                   10022:                         if (ref($statushash) eq 'HASH') {
                   10023:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10024:                         }
1.290     albertel 10025: 		    }
1.279     raeburn  10026:                 }
                   10027:             }
                   10028:         }
1.419     raeburn  10029:         foreach my $user (keys(%seclists)) {
                   10030:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10031:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10032:         }
1.275     raeburn  10033:     }
                   10034:     return;
                   10035: }
                   10036: 
1.288     raeburn  10037: sub get_user_info {
                   10038:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10039:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10040: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10041:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10042:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10043:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10044:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10045:     return;
                   10046: }
1.275     raeburn  10047: 
1.472     raeburn  10048: ###############################################
                   10049: 
                   10050: =pod
                   10051: 
                   10052: =item * &get_user_quota()
                   10053: 
1.1134    raeburn  10054: Retrieves quota assigned for storage of user files.
                   10055: Default is to report quota for portfolio files.
1.472     raeburn  10056: 
                   10057: Incoming parameters:
                   10058: 1. user's username
                   10059: 2. user's domain
1.1134    raeburn  10060: 3. quota name - portfolio, author, or course
1.1136    raeburn  10061:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  10062: 4. crstype - official, unofficial, textbook, placement or community, 
                   10063:    if quota name is course
1.472     raeburn  10064: 
                   10065: Returns:
1.1163    raeburn  10066: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10067: 2. (Optional) Type of setting: custom or default
                   10068:    (individually assigned or default for user's 
                   10069:    institutional status).
                   10070: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10071:    or student - types as defined in localenroll::inst_usertypes 
                   10072:    for user's domain, which determines default quota for user.
                   10073: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10074: 
                   10075: If a value has been stored in the user's environment, 
1.536     raeburn  10076: it will return that, otherwise it returns the maximal default
1.1134    raeburn  10077: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10078: 
                   10079: =cut
                   10080: 
                   10081: ###############################################
                   10082: 
                   10083: 
                   10084: sub get_user_quota {
1.1136    raeburn  10085:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10086:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10087:     if (!defined($udom)) {
                   10088:         $udom = $env{'user.domain'};
                   10089:     }
                   10090:     if (!defined($uname)) {
                   10091:         $uname = $env{'user.name'};
                   10092:     }
                   10093:     if (($udom eq '' || $uname eq '') ||
                   10094:         ($udom eq 'public') && ($uname eq 'public')) {
                   10095:         $quota = 0;
1.536     raeburn  10096:         $quotatype = 'default';
                   10097:         $defquota = 0; 
1.472     raeburn  10098:     } else {
1.536     raeburn  10099:         my $inststatus;
1.1134    raeburn  10100:         if ($quotaname eq 'course') {
                   10101:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10102:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10103:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10104:             } else {
                   10105:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10106:                 $quota = $cenv{'internal.uploadquota'};
                   10107:             }
1.536     raeburn  10108:         } else {
1.1134    raeburn  10109:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10110:                 if ($quotaname eq 'author') {
                   10111:                     $quota = $env{'environment.authorquota'};
                   10112:                 } else {
                   10113:                     $quota = $env{'environment.portfolioquota'};
                   10114:                 }
                   10115:                 $inststatus = $env{'environment.inststatus'};
                   10116:             } else {
                   10117:                 my %userenv = 
                   10118:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10119:                                          'authorquota','inststatus'],$udom,$uname);
                   10120:                 my ($tmp) = keys(%userenv);
                   10121:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10122:                     if ($quotaname eq 'author') {
                   10123:                         $quota = $userenv{'authorquota'};
                   10124:                     } else {
                   10125:                         $quota = $userenv{'portfolioquota'};
                   10126:                     }
                   10127:                     $inststatus = $userenv{'inststatus'};
                   10128:                 } else {
                   10129:                     undef(%userenv);
                   10130:                 }
                   10131:             }
                   10132:         }
                   10133:         if ($quota eq '' || wantarray) {
                   10134:             if ($quotaname eq 'course') {
                   10135:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  10136:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  10137:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   10138:                     ($crstype eq 'placement')) { 
1.1136    raeburn  10139:                     $defquota = $domdefs{$crstype.'quota'};
                   10140:                 }
                   10141:                 if ($defquota eq '') {
                   10142:                     $defquota = 500;
                   10143:                 }
1.1134    raeburn  10144:             } else {
                   10145:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10146:             }
                   10147:             if ($quota eq '') {
                   10148:                 $quota = $defquota;
                   10149:                 $quotatype = 'default';
                   10150:             } else {
                   10151:                 $quotatype = 'custom';
                   10152:             }
1.472     raeburn  10153:         }
                   10154:     }
1.536     raeburn  10155:     if (wantarray) {
                   10156:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10157:     } else {
                   10158:         return $quota;
                   10159:     }
1.472     raeburn  10160: }
                   10161: 
                   10162: ###############################################
                   10163: 
                   10164: =pod
                   10165: 
                   10166: =item * &default_quota()
                   10167: 
1.536     raeburn  10168: Retrieves default quota assigned for storage of user portfolio files,
                   10169: given an (optional) user's institutional status.
1.472     raeburn  10170: 
                   10171: Incoming parameters:
1.1142    raeburn  10172: 
1.472     raeburn  10173: 1. domain
1.536     raeburn  10174: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10175:    status types (e.g., faculty, staff, student etc.)
                   10176:    which apply to the user for whom the default is being retrieved.
                   10177:    If the institutional status string in undefined, the domain
1.1134    raeburn  10178:    default quota will be returned.
                   10179: 3.  quota name - portfolio, author, or course
                   10180:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10181: 
                   10182: Returns:
1.1142    raeburn  10183: 
1.1163    raeburn  10184: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10185: 2. (Optional) institutional type which determined the value of the
                   10186:    default quota.
1.472     raeburn  10187: 
                   10188: If a value has been stored in the domain's configuration db,
                   10189: it will return that, otherwise it returns 20 (for backwards 
                   10190: compatibility with domains which have not set up a configuration
1.1163    raeburn  10191: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10192: 
1.536     raeburn  10193: If the user's status includes multiple types (e.g., staff and student),
                   10194: the largest default quota which applies to the user determines the
                   10195: default quota returned.
                   10196: 
1.472     raeburn  10197: =cut
                   10198: 
                   10199: ###############################################
                   10200: 
                   10201: 
                   10202: sub default_quota {
1.1134    raeburn  10203:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10204:     my ($defquota,$settingstatus);
                   10205:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10206:                                             ['quotas'],$udom);
1.1134    raeburn  10207:     my $key = 'defaultquota';
                   10208:     if ($quotaname eq 'author') {
                   10209:         $key = 'authorquota';
                   10210:     }
1.622     raeburn  10211:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10212:         if ($inststatus ne '') {
1.765     raeburn  10213:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10214:             foreach my $item (@statuses) {
1.1134    raeburn  10215:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10216:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10217:                         if ($defquota eq '') {
1.1134    raeburn  10218:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10219:                             $settingstatus = $item;
1.1134    raeburn  10220:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10221:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10222:                             $settingstatus = $item;
                   10223:                         }
                   10224:                     }
1.1134    raeburn  10225:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10226:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10227:                         if ($defquota eq '') {
                   10228:                             $defquota = $quotahash{'quotas'}{$item};
                   10229:                             $settingstatus = $item;
                   10230:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10231:                             $defquota = $quotahash{'quotas'}{$item};
                   10232:                             $settingstatus = $item;
                   10233:                         }
1.536     raeburn  10234:                     }
                   10235:                 }
                   10236:             }
                   10237:         }
                   10238:         if ($defquota eq '') {
1.1134    raeburn  10239:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10240:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10241:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10242:                 $defquota = $quotahash{'quotas'}{'default'};
                   10243:             }
1.536     raeburn  10244:             $settingstatus = 'default';
1.1139    raeburn  10245:             if ($defquota eq '') {
                   10246:                 if ($quotaname eq 'author') {
                   10247:                     $defquota = 500;
                   10248:                 }
                   10249:             }
1.536     raeburn  10250:         }
                   10251:     } else {
                   10252:         $settingstatus = 'default';
1.1134    raeburn  10253:         if ($quotaname eq 'author') {
                   10254:             $defquota = 500;
                   10255:         } else {
                   10256:             $defquota = 20;
                   10257:         }
1.536     raeburn  10258:     }
                   10259:     if (wantarray) {
                   10260:         return ($defquota,$settingstatus);
1.472     raeburn  10261:     } else {
1.536     raeburn  10262:         return $defquota;
1.472     raeburn  10263:     }
                   10264: }
                   10265: 
1.1135    raeburn  10266: ###############################################
                   10267: 
                   10268: =pod
                   10269: 
1.1136    raeburn  10270: =item * &excess_filesize_warning()
1.1135    raeburn  10271: 
                   10272: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  10273: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  10274: space to be exceeded.
1.1136    raeburn  10275: 
                   10276: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  10277: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  10278: 
1.1165    raeburn  10279: Inputs: 7 
1.1136    raeburn  10280: 1. username or coursenum
1.1135    raeburn  10281: 2. domain
1.1136    raeburn  10282: 3. context ('author' or 'course')
1.1135    raeburn  10283: 4. filename of file for which action is being requested
                   10284: 5. filesize (kB) of file
                   10285: 6. action being taken: copy or upload.
1.1237    raeburn  10286: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  10287: 
                   10288: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  10289:          otherwise return null.
                   10290: 
                   10291: =back
1.1135    raeburn  10292: 
                   10293: =cut
                   10294: 
1.1136    raeburn  10295: sub excess_filesize_warning {
1.1165    raeburn  10296:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10297:     my $current_disk_usage = 0;
1.1165    raeburn  10298:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10299:     if ($context eq 'author') {
                   10300:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10301:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10302:     } else {
                   10303:         foreach my $subdir ('docs','supplemental') {
                   10304:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10305:         }
                   10306:     }
1.1135    raeburn  10307:     $disk_quota = int($disk_quota * 1000);
                   10308:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   10309:         return '<p class="LC_warning">'.
1.1135    raeburn  10310:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   10311:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10312:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  10313:                             $disk_quota,$current_disk_usage).
                   10314:                '</p>';
                   10315:     }
                   10316:     return;
                   10317: }
                   10318: 
                   10319: ###############################################
                   10320: 
                   10321: 
1.1136    raeburn  10322: 
                   10323: 
1.384     raeburn  10324: sub get_secgrprole_info {
                   10325:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10326:     my %sections_count = &get_sections($cdom,$cnum);
                   10327:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10328:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10329:     my @groups = sort(keys(%curr_groups));
                   10330:     my $allroles = [];
                   10331:     my $rolehash;
                   10332:     my $accesshash = {
                   10333:                      active => 'Currently has access',
                   10334:                      future => 'Will have future access',
                   10335:                      previous => 'Previously had access',
                   10336:                   };
                   10337:     if ($needroles) {
                   10338:         $rolehash = {'all' => 'all'};
1.385     albertel 10339:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10340: 	if (&Apache::lonnet::error(%user_roles)) {
                   10341: 	    undef(%user_roles);
                   10342: 	}
                   10343:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10344:             my ($role)=split(/\:/,$item,2);
                   10345:             if ($role eq 'cr') { next; }
                   10346:             if ($role =~ /^cr/) {
                   10347:                 $$rolehash{$role} = (split('/',$role))[3];
                   10348:             } else {
                   10349:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10350:             }
                   10351:         }
                   10352:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10353:             push(@{$allroles},$key);
                   10354:         }
                   10355:         push (@{$allroles},'st');
                   10356:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10357:     }
                   10358:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10359: }
                   10360: 
1.555     raeburn  10361: sub user_picker {
1.1279    raeburn  10362:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10363:     my $currdom = $dom;
1.1253    raeburn  10364:     my @alldoms = &Apache::lonnet::all_domains();
                   10365:     if (@alldoms == 1) {
                   10366:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10367:                                                ['directorysrch'],$alldoms[0]);
                   10368:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10369:         my $showdom = $domdesc;
                   10370:         if ($showdom eq '') {
                   10371:             $showdom = $dom;
                   10372:         }
                   10373:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10374:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10375:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10376:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10377:             }
                   10378:         }
                   10379:     }
1.555     raeburn  10380:     my %curr_selected = (
                   10381:                         srchin => 'dom',
1.580     raeburn  10382:                         srchby => 'lastname',
1.555     raeburn  10383:                       );
                   10384:     my $srchterm;
1.625     raeburn  10385:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10386:         if ($srch->{'srchby'} ne '') {
                   10387:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10388:         }
                   10389:         if ($srch->{'srchin'} ne '') {
                   10390:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10391:         }
                   10392:         if ($srch->{'srchtype'} ne '') {
                   10393:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10394:         }
                   10395:         if ($srch->{'srchdomain'} ne '') {
                   10396:             $currdom = $srch->{'srchdomain'};
                   10397:         }
                   10398:         $srchterm = $srch->{'srchterm'};
                   10399:     }
1.1222    damieng  10400:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10401:                     'usr'       => 'Search criteria',
1.563     raeburn  10402:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10403:                     'uname'     => 'username',
                   10404:                     'lastname'  => 'last name',
1.555     raeburn  10405:                     'lastfirst' => 'last name, first name',
1.558     albertel 10406:                     'crs'       => 'in this course',
1.576     raeburn  10407:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10408:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10409:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10410:                     'exact'     => 'is',
                   10411:                     'contains'  => 'contains',
1.569     raeburn  10412:                     'begins'    => 'begins with',
1.1222    damieng  10413:                                        );
                   10414:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10415:                     'youm'      => "You must include some text to search for.",
                   10416:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10417:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10418:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10419:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10420:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10421:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10422:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10423:                                        );
1.1222    damieng  10424:     &html_escape(\%html_lt);
                   10425:     &js_escape(\%js_lt);
1.1255    raeburn  10426:     my $domform;
1.1277    raeburn  10427:     my $allow_blank = 1;
1.1255    raeburn  10428:     if ($fixeddom) {
1.1277    raeburn  10429:         $allow_blank = 0;
                   10430:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  10431:     } else {
1.1287    raeburn  10432:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  10433:         my ($trusted,$untrusted);
1.1287    raeburn  10434:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  10435:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  10436:         } elsif ($context eq 'author') {
1.1288    raeburn  10437:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  10438:         } elsif ($context eq 'domain') {
1.1288    raeburn  10439:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  10440:         }
1.1288    raeburn  10441:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  10442:     }
1.563     raeburn  10443:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10444: 
                   10445:     my @srchins = ('crs','dom','alc','instd');
                   10446: 
                   10447:     foreach my $option (@srchins) {
                   10448:         # FIXME 'alc' option unavailable until 
                   10449:         #       loncreateuser::print_user_query_page()
                   10450:         #       has been completed.
                   10451:         next if ($option eq 'alc');
1.880     raeburn  10452:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10453:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  10454:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10455:         if ($curr_selected{'srchin'} eq $option) {
                   10456:             $srchinsel .= ' 
1.1222    damieng  10457:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10458:         } else {
                   10459:             $srchinsel .= '
1.1222    damieng  10460:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10461:         }
1.555     raeburn  10462:     }
1.563     raeburn  10463:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10464: 
                   10465:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10466:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10467:         if ($curr_selected{'srchby'} eq $option) {
                   10468:             $srchbysel .= '
1.1222    damieng  10469:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10470:         } else {
                   10471:             $srchbysel .= '
1.1222    damieng  10472:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10473:          }
                   10474:     }
                   10475:     $srchbysel .= "\n  </select>\n";
                   10476: 
                   10477:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10478:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10479:         if ($curr_selected{'srchtype'} eq $option) {
                   10480:             $srchtypesel .= '
1.1222    damieng  10481:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10482:         } else {
                   10483:             $srchtypesel .= '
1.1222    damieng  10484:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10485:         }
                   10486:     }
                   10487:     $srchtypesel .= "\n  </select>\n";
                   10488: 
1.558     albertel 10489:     my ($newuserscript,$new_user_create);
1.994     raeburn  10490:     my $context_dom = $env{'request.role.domain'};
                   10491:     if ($context eq 'requestcrs') {
                   10492:         if ($env{'form.coursedom'} ne '') { 
                   10493:             $context_dom = $env{'form.coursedom'};
                   10494:         }
                   10495:     }
1.556     raeburn  10496:     if ($forcenewuser) {
1.576     raeburn  10497:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10498:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10499:                 if ($cancreate) {
                   10500:                     $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>';
                   10501:                 } else {
1.799     bisitz   10502:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10503:                     my %usertypetext = (
                   10504:                         official   => 'institutional',
                   10505:                         unofficial => 'non-institutional',
                   10506:                     );
1.799     bisitz   10507:                     $new_user_create = '<p class="LC_warning">'
                   10508:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10509:                                       .' '
                   10510:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10511:                                           ,'<a href="'.$helplink.'">','</a>')
                   10512:                                       .'</p><br />';
1.627     raeburn  10513:                 }
1.576     raeburn  10514:             }
                   10515:         }
                   10516: 
1.556     raeburn  10517:         $newuserscript = <<"ENDSCRIPT";
                   10518: 
1.570     raeburn  10519: function setSearch(createnew,callingForm) {
1.556     raeburn  10520:     if (createnew == 1) {
1.570     raeburn  10521:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10522:             if (callingForm.srchby.options[i].value == 'uname') {
                   10523:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10524:             }
                   10525:         }
1.570     raeburn  10526:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10527:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10528: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10529:             }
                   10530:         }
1.570     raeburn  10531:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10532:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10533:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10534:             }
                   10535:         }
1.570     raeburn  10536:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10537:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10538:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10539:             }
                   10540:         }
                   10541:     }
                   10542: }
                   10543: ENDSCRIPT
1.558     albertel 10544: 
1.556     raeburn  10545:     }
                   10546: 
1.555     raeburn  10547:     my $output = <<"END_BLOCK";
1.556     raeburn  10548: <script type="text/javascript">
1.824     bisitz   10549: // <![CDATA[
1.570     raeburn  10550: function validateEntry(callingForm) {
1.558     albertel 10551: 
1.556     raeburn  10552:     var checkok = 1;
1.558     albertel 10553:     var srchin;
1.570     raeburn  10554:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10555: 	if ( callingForm.srchin[i].checked ) {
                   10556: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10557: 	}
                   10558:     }
                   10559: 
1.570     raeburn  10560:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10561:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10562:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10563:     var srchterm =  callingForm.srchterm.value;
                   10564:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10565:     var msg = "";
                   10566: 
                   10567:     if (srchterm == "") {
                   10568:         checkok = 0;
1.1222    damieng  10569:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10570:     }
                   10571: 
1.569     raeburn  10572:     if (srchtype== 'begins') {
                   10573:         if (srchterm.length < 2) {
                   10574:             checkok = 0;
1.1222    damieng  10575:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10576:         }
                   10577:     }
                   10578: 
1.556     raeburn  10579:     if (srchtype== 'contains') {
                   10580:         if (srchterm.length < 3) {
                   10581:             checkok = 0;
1.1222    damieng  10582:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10583:         }
                   10584:     }
                   10585:     if (srchin == 'instd') {
                   10586:         if (srchdomain == '') {
                   10587:             checkok = 0;
1.1222    damieng  10588:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10589:         }
                   10590:     }
                   10591:     if (srchin == 'dom') {
                   10592:         if (srchdomain == '') {
                   10593:             checkok = 0;
1.1222    damieng  10594:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10595:         }
                   10596:     }
                   10597:     if (srchby == 'lastfirst') {
                   10598:         if (srchterm.indexOf(",") == -1) {
                   10599:             checkok = 0;
1.1222    damieng  10600:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10601:         }
                   10602:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10603:             checkok = 0;
1.1222    damieng  10604:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10605:         }
                   10606:     }
                   10607:     if (checkok == 0) {
1.1222    damieng  10608:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10609:         return;
                   10610:     }
                   10611:     if (checkok == 1) {
1.570     raeburn  10612:         callingForm.submit();
1.556     raeburn  10613:     }
                   10614: }
                   10615: 
                   10616: $newuserscript
                   10617: 
1.824     bisitz   10618: // ]]>
1.556     raeburn  10619: </script>
1.558     albertel 10620: 
                   10621: $new_user_create
                   10622: 
1.555     raeburn  10623: END_BLOCK
1.558     albertel 10624: 
1.876     raeburn  10625:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  10626:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10627:                $domform.
                   10628:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  10629:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10630:                $srchbysel.
                   10631:                $srchtypesel. 
                   10632:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10633:                $srchinsel.
                   10634:                &Apache::lonhtmlcommon::row_closure(1). 
                   10635:                &Apache::lonhtmlcommon::end_pick_box().
                   10636:                '<br />';
1.1253    raeburn  10637:     return ($output,1);
1.555     raeburn  10638: }
                   10639: 
1.612     raeburn  10640: sub user_rule_check {
1.615     raeburn  10641:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  10642:     my ($response,%inst_response);
1.612     raeburn  10643:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  10644:         if (keys(%{$usershash}) > 1) {
                   10645:             my (%by_username,%by_id,%userdoms);
                   10646:             my $checkid; 
                   10647:             if (ref($checks) eq 'HASH') {
                   10648:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10649:                     $checkid = 1;
                   10650:                 }
                   10651:             }
                   10652:             foreach my $user (keys(%{$usershash})) {
                   10653:                 my ($uname,$udom) = split(/:/,$user);
                   10654:                 if ($checkid) {
                   10655:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10656:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  10657:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  10658:                             $userdoms{$udom} = 1;
1.1227    raeburn  10659:                             if (ref($inst_results) eq 'HASH') {
                   10660:                                 $inst_results->{$uname.':'.$udom} = {};
                   10661:                             }
1.1226    raeburn  10662:                         }
                   10663:                     }
                   10664:                 } else {
                   10665:                     $by_username{$udom}{$uname} = 1;
                   10666:                     $userdoms{$udom} = 1;
1.1227    raeburn  10667:                     if (ref($inst_results) eq 'HASH') {
                   10668:                         $inst_results->{$uname.':'.$udom} = {};
                   10669:                     }
1.1226    raeburn  10670:                 }
                   10671:             }
                   10672:             foreach my $udom (keys(%userdoms)) {
                   10673:                 if (!$got_rules->{$udom}) {
                   10674:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10675:                                                              ['usercreation'],$udom);
                   10676:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10677:                         foreach my $item ('username','id') {
                   10678:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  10679:                                 $$curr_rules{$udom}{$item} =
                   10680:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  10681:                             }
                   10682:                         }
                   10683:                     }
                   10684:                     $got_rules->{$udom} = 1;
                   10685:                 }
1.612     raeburn  10686:             }
1.1226    raeburn  10687:             if ($checkid) {
                   10688:                 foreach my $udom (keys(%by_id)) {
                   10689:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10690:                     if ($outcome eq 'ok') {
1.1227    raeburn  10691:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10692:                             my $uname = $by_id{$udom}{$id};
                   10693:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10694:                         }
1.1226    raeburn  10695:                         if (ref($results) eq 'HASH') {
                   10696:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  10697:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10698:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10699:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10700:                                 }
1.1226    raeburn  10701:                             }
                   10702:                         }
                   10703:                     }
1.612     raeburn  10704:                 }
1.615     raeburn  10705:             } else {
1.1226    raeburn  10706:                 foreach my $udom (keys(%by_username)) {
                   10707:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10708:                     if ($outcome eq 'ok') {
1.1227    raeburn  10709:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10710:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10711:                         }
1.1226    raeburn  10712:                         if (ref($results) eq 'HASH') {
                   10713:                             foreach my $uname (keys(%{$results})) {
                   10714:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10715:                             }
                   10716:                         }
                   10717:                     }
                   10718:                 }
1.612     raeburn  10719:             }
1.1226    raeburn  10720:         } elsif (keys(%{$usershash}) == 1) {
                   10721:             my $user = (keys(%{$usershash}))[0];
                   10722:             my ($uname,$udom) = split(/:/,$user);
                   10723:             if (($udom ne '') && ($uname ne '')) {
                   10724:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10725:                     if (ref($checks) eq 'HASH') {
                   10726:                         if (defined($checks->{'username'})) {
                   10727:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   10728:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10729:                         } elsif (defined($checks->{'id'})) {
                   10730:                             if ($usershash->{$user}->{'id'} ne '') {
                   10731:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10732:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10733:                                                                   $usershash->{$user}->{'id'});
                   10734:                             } else {
                   10735:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10736:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10737:                             }
1.585     raeburn  10738:                         }
1.1226    raeburn  10739:                     } else {
                   10740:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10741:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10742:                        return;
                   10743:                     }
                   10744:                     if (!$got_rules->{$udom}) {
                   10745:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10746:                                                                  ['usercreation'],$udom);
                   10747:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10748:                             foreach my $item ('username','id') {
                   10749:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10750:                                    $$curr_rules{$udom}{$item} = 
                   10751:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10752:                                 }
                   10753:                             }
                   10754:                         }
                   10755:                         $got_rules->{$udom} = 1;
1.585     raeburn  10756:                     }
                   10757:                 }
1.1226    raeburn  10758:             } else {
                   10759:                 return;
                   10760:             }
                   10761:         } else {
                   10762:             return;
                   10763:         }
                   10764:         foreach my $user (keys(%{$usershash})) {
                   10765:             my ($uname,$udom) = split(/:/,$user);
                   10766:             next if (($udom eq '') || ($uname eq ''));
                   10767:             my $id;
1.1227    raeburn  10768:             if (ref($inst_results) eq 'HASH') {
                   10769:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10770:                     $id = $inst_results->{$user}->{'id'};
                   10771:                 }
                   10772:             }
                   10773:             if ($id eq '') { 
                   10774:                 if (ref($usershash->{$user})) {
                   10775:                     $id = $usershash->{$user}->{'id'};
                   10776:                 }
1.585     raeburn  10777:             }
1.612     raeburn  10778:             foreach my $item (keys(%{$checks})) {
                   10779:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10780:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10781:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  10782:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10783:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10784:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10785:                                 if ($rule_check{$rule}) {
                   10786:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  10787:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10788:                                         if (ref($inst_results) eq 'HASH') {
                   10789:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10790:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10791:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  10792:                                                 } elsif ($item eq 'id') {
                   10793:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10794:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10795:                                                     }
1.615     raeburn  10796:                                                 }
1.612     raeburn  10797:                                             }
                   10798:                                         }
1.615     raeburn  10799:                                     }
                   10800:                                     last;
1.585     raeburn  10801:                                 }
                   10802:                             }
                   10803:                         }
                   10804:                     }
                   10805:                 }
                   10806:             }
                   10807:         }
                   10808:     }
1.612     raeburn  10809:     return;
                   10810: }
                   10811: 
                   10812: sub user_rule_formats {
                   10813:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10814:     my %text = ( 
                   10815:                  'username' => 'Usernames',
                   10816:                  'id'       => 'IDs',
                   10817:                );
                   10818:     my $output;
                   10819:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10820:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10821:         if (@{$ruleorder} > 0) {
1.1102    raeburn  10822:             $output = '<br />'.
                   10823:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10824:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10825:                       ' <ul>';
1.612     raeburn  10826:             foreach my $rule (@{$ruleorder}) {
                   10827:                 if (ref($curr_rules) eq 'ARRAY') {
                   10828:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10829:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10830:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10831:                                         $rules->{$rule}{'desc'}.'</li>';
                   10832:                         }
                   10833:                     }
                   10834:                 }
                   10835:             }
                   10836:             $output .= '</ul>';
                   10837:         }
                   10838:     }
                   10839:     return $output;
                   10840: }
                   10841: 
                   10842: sub instrule_disallow_msg {
1.615     raeburn  10843:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10844:     my $response;
                   10845:     my %text = (
                   10846:                   item   => 'username',
                   10847:                   items  => 'usernames',
                   10848:                   match  => 'matches',
                   10849:                   do     => 'does',
                   10850:                   action => 'a username',
                   10851:                   one    => 'one',
                   10852:                );
                   10853:     if ($count > 1) {
                   10854:         $text{'item'} = 'usernames';
                   10855:         $text{'match'} ='match';
                   10856:         $text{'do'} = 'do';
                   10857:         $text{'action'} = 'usernames',
                   10858:         $text{'one'} = 'ones';
                   10859:     }
                   10860:     if ($checkitem eq 'id') {
                   10861:         $text{'items'} = 'IDs';
                   10862:         $text{'item'} = 'ID';
                   10863:         $text{'action'} = 'an ID';
1.615     raeburn  10864:         if ($count > 1) {
                   10865:             $text{'item'} = 'IDs';
                   10866:             $text{'action'} = 'IDs';
                   10867:         }
1.612     raeburn  10868:     }
1.674     bisitz   10869:     $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  10870:     if ($mode eq 'upload') {
                   10871:         if ($checkitem eq 'username') {
                   10872:             $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'}.");
                   10873:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10874:             $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  10875:         }
1.669     raeburn  10876:     } elsif ($mode eq 'selfcreate') {
                   10877:         if ($checkitem eq 'id') {
                   10878:             $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.");
                   10879:         }
1.615     raeburn  10880:     } else {
                   10881:         if ($checkitem eq 'username') {
                   10882:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10883:         } elsif ($checkitem eq 'id') {
                   10884:             $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.");
                   10885:         }
1.612     raeburn  10886:     }
                   10887:     return $response;
1.585     raeburn  10888: }
                   10889: 
1.624     raeburn  10890: sub personal_data_fieldtitles {
                   10891:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10892:                         id => 'Student/Employee ID',
                   10893:                         permanentemail => 'E-mail address',
                   10894:                         lastname => 'Last Name',
                   10895:                         firstname => 'First Name',
                   10896:                         middlename => 'Middle Name',
                   10897:                         generation => 'Generation',
                   10898:                         gen => 'Generation',
1.765     raeburn  10899:                         inststatus => 'Affiliation',
1.624     raeburn  10900:                    );
                   10901:     return %fieldtitles;
                   10902: }
                   10903: 
1.642     raeburn  10904: sub sorted_inst_types {
                   10905:     my ($dom) = @_;
1.1185    raeburn  10906:     my ($usertypes,$order);
                   10907:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10908:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10909:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10910:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10911:     } else {
                   10912:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10913:     }
1.642     raeburn  10914:     my $othertitle = &mt('All users');
                   10915:     if ($env{'request.course.id'}) {
1.668     raeburn  10916:         $othertitle  = &mt('Any users');
1.642     raeburn  10917:     }
                   10918:     my @types;
                   10919:     if (ref($order) eq 'ARRAY') {
                   10920:         @types = @{$order};
                   10921:     }
                   10922:     if (@types == 0) {
                   10923:         if (ref($usertypes) eq 'HASH') {
                   10924:             @types = sort(keys(%{$usertypes}));
                   10925:         }
                   10926:     }
                   10927:     if (keys(%{$usertypes}) > 0) {
                   10928:         $othertitle = &mt('Other users');
                   10929:     }
                   10930:     return ($othertitle,$usertypes,\@types);
                   10931: }
                   10932: 
1.645     raeburn  10933: sub get_institutional_codes {
                   10934:     my ($settings,$allcourses,$LC_code) = @_;
                   10935: # Get complete list of course sections to update
                   10936:     my @currsections = ();
                   10937:     my @currxlists = ();
                   10938:     my $coursecode = $$settings{'internal.coursecode'};
                   10939: 
                   10940:     if ($$settings{'internal.sectionnums'} ne '') {
                   10941:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10942:     }
                   10943: 
                   10944:     if ($$settings{'internal.crosslistings'} ne '') {
                   10945:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10946:     }
                   10947: 
                   10948:     if (@currxlists > 0) {
                   10949:         foreach (@currxlists) {
                   10950:             if (m/^([^:]+):(\w*)$/) {
                   10951:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  10952:                     push(@{$allcourses},$1);
1.645     raeburn  10953:                     $$LC_code{$1} = $2;
                   10954:                 }
                   10955:             }
                   10956:         }
                   10957:     }
                   10958:  
                   10959:     if (@currsections > 0) {
                   10960:         foreach (@currsections) {
                   10961:             if (m/^(\w+):(\w*)$/) {
                   10962:                 my $sec = $coursecode.$1;
                   10963:                 my $lc_sec = $2;
                   10964:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1263    raeburn  10965:                     push(@{$allcourses},$sec);
1.645     raeburn  10966:                     $$LC_code{$sec} = $lc_sec;
                   10967:                 }
                   10968:             }
                   10969:         }
                   10970:     }
                   10971:     return;
                   10972: }
                   10973: 
1.971     raeburn  10974: sub get_standard_codeitems {
                   10975:     return ('Year','Semester','Department','Number','Section');
                   10976: }
                   10977: 
1.112     bowersj2 10978: =pod
                   10979: 
1.780     raeburn  10980: =head1 Slot Helpers
                   10981: 
                   10982: =over 4
                   10983: 
                   10984: =item * sorted_slots()
                   10985: 
1.1040    raeburn  10986: Sorts an array of slot names in order of an optional sort key,
                   10987: default sort is by slot start time (earliest first). 
1.780     raeburn  10988: 
                   10989: Inputs:
                   10990: 
                   10991: =over 4
                   10992: 
                   10993: slotsarr  - Reference to array of unsorted slot names.
                   10994: 
                   10995: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10996: 
1.1040    raeburn  10997: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10998: 
1.549     albertel 10999: =back
                   11000: 
1.780     raeburn  11001: Returns:
                   11002: 
                   11003: =over 4
                   11004: 
1.1040    raeburn  11005: sorted   - An array of slot names sorted by a specified sort key 
                   11006:            (default sort key is start time of the slot).
1.780     raeburn  11007: 
                   11008: =back
                   11009: 
                   11010: =cut
                   11011: 
                   11012: 
                   11013: sub sorted_slots {
1.1040    raeburn  11014:     my ($slotsarr,$slots,$sortkey) = @_;
                   11015:     if ($sortkey eq '') {
                   11016:         $sortkey = 'starttime';
                   11017:     }
1.780     raeburn  11018:     my @sorted;
                   11019:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11020:         @sorted =
                   11021:             sort {
                   11022:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11023:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11024:                      }
                   11025:                      if (ref($slots->{$a})) { return -1;}
                   11026:                      if (ref($slots->{$b})) { return 1;}
                   11027:                      return 0;
                   11028:                  } @{$slotsarr};
                   11029:     }
                   11030:     return @sorted;
                   11031: }
                   11032: 
1.1040    raeburn  11033: =pod
                   11034: 
                   11035: =item * get_future_slots()
                   11036: 
                   11037: Inputs:
                   11038: 
                   11039: =over 4
                   11040: 
                   11041: cnum - course number
                   11042: 
                   11043: cdom - course domain
                   11044: 
                   11045: now - current UNIX time
                   11046: 
                   11047: symb - optional symb
                   11048: 
                   11049: =back
                   11050: 
                   11051: Returns:
                   11052: 
                   11053: =over 4
                   11054: 
                   11055: sorted_reservable - ref to array of student_schedulable slots currently 
                   11056:                     reservable, ordered by end date of reservation period.
                   11057: 
                   11058: reservable_now - ref to hash of student_schedulable slots currently
                   11059:                  reservable.
                   11060: 
                   11061:     Keys in inner hash are:
                   11062:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11063:     (b) endreserve: end date of reservation period.
                   11064:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11065:         selected.
1.1040    raeburn  11066: 
                   11067: sorted_future - ref to array of student_schedulable slots reservable in
                   11068:                 the future, ordered by start date of reservation period.
                   11069: 
                   11070: future_reservable - ref to hash of student_schedulable slots reservable
                   11071:                     in the future.
                   11072: 
                   11073:     Keys in inner hash are:
                   11074:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11075:     (b) startreserve: start date of reservation period.
                   11076:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11077:         selected.
1.1040    raeburn  11078: 
                   11079: =back
                   11080: 
                   11081: =cut
                   11082: 
                   11083: sub get_future_slots {
                   11084:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  11085:     my $map;
                   11086:     if ($symb) {
                   11087:         ($map) = &Apache::lonnet::decode_symb($symb);
                   11088:     }
1.1040    raeburn  11089:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11090:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11091:     foreach my $slot (keys(%slots)) {
                   11092:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11093:         if ($symb) {
1.1229    raeburn  11094:             if ($slots{$slot}->{'symb'} ne '') {
                   11095:                 my $canuse;
                   11096:                 my %oksymbs;
                   11097:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   11098:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   11099:                 if ($oksymbs{$symb}) {
                   11100:                     $canuse = 1;
                   11101:                 } else {
                   11102:                     foreach my $item (@slotsymbs) {
                   11103:                         if ($item =~ /\.(page|sequence)$/) {
                   11104:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   11105:                             if (($map ne '') && ($map eq $sloturl)) {
                   11106:                                 $canuse = 1;
                   11107:                                 last;
                   11108:                             }
                   11109:                         }
                   11110:                     }
                   11111:                 }
                   11112:                 next unless ($canuse);
                   11113:             }
1.1040    raeburn  11114:         }
                   11115:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11116:             ($slots{$slot}->{'endtime'} > $now)) {
                   11117:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11118:                 my $userallowed = 0;
                   11119:                 if ($slots{$slot}->{'allowedsections'}) {
                   11120:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11121:                     if (!defined($env{'request.role.sec'})
                   11122:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11123:                         $userallowed=1;
                   11124:                     } else {
                   11125:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11126:                             $userallowed=1;
                   11127:                         }
                   11128:                     }
                   11129:                     unless ($userallowed) {
                   11130:                         if (defined($env{'request.course.groups'})) {
                   11131:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11132:                             foreach my $group (@groups) {
                   11133:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11134:                                     $userallowed=1;
                   11135:                                     last;
                   11136:                                 }
                   11137:                             }
                   11138:                         }
                   11139:                     }
                   11140:                 }
                   11141:                 if ($slots{$slot}->{'allowedusers'}) {
                   11142:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11143:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11144:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11145:                         $userallowed = 1;
                   11146:                     }
                   11147:                 }
                   11148:                 next unless($userallowed);
                   11149:             }
                   11150:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11151:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11152:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  11153:             my $uniqueperiod;
                   11154:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11155:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11156:             }
1.1040    raeburn  11157:             if (($startreserve < $now) &&
                   11158:                 (!$endreserve || $endreserve > $now)) {
                   11159:                 my $lastres = $endreserve;
                   11160:                 if (!$lastres) {
                   11161:                     $lastres = $slots{$slot}->{'starttime'};
                   11162:                 }
                   11163:                 $reservable_now{$slot} = {
                   11164:                                            symb       => $symb,
1.1250    raeburn  11165:                                            endreserve => $lastres,
                   11166:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  11167:                                          };
                   11168:             } elsif (($startreserve > $now) &&
                   11169:                      (!$endreserve || $endreserve > $startreserve)) {
                   11170:                 $future_reservable{$slot} = {
                   11171:                                               symb         => $symb,
1.1250    raeburn  11172:                                               startreserve => $startreserve,
                   11173:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11174:                                             };
                   11175:             }
                   11176:         }
                   11177:     }
                   11178:     my @unsorted_reservable = keys(%reservable_now);
                   11179:     if (@unsorted_reservable > 0) {
                   11180:         @sorted_reservable = 
                   11181:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11182:     }
                   11183:     my @unsorted_future = keys(%future_reservable);
                   11184:     if (@unsorted_future > 0) {
                   11185:         @sorted_future =
                   11186:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11187:     }
                   11188:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11189: }
1.780     raeburn  11190: 
                   11191: =pod
                   11192: 
1.1057    foxr     11193: =back
                   11194: 
1.549     albertel 11195: =head1 HTTP Helpers
                   11196: 
                   11197: =over 4
                   11198: 
1.648     raeburn  11199: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11200: 
1.258     albertel 11201: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11202: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11203: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11204: 
                   11205: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11206: $possible_names is an ref to an array of form element names.  As an example:
                   11207: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11208: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11209: 
                   11210: =cut
1.1       albertel 11211: 
1.6       albertel 11212: sub get_unprocessed_cgi {
1.25      albertel 11213:   my ($query,$possible_names)= @_;
1.26      matthew  11214:   # $Apache::lonxml::debug=1;
1.356     albertel 11215:   foreach my $pair (split(/&/,$query)) {
                   11216:     my ($name, $value) = split(/=/,$pair);
1.369     www      11217:     $name = &unescape($name);
1.25      albertel 11218:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11219:       $value =~ tr/+/ /;
                   11220:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11221:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11222:     }
1.16      harris41 11223:   }
1.6       albertel 11224: }
                   11225: 
1.112     bowersj2 11226: =pod
                   11227: 
1.648     raeburn  11228: =item * &cacheheader() 
1.112     bowersj2 11229: 
                   11230: returns cache-controlling header code
                   11231: 
                   11232: =cut
                   11233: 
1.7       albertel 11234: sub cacheheader {
1.258     albertel 11235:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11236:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11237:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11238:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11239:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11240:     return $output;
1.7       albertel 11241: }
                   11242: 
1.112     bowersj2 11243: =pod
                   11244: 
1.648     raeburn  11245: =item * &no_cache($r) 
1.112     bowersj2 11246: 
                   11247: specifies header code to not have cache
                   11248: 
                   11249: =cut
                   11250: 
1.9       albertel 11251: sub no_cache {
1.216     albertel 11252:     my ($r) = @_;
                   11253:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11254: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11255:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11256:     $r->no_cache(1);
                   11257:     $r->header_out("Expires" => $date);
                   11258:     $r->header_out("Pragma" => "no-cache");
1.123     www      11259: }
                   11260: 
                   11261: sub content_type {
1.181     albertel 11262:     my ($r,$type,$charset) = @_;
1.299     foxr     11263:     if ($r) {
                   11264: 	#  Note that printout.pl calls this with undef for $r.
                   11265: 	&no_cache($r);
                   11266:     }
1.258     albertel 11267:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11268:     unless ($charset) {
                   11269: 	$charset=&Apache::lonlocal::current_encoding;
                   11270:     }
                   11271:     if ($charset) { $type.='; charset='.$charset; }
                   11272:     if ($r) {
                   11273: 	$r->content_type($type);
                   11274:     } else {
                   11275: 	print("Content-type: $type\n\n");
                   11276:     }
1.9       albertel 11277: }
1.25      albertel 11278: 
1.112     bowersj2 11279: =pod
                   11280: 
1.648     raeburn  11281: =item * &add_to_env($name,$value) 
1.112     bowersj2 11282: 
1.258     albertel 11283: adds $name to the %env hash with value
1.112     bowersj2 11284: $value, if $name already exists, the entry is converted to an array
                   11285: reference and $value is added to the array.
                   11286: 
                   11287: =cut
                   11288: 
1.25      albertel 11289: sub add_to_env {
                   11290:   my ($name,$value)=@_;
1.258     albertel 11291:   if (defined($env{$name})) {
                   11292:     if (ref($env{$name})) {
1.25      albertel 11293:       #already have multiple values
1.258     albertel 11294:       push(@{ $env{$name} },$value);
1.25      albertel 11295:     } else {
                   11296:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11297:       my $first=$env{$name};
                   11298:       undef($env{$name});
                   11299:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11300:     }
                   11301:   } else {
1.258     albertel 11302:     $env{$name}=$value;
1.25      albertel 11303:   }
1.31      albertel 11304: }
1.149     albertel 11305: 
                   11306: =pod
                   11307: 
1.648     raeburn  11308: =item * &get_env_multiple($name) 
1.149     albertel 11309: 
1.258     albertel 11310: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11311: values may be defined and end up as an array ref.
                   11312: 
                   11313: returns an array of values
                   11314: 
                   11315: =cut
                   11316: 
                   11317: sub get_env_multiple {
                   11318:     my ($name) = @_;
                   11319:     my @values;
1.258     albertel 11320:     if (defined($env{$name})) {
1.149     albertel 11321:         # exists is it an array
1.258     albertel 11322:         if (ref($env{$name})) {
                   11323:             @values=@{ $env{$name} };
1.149     albertel 11324:         } else {
1.258     albertel 11325:             $values[0]=$env{$name};
1.149     albertel 11326:         }
                   11327:     }
                   11328:     return(@values);
                   11329: }
                   11330: 
1.1249    damieng  11331: # Looks at given dependencies, and returns something depending on the context.
                   11332: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   11333: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   11334: # For all other contexts, returns ($output, $counter, $numpathchg).
                   11335: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   11336: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
                   11337: # $numpathchg: integer with the number of cleaned up dependency paths.
                   11338: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   11339: # \%mapping: hash reference clean path -> original path for all dependencies.
                   11340: # @param {string} actionurl - The path to the handler, indicative of the context.
                   11341: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   11342: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   11343: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   11344: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
                   11345: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  11346: sub ask_for_embedded_content {
1.1249    damieng  11347:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  11348:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11349:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  11350:         %currsubfile,%unused,$rem);
1.1071    raeburn  11351:     my $counter = 0;
                   11352:     my $numnew = 0;
1.987     raeburn  11353:     my $numremref = 0;
                   11354:     my $numinvalid = 0;
                   11355:     my $numpathchg = 0;
                   11356:     my $numexisting = 0;
1.1071    raeburn  11357:     my $numunused = 0;
                   11358:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11359:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11360:     my $heading = &mt('Upload embedded files');
                   11361:     my $buttontext = &mt('Upload');
                   11362: 
1.1249    damieng  11363:     # fills these variables based on the context:
                   11364:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11365:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11366:     if ($env{'request.course.id'}) {
1.1123    raeburn  11367:         if ($actionurl eq '/adm/dependencies') {
                   11368:             $navmap = Apache::lonnavmaps::navmap->new();
                   11369:         }
                   11370:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11371:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11372:     }
1.1123    raeburn  11373:     if (($actionurl eq '/adm/portfolio') || 
                   11374:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11375:         my $current_path='/';
                   11376:         if ($env{'form.currentpath'}) {
                   11377:             $current_path = $env{'form.currentpath'};
                   11378:         }
                   11379:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  11380:             $udom = $cdom;
                   11381:             $uname = $cnum;
1.984     raeburn  11382:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11383:         } else {
                   11384:             $udom = $env{'user.domain'};
                   11385:             $uname = $env{'user.name'};
                   11386:             $url = '/userfiles/portfolio';
                   11387:         }
1.987     raeburn  11388:         $toplevel = $url.'/';
1.984     raeburn  11389:         $url .= $current_path;
                   11390:         $getpropath = 1;
1.987     raeburn  11391:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11392:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11393:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11394:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11395:         $toplevel = $url;
1.984     raeburn  11396:         if ($rest ne '') {
1.987     raeburn  11397:             $url .= $rest;
                   11398:         }
                   11399:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11400:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11401:             $url = $args->{'docs_url'};
                   11402:             $toplevel = $url;
1.1084    raeburn  11403:             if ($args->{'context'} eq 'paste') {
                   11404:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11405:                 ($path) = 
                   11406:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11407:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11408:                 $fileloc =~ s{^/}{};
                   11409:             }
1.1071    raeburn  11410:         }
1.1084    raeburn  11411:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  11412:         if ($env{'request.course.id'} ne '') {
                   11413:             if (ref($args) eq 'HASH') {
                   11414:                 $url = $args->{'docs_url'};
                   11415:                 $title = $args->{'docs_title'};
1.1126    raeburn  11416:                 $toplevel = $url; 
                   11417:                 unless ($toplevel =~ m{^/}) {
                   11418:                     $toplevel = "/$url";
                   11419:                 }
1.1085    raeburn  11420:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  11421:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11422:                     $path = $1;
                   11423:                 } else {
                   11424:                     ($path) =
                   11425:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11426:                 }
1.1195    raeburn  11427:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11428:                     $fileloc = $toplevel;
                   11429:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11430:                     my ($udom,$uname,$fname) =
                   11431:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11432:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11433:                 } else {
                   11434:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11435:                 }
1.1071    raeburn  11436:                 $fileloc =~ s{^/}{};
                   11437:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11438:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11439:             }
1.987     raeburn  11440:         }
1.1123    raeburn  11441:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11442:         $udom = $cdom;
                   11443:         $uname = $cnum;
                   11444:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11445:         $toplevel = $url;
                   11446:         $path = $url;
                   11447:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11448:         $fileloc =~ s{^/}{};
1.987     raeburn  11449:     }
1.1249    damieng  11450:     
                   11451:     # parses the dependency paths to get some info
                   11452:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   11453:     # $newfiles: hash URL -> 1 for new files or external URLs
                   11454:     # (will be completed later)
                   11455:     # $mapping:
                   11456:     #   for external URLs: external URL -> external URL
                   11457:     #   for relative paths: clean path -> original path
                   11458:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   11459:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  11460:     foreach my $file (keys(%{$allfiles})) {
                   11461:         my $embed_file;
                   11462:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11463:             $embed_file = $1;
                   11464:         } else {
                   11465:             $embed_file = $file;
                   11466:         }
1.1158    raeburn  11467:         my ($absolutepath,$cleaned_file);
                   11468:         if ($embed_file =~ m{^\w+://}) {
                   11469:             $cleaned_file = $embed_file;
1.1147    raeburn  11470:             $newfiles{$cleaned_file} = 1;
                   11471:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11472:         } else {
1.1158    raeburn  11473:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11474:             if ($embed_file =~ m{^/}) {
                   11475:                 $absolutepath = $embed_file;
                   11476:             }
1.1147    raeburn  11477:             if ($cleaned_file =~ m{/}) {
                   11478:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11479:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11480:                 my $item = $fname;
                   11481:                 if ($path ne '') {
                   11482:                     $item = $path.'/'.$fname;
                   11483:                     $subdependencies{$path}{$fname} = 1;
                   11484:                 } else {
                   11485:                     $dependencies{$item} = 1;
                   11486:                 }
                   11487:                 if ($absolutepath) {
                   11488:                     $mapping{$item} = $absolutepath;
                   11489:                 } else {
                   11490:                     $mapping{$item} = $embed_file;
                   11491:                 }
                   11492:             } else {
                   11493:                 $dependencies{$embed_file} = 1;
                   11494:                 if ($absolutepath) {
1.1147    raeburn  11495:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11496:                 } else {
1.1147    raeburn  11497:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11498:                 }
                   11499:             }
1.984     raeburn  11500:         }
                   11501:     }
1.1249    damieng  11502:     
                   11503:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   11504:     # and lists
                   11505:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   11506:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   11507:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   11508:     #                                    the path had to be cleaned up
                   11509:     # $existing: hash clean path -> 1 if the file exists
                   11510:     # $numexisting: number of keys in $existing
                   11511:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   11512:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   11513:     #                                      dependency subdirectories that are
                   11514:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  11515:     my $dirptr = 16384;
1.984     raeburn  11516:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11517:         $currsubfile{$path} = {};
1.1123    raeburn  11518:         if (($actionurl eq '/adm/portfolio') || 
                   11519:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11520:             my ($sublistref,$listerror) =
                   11521:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11522:             if (ref($sublistref) eq 'ARRAY') {
                   11523:                 foreach my $line (@{$sublistref}) {
                   11524:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11525:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11526:                 }
1.984     raeburn  11527:             }
1.987     raeburn  11528:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11529:             if (opendir(my $dir,$url.'/'.$path)) {
                   11530:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11531:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11532:             }
1.1084    raeburn  11533:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11534:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11535:                   ($args->{'context'} eq 'paste')) ||
                   11536:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11537:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  11538:                 my $dir;
                   11539:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11540:                     $dir = $fileloc;
                   11541:                 } else {
                   11542:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11543:                 }
1.1071    raeburn  11544:                 if ($dir ne '') {
                   11545:                     my ($sublistref,$listerror) =
                   11546:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11547:                     if (ref($sublistref) eq 'ARRAY') {
                   11548:                         foreach my $line (@{$sublistref}) {
                   11549:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11550:                                 undef,$mtime)=split(/\&/,$line,12);
                   11551:                             unless (($testdir&$dirptr) ||
                   11552:                                     ($file_name =~ /^\.\.?$/)) {
                   11553:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11554:                             }
                   11555:                         }
                   11556:                     }
                   11557:                 }
1.984     raeburn  11558:             }
                   11559:         }
                   11560:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11561:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11562:                 my $item = $path.'/'.$file;
                   11563:                 unless ($mapping{$item} eq $item) {
                   11564:                     $pathchanges{$item} = 1;
                   11565:                 }
                   11566:                 $existing{$item} = 1;
                   11567:                 $numexisting ++;
                   11568:             } else {
                   11569:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11570:             }
                   11571:         }
1.1071    raeburn  11572:         if ($actionurl eq '/adm/dependencies') {
                   11573:             foreach my $path (keys(%currsubfile)) {
                   11574:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11575:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11576:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  11577:                              next if (($rem ne '') &&
                   11578:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11579:                                        (ref($navmap) &&
                   11580:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11581:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11582:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11583:                              $unused{$path.'/'.$file} = 1; 
                   11584:                          }
                   11585:                     }
                   11586:                 }
                   11587:             }
                   11588:         }
1.984     raeburn  11589:     }
1.1249    damieng  11590:     
                   11591:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   11592:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  11593:     my %currfile;
1.1123    raeburn  11594:     if (($actionurl eq '/adm/portfolio') ||
                   11595:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11596:         my ($dirlistref,$listerror) =
                   11597:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11598:         if (ref($dirlistref) eq 'ARRAY') {
                   11599:             foreach my $line (@{$dirlistref}) {
                   11600:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11601:                 $currfile{$file_name} = 1;
                   11602:             }
1.984     raeburn  11603:         }
1.987     raeburn  11604:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11605:         if (opendir(my $dir,$url)) {
1.987     raeburn  11606:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11607:             map {$currfile{$_} = 1;} @dir_list;
                   11608:         }
1.1084    raeburn  11609:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11610:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11611:               ($args->{'context'} eq 'paste')) ||
                   11612:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11613:         if ($env{'request.course.id'} ne '') {
                   11614:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11615:             if ($dir ne '') {
                   11616:                 my ($dirlistref,$listerror) =
                   11617:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11618:                 if (ref($dirlistref) eq 'ARRAY') {
                   11619:                     foreach my $line (@{$dirlistref}) {
                   11620:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11621:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11622:                         unless (($testdir&$dirptr) ||
                   11623:                                 ($file_name =~ /^\.\.?$/)) {
                   11624:                             $currfile{$file_name} = [$size,$mtime];
                   11625:                         }
                   11626:                     }
                   11627:                 }
                   11628:             }
                   11629:         }
1.984     raeburn  11630:     }
1.1249    damieng  11631:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   11632:     # are not in subdirectories, using $currfile
1.984     raeburn  11633:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11634:         if (exists($currfile{$file})) {
1.987     raeburn  11635:             unless ($mapping{$file} eq $file) {
                   11636:                 $pathchanges{$file} = 1;
                   11637:             }
                   11638:             $existing{$file} = 1;
                   11639:             $numexisting ++;
                   11640:         } else {
1.984     raeburn  11641:             $newfiles{$file} = 1;
                   11642:         }
                   11643:     }
1.1071    raeburn  11644:     foreach my $file (keys(%currfile)) {
                   11645:         unless (($file eq $filename) ||
                   11646:                 ($file eq $filename.'.bak') ||
                   11647:                 ($dependencies{$file})) {
1.1085    raeburn  11648:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  11649:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11650:                     next if (($rem ne '') &&
                   11651:                              (($env{"httpref.$rem".$file} ne '') ||
                   11652:                               (ref($navmap) &&
                   11653:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11654:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11655:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11656:                 }
1.1085    raeburn  11657:             }
1.1071    raeburn  11658:             $unused{$file} = 1;
                   11659:         }
                   11660:     }
1.1249    damieng  11661:     
                   11662:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  11663:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11664:         ($args->{'context'} eq 'paste')) {
                   11665:         $counter = scalar(keys(%existing));
                   11666:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  11667:         return ($output,$counter,$numpathchg,\%existing);
                   11668:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   11669:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11670:         $counter = scalar(keys(%existing));
                   11671:         $numpathchg = scalar(keys(%pathchanges));
                   11672:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  11673:     }
1.1249    damieng  11674:     
                   11675:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   11676:     
                   11677:     # $upload_output: missing dependencies (with upload form)
                   11678:     # $modify_output: uploaded dependencies (in use)
                   11679:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  11680:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11681:         if ($actionurl eq '/adm/dependencies') {
                   11682:             next if ($embed_file =~ m{^\w+://});
                   11683:         }
1.660     raeburn  11684:         $upload_output .= &start_data_table_row().
1.1123    raeburn  11685:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11686:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11687:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  11688:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11689:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11690:         }
1.1123    raeburn  11691:         $upload_output .= '</td>';
1.1071    raeburn  11692:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  11693:             $upload_output.='<td align="right">'.
                   11694:                             '<span class="LC_info LC_fontsize_medium">'.
                   11695:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11696:             $numremref++;
1.660     raeburn  11697:         } elsif ($args->{'error_on_invalid_names'}
                   11698:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  11699:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11700:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11701:             $numinvalid++;
1.660     raeburn  11702:         } else {
1.1123    raeburn  11703:             $upload_output .= '<td>'.
                   11704:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11705:                                                      $embed_file,\%mapping,
1.1071    raeburn  11706:                                                      $allfiles,$codebase,'upload');
                   11707:             $counter ++;
                   11708:             $numnew ++;
1.987     raeburn  11709:         }
                   11710:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11711:     }
                   11712:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11713:         if ($actionurl eq '/adm/dependencies') {
                   11714:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11715:             $modify_output .= &start_data_table_row().
                   11716:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11717:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11718:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11719:                               '<td>'.$size.'</td>'.
                   11720:                               '<td>'.$mtime.'</td>'.
                   11721:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11722:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11723:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11724:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11725:                               &embedded_file_element('upload_embedded',$counter,
                   11726:                                                      $embed_file,\%mapping,
                   11727:                                                      $allfiles,$codebase,'modify').
                   11728:                               '</div></td>'.
                   11729:                               &end_data_table_row()."\n";
                   11730:             $counter ++;
                   11731:         } else {
                   11732:             $upload_output .= &start_data_table_row().
1.1123    raeburn  11733:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11734:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11735:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11736:                               &Apache::loncommon::end_data_table_row()."\n";
                   11737:         }
                   11738:     }
                   11739:     my $delidx = $counter;
                   11740:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11741:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11742:         $delete_output .= &start_data_table_row().
                   11743:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11744:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11745:                           '<td>'.$size.'</td>'.
                   11746:                           '<td>'.$mtime.'</td>'.
                   11747:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11748:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11749:                           &embedded_file_element('upload_embedded',$delidx,
                   11750:                                                  $oldfile,\%mapping,$allfiles,
                   11751:                                                  $codebase,'delete').'</td>'.
                   11752:                           &end_data_table_row()."\n"; 
                   11753:         $numunused ++;
                   11754:         $delidx ++;
1.987     raeburn  11755:     }
                   11756:     if ($upload_output) {
                   11757:         $upload_output = &start_data_table().
                   11758:                          $upload_output.
                   11759:                          &end_data_table()."\n";
                   11760:     }
1.1071    raeburn  11761:     if ($modify_output) {
                   11762:         $modify_output = &start_data_table().
                   11763:                          &start_data_table_header_row().
                   11764:                          '<th>'.&mt('File').'</th>'.
                   11765:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11766:                          '<th>'.&mt('Modified').'</th>'.
                   11767:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11768:                          &end_data_table_header_row().
                   11769:                          $modify_output.
                   11770:                          &end_data_table()."\n";
                   11771:     }
                   11772:     if ($delete_output) {
                   11773:         $delete_output = &start_data_table().
                   11774:                          &start_data_table_header_row().
                   11775:                          '<th>'.&mt('File').'</th>'.
                   11776:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11777:                          '<th>'.&mt('Modified').'</th>'.
                   11778:                          '<th>'.&mt('Delete?').'</th>'.
                   11779:                          &end_data_table_header_row().
                   11780:                          $delete_output.
                   11781:                          &end_data_table()."\n";
                   11782:     }
1.987     raeburn  11783:     my $applies = 0;
                   11784:     if ($numremref) {
                   11785:         $applies ++;
                   11786:     }
                   11787:     if ($numinvalid) {
                   11788:         $applies ++;
                   11789:     }
                   11790:     if ($numexisting) {
                   11791:         $applies ++;
                   11792:     }
1.1071    raeburn  11793:     if ($counter || $numunused) {
1.987     raeburn  11794:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11795:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11796:                   $state.'<h3>'.$heading.'</h3>'; 
                   11797:         if ($actionurl eq '/adm/dependencies') {
                   11798:             if ($numnew) {
                   11799:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11800:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11801:                            $upload_output.'<br />'."\n";
                   11802:             }
                   11803:             if ($numexisting) {
                   11804:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11805:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11806:                            $modify_output.'<br />'."\n";
                   11807:                            $buttontext = &mt('Save changes');
                   11808:             }
                   11809:             if ($numunused) {
                   11810:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11811:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11812:                            $delete_output.'<br />'."\n";
                   11813:                            $buttontext = &mt('Save changes');
                   11814:             }
                   11815:         } else {
                   11816:             $output .= $upload_output.'<br />'."\n";
                   11817:         }
                   11818:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11819:                    $counter.'" />'."\n";
                   11820:         if ($actionurl eq '/adm/dependencies') { 
                   11821:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11822:                        $numnew.'" />'."\n";
                   11823:         } elsif ($actionurl eq '') {
1.987     raeburn  11824:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11825:         }
                   11826:     } elsif ($applies) {
                   11827:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11828:         if ($applies > 1) {
                   11829:             $output .=  
1.1123    raeburn  11830:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11831:             if ($numremref) {
                   11832:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11833:             }
                   11834:             if ($numinvalid) {
                   11835:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11836:             }
                   11837:             if ($numexisting) {
                   11838:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11839:             }
                   11840:             $output .= '</ul><br />';
                   11841:         } elsif ($numremref) {
                   11842:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11843:         } elsif ($numinvalid) {
                   11844:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11845:         } elsif ($numexisting) {
                   11846:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11847:         }
                   11848:         $output .= $upload_output.'<br />';
                   11849:     }
                   11850:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11851:     $chgcount = $counter;
1.987     raeburn  11852:     if (keys(%pathchanges) > 0) {
                   11853:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11854:             if ($counter) {
1.987     raeburn  11855:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11856:                                                   $embed_file,\%mapping,
1.1071    raeburn  11857:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11858:             } else {
                   11859:                 $pathchange_output .= 
                   11860:                     &start_data_table_row().
                   11861:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11862:                     $chgcount.'" checked="checked" /></td>'.
                   11863:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11864:                     '<td>'.$embed_file.
                   11865:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11866:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11867:                     '</td>'.&end_data_table_row();
1.660     raeburn  11868:             }
1.987     raeburn  11869:             $numpathchg ++;
                   11870:             $chgcount ++;
1.660     raeburn  11871:         }
                   11872:     }
1.1127    raeburn  11873:     if (($counter) || ($numunused)) {
1.987     raeburn  11874:         if ($numpathchg) {
                   11875:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11876:                        $numpathchg.'" />'."\n";
                   11877:         }
                   11878:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11879:             ($actionurl eq '/adm/imsimport')) {
                   11880:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11881:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11882:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11883:         } elsif ($actionurl eq '/adm/dependencies') {
                   11884:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11885:         }
1.1123    raeburn  11886:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11887:     } elsif ($numpathchg) {
                   11888:         my %pathchange = ();
                   11889:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11890:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11891:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  11892:         }
1.987     raeburn  11893:     }
1.1071    raeburn  11894:     return ($output,$counter,$numpathchg);
1.987     raeburn  11895: }
                   11896: 
1.1147    raeburn  11897: =pod
                   11898: 
                   11899: =item * clean_path($name)
                   11900: 
                   11901: Performs clean-up of directories, subdirectories and filename in an
                   11902: embedded object, referenced in an HTML file which is being uploaded
                   11903: to a course or portfolio, where 
                   11904: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11905: checked.
                   11906: 
                   11907: Clean-up is similar to replacements in lonnet::clean_filename()
                   11908: except each / between sub-directory and next level is preserved.
                   11909: 
                   11910: =cut
                   11911: 
                   11912: sub clean_path {
                   11913:     my ($embed_file) = @_;
                   11914:     $embed_file =~s{^/+}{};
                   11915:     my @contents;
                   11916:     if ($embed_file =~ m{/}) {
                   11917:         @contents = split(/\//,$embed_file);
                   11918:     } else {
                   11919:         @contents = ($embed_file);
                   11920:     }
                   11921:     my $lastidx = scalar(@contents)-1;
                   11922:     for (my $i=0; $i<=$lastidx; $i++) { 
                   11923:         $contents[$i]=~s{\\}{/}g;
                   11924:         $contents[$i]=~s/\s+/\_/g;
                   11925:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11926:         if ($i == $lastidx) {
                   11927:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11928:         }
                   11929:     }
                   11930:     if ($lastidx > 0) {
                   11931:         return join('/',@contents);
                   11932:     } else {
                   11933:         return $contents[0];
                   11934:     }
                   11935: }
                   11936: 
1.987     raeburn  11937: sub embedded_file_element {
1.1071    raeburn  11938:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11939:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11940:                    (ref($codebase) eq 'HASH'));
                   11941:     my $output;
1.1071    raeburn  11942:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11943:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11944:     }
                   11945:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11946:                &escape($embed_file).'" />';
                   11947:     unless (($context eq 'upload_embedded') && 
                   11948:             ($mapping->{$embed_file} eq $embed_file)) {
                   11949:         $output .='
                   11950:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11951:     }
                   11952:     my $attrib;
                   11953:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11954:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11955:     }
                   11956:     $output .=
                   11957:         "\n\t\t".
                   11958:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11959:         $attrib.'" />';
                   11960:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11961:         $output .=
                   11962:             "\n\t\t".
                   11963:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11964:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11965:     }
1.987     raeburn  11966:     return $output;
1.660     raeburn  11967: }
                   11968: 
1.1071    raeburn  11969: sub get_dependency_details {
                   11970:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11971:     my ($size,$mtime,$showsize,$showmtime);
                   11972:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11973:         if ($embed_file =~ m{/}) {
                   11974:             my ($path,$fname) = split(/\//,$embed_file);
                   11975:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11976:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11977:             }
                   11978:         } else {
                   11979:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11980:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11981:             }
                   11982:         }
                   11983:         $showsize = $size/1024.0;
                   11984:         $showsize = sprintf("%.1f",$showsize);
                   11985:         if ($mtime > 0) {
                   11986:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11987:         }
                   11988:     }
                   11989:     return ($showsize,$showmtime);
                   11990: }
                   11991: 
                   11992: sub ask_embedded_js {
                   11993:     return <<"END";
                   11994: <script type="text/javascript"">
                   11995: // <![CDATA[
                   11996: function toggleBrowse(counter) {
                   11997:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11998:     var fileid = document.getElementById('embedded_item_'+counter);
                   11999:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12000:     if (chkboxid.checked == true) {
                   12001:         uploaddivid.style.display='block';
                   12002:     } else {
                   12003:         uploaddivid.style.display='none';
                   12004:         fileid.value = '';
                   12005:     }
                   12006: }
                   12007: // ]]>
                   12008: </script>
                   12009: 
                   12010: END
                   12011: }
                   12012: 
1.661     raeburn  12013: sub upload_embedded {
                   12014:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12015:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12016:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12017:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12018:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12019:         my $orig_uploaded_filename =
                   12020:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12021:         foreach my $type ('orig','ref','attrib','codebase') {
                   12022:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12023:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12024:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12025:             }
                   12026:         }
1.661     raeburn  12027:         my ($path,$fname) =
                   12028:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12029:         # no path, whole string is fname
                   12030:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12031:         $fname = &Apache::lonnet::clean_filename($fname);
                   12032:         # See if there is anything left
                   12033:         next if ($fname eq '');
                   12034: 
                   12035:         # Check if file already exists as a file or directory.
                   12036:         my ($state,$msg);
                   12037:         if ($context eq 'portfolio') {
                   12038:             my $port_path = $dirpath;
                   12039:             if ($group ne '') {
                   12040:                 $port_path = "groups/$group/$port_path";
                   12041:             }
1.987     raeburn  12042:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12043:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12044:                                               $dir_root,$port_path,$disk_quota,
                   12045:                                               $current_disk_usage,$uname,$udom);
                   12046:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12047:                 || $state eq 'file_locked') {
1.661     raeburn  12048:                 $output .= $msg;
                   12049:                 next;
                   12050:             }
                   12051:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12052:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12053:             if ($state eq 'exists') {
                   12054:                 $output .= $msg;
                   12055:                 next;
                   12056:             }
                   12057:         }
                   12058:         # Check if extension is valid
                   12059:         if (($fname =~ /\.(\w+)$/) &&
                   12060:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   12061:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12062:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12063:             next;
                   12064:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12065:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12066:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12067:             next;
                   12068:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   12069:             $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  12070:             next;
                   12071:         }
                   12072:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  12073:         my $subdir = $path;
                   12074:         $subdir =~ s{/+$}{};
1.661     raeburn  12075:         if ($context eq 'portfolio') {
1.984     raeburn  12076:             my $result;
                   12077:             if ($state eq 'existingfile') {
                   12078:                 $result=
                   12079:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  12080:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12081:             } else {
1.984     raeburn  12082:                 $result=
                   12083:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12084:                                                     $dirpath.
1.1123    raeburn  12085:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12086:                 if ($result !~ m|^/uploaded/|) {
                   12087:                     $output .= '<span class="LC_error">'
                   12088:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12089:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12090:                                .'</span><br />';
                   12091:                     next;
                   12092:                 } else {
1.987     raeburn  12093:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12094:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12095:                 }
1.661     raeburn  12096:             }
1.1123    raeburn  12097:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  12098:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12099:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12100:             my $result =
1.1126    raeburn  12101:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12102:             if ($result !~ m|^/uploaded/|) {
                   12103:                 $output .= '<span class="LC_error">'
                   12104:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12105:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12106:                            .'</span><br />';
                   12107:                     next;
                   12108:             } else {
                   12109:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12110:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  12111:                 if ($context eq 'syllabus') {
                   12112:                     &Apache::lonnet::make_public_indefinitely($result);
                   12113:                 }
1.987     raeburn  12114:             }
1.661     raeburn  12115:         } else {
                   12116: # Save the file
                   12117:             my $target = $env{'form.embedded_item_'.$i};
                   12118:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12119:             my $dest = $fullpath.$fname;
                   12120:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12121:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12122:             my $count;
                   12123:             my $filepath = $dir_root;
1.1027    raeburn  12124:             foreach my $subdir (@parts) {
                   12125:                 $filepath .= "/$subdir";
                   12126:                 if (!-e $filepath) {
1.661     raeburn  12127:                     mkdir($filepath,0770);
                   12128:                 }
                   12129:             }
                   12130:             my $fh;
                   12131:             if (!open($fh,'>'.$dest)) {
                   12132:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12133:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12134:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12135:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12136:                            '</span><br />';
                   12137:             } else {
                   12138:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12139:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12140:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12141:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12142:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12143:                               '</span><br />';
                   12144:                 } else {
1.987     raeburn  12145:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12146:                                $url.'</span>').'<br />';
                   12147:                     unless ($context eq 'testbank') {
                   12148:                         $footer .= &mt('View embedded file: [_1]',
                   12149:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12150:                     }
                   12151:                 }
                   12152:                 close($fh);
                   12153:             }
                   12154:         }
                   12155:         if ($env{'form.embedded_ref_'.$i}) {
                   12156:             $pathchange{$i} = 1;
                   12157:         }
                   12158:     }
                   12159:     if ($output) {
                   12160:         $output = '<p>'.$output.'</p>';
                   12161:     }
                   12162:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12163:     $returnflag = 'ok';
1.1071    raeburn  12164:     my $numpathchgs = scalar(keys(%pathchange));
                   12165:     if ($numpathchgs > 0) {
1.987     raeburn  12166:         if ($context eq 'portfolio') {
                   12167:             $output .= '<p>'.&mt('or').'</p>';
                   12168:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12169:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12170:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12171:             $returnflag = 'modify_orightml';
                   12172:         }
                   12173:     }
1.1071    raeburn  12174:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12175: }
                   12176: 
                   12177: sub modify_html_form {
                   12178:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12179:     my $end = 0;
                   12180:     my $modifyform;
                   12181:     if ($context eq 'upload_embedded') {
                   12182:         return unless (ref($pathchange) eq 'HASH');
                   12183:         if ($env{'form.number_embedded_items'}) {
                   12184:             $end += $env{'form.number_embedded_items'};
                   12185:         }
                   12186:         if ($env{'form.number_pathchange_items'}) {
                   12187:             $end += $env{'form.number_pathchange_items'};
                   12188:         }
                   12189:         if ($end) {
                   12190:             for (my $i=0; $i<$end; $i++) {
                   12191:                 if ($i < $env{'form.number_embedded_items'}) {
                   12192:                     next unless($pathchange->{$i});
                   12193:                 }
                   12194:                 $modifyform .=
                   12195:                     &start_data_table_row().
                   12196:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12197:                     'checked="checked" /></td>'.
                   12198:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12199:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12200:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12201:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12202:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12203:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12204:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12205:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12206:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12207:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12208:                     &end_data_table_row();
1.1071    raeburn  12209:             }
1.987     raeburn  12210:         }
                   12211:     } else {
                   12212:         $modifyform = $pathchgtable;
                   12213:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12214:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12215:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12216:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12217:         }
                   12218:     }
                   12219:     if ($modifyform) {
1.1071    raeburn  12220:         if ($actionurl eq '/adm/dependencies') {
                   12221:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12222:         }
1.987     raeburn  12223:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12224:                '<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".
                   12225:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12226:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12227:                '</ol></p>'."\n".'<p>'.
                   12228:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12229:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12230:                &start_data_table()."\n".
                   12231:                &start_data_table_header_row().
                   12232:                '<th>'.&mt('Change?').'</th>'.
                   12233:                '<th>'.&mt('Current reference').'</th>'.
                   12234:                '<th>'.&mt('Required reference').'</th>'.
                   12235:                &end_data_table_header_row()."\n".
                   12236:                $modifyform.
                   12237:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12238:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12239:                '</form>'."\n";
                   12240:     }
                   12241:     return;
                   12242: }
                   12243: 
                   12244: sub modify_html_refs {
1.1123    raeburn  12245:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12246:     my $container;
                   12247:     if ($context eq 'portfolio') {
                   12248:         $container = $env{'form.container'};
                   12249:     } elsif ($context eq 'coursedoc') {
                   12250:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12251:     } elsif ($context eq 'manage_dependencies') {
                   12252:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12253:         $container = "/$container";
1.1123    raeburn  12254:     } elsif ($context eq 'syllabus') {
                   12255:         $container = $url;
1.987     raeburn  12256:     } else {
1.1027    raeburn  12257:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12258:     }
                   12259:     my (%allfiles,%codebase,$output,$content);
                   12260:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  12261:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  12262:         if (wantarray) {
                   12263:             return ('',0,0); 
                   12264:         } else {
                   12265:             return;
                   12266:         }
                   12267:     }
                   12268:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12269:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12270:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12271:             if (wantarray) {
                   12272:                 return ('',0,0);
                   12273:             } else {
                   12274:                 return;
                   12275:             }
                   12276:         } 
1.987     raeburn  12277:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12278:         if ($content eq '-1') {
                   12279:             if (wantarray) {
                   12280:                 return ('',0,0);
                   12281:             } else {
                   12282:                 return;
                   12283:             }
                   12284:         }
1.987     raeburn  12285:     } else {
1.1071    raeburn  12286:         unless ($container =~ /^\Q$dir_root\E/) {
                   12287:             if (wantarray) {
                   12288:                 return ('',0,0);
                   12289:             } else {
                   12290:                 return;
                   12291:             }
                   12292:         } 
1.1317    raeburn  12293:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12294:             $content = join('', <$fh>);
                   12295:             close($fh);
                   12296:         } else {
1.1071    raeburn  12297:             if (wantarray) {
                   12298:                 return ('',0,0);
                   12299:             } else {
                   12300:                 return;
                   12301:             }
1.987     raeburn  12302:         }
                   12303:     }
                   12304:     my ($count,$codebasecount) = (0,0);
                   12305:     my $mm = new File::MMagic;
                   12306:     my $mime_type = $mm->checktype_contents($content);
                   12307:     if ($mime_type eq 'text/html') {
                   12308:         my $parse_result = 
                   12309:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12310:                                                     \%codebase,\$content);
                   12311:         if ($parse_result eq 'ok') {
                   12312:             foreach my $i (@changes) {
                   12313:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12314:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12315:                 if ($allfiles{$ref}) {
                   12316:                     my $newname =  $orig;
                   12317:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12318:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12319:                     if ($attrib_regexp =~ /:/) {
                   12320:                         $attrib_regexp =~ s/\:/|/g;
                   12321:                     }
                   12322:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12323:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12324:                         $count += $numchg;
1.1123    raeburn  12325:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  12326:                         delete($allfiles{$ref});
1.987     raeburn  12327:                     }
                   12328:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12329:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12330:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12331:                         $codebasecount ++;
                   12332:                     }
                   12333:                 }
                   12334:             }
1.1123    raeburn  12335:             my $skiprewrites;
1.987     raeburn  12336:             if ($count || $codebasecount) {
                   12337:                 my $saveresult;
1.1071    raeburn  12338:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12339:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12340:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12341:                     if ($url eq $container) {
                   12342:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12343:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12344:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12345:                                             $fname.'</span>').'</p>';
1.987     raeburn  12346:                     } else {
                   12347:                          $output = '<p class="LC_error">'.
                   12348:                                    &mt('Error: update failed for: [_1].',
                   12349:                                    '<span class="LC_filename">'.
                   12350:                                    $container.'</span>').'</p>';
                   12351:                     }
1.1123    raeburn  12352:                     if ($context eq 'syllabus') {
                   12353:                         unless ($saveresult eq 'ok') {
                   12354:                             $skiprewrites = 1;
                   12355:                         }
                   12356:                     }
1.987     raeburn  12357:                 } else {
1.1317    raeburn  12358:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  12359:                         print $fh $content;
                   12360:                         close($fh);
                   12361:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12362:                                   $count,'<span class="LC_filename">'.
                   12363:                                   $container.'</span>').'</p>';
1.661     raeburn  12364:                     } else {
1.987     raeburn  12365:                          $output = '<p class="LC_error">'.
                   12366:                                    &mt('Error: could not update [_1].',
                   12367:                                    '<span class="LC_filename">'.
                   12368:                                    $container.'</span>').'</p>';
1.661     raeburn  12369:                     }
                   12370:                 }
                   12371:             }
1.1123    raeburn  12372:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12373:                 my ($actionurl,$state);
                   12374:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12375:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12376:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12377:                                               \%codebase,
                   12378:                                               {'context' => 'rewrites',
                   12379:                                                'ignore_remote_references' => 1,});
                   12380:                 if (ref($mapping) eq 'HASH') {
                   12381:                     my $rewrites = 0;
                   12382:                     foreach my $key (keys(%{$mapping})) {
                   12383:                         next if ($key =~ m{^https?://});
                   12384:                         my $ref = $mapping->{$key};
                   12385:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12386:                         my $attrib;
                   12387:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12388:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12389:                         }
                   12390:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12391:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12392:                             $rewrites += $numchg;
                   12393:                         }
                   12394:                     }
                   12395:                     if ($rewrites) {
                   12396:                         my $saveresult; 
                   12397:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12398:                         if ($url eq $container) {
                   12399:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12400:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12401:                                             $count,'<span class="LC_filename">'.
                   12402:                                             $fname.'</span>').'</p>';
                   12403:                         } else {
                   12404:                             $output .= '<p class="LC_error">'.
                   12405:                                        &mt('Error: could not update links in [_1].',
                   12406:                                        '<span class="LC_filename">'.
                   12407:                                        $container.'</span>').'</p>';
                   12408: 
                   12409:                         }
                   12410:                     }
                   12411:                 }
                   12412:             }
1.987     raeburn  12413:         } else {
                   12414:             &logthis('Failed to parse '.$container.
                   12415:                      ' to modify references: '.$parse_result);
1.661     raeburn  12416:         }
                   12417:     }
1.1071    raeburn  12418:     if (wantarray) {
                   12419:         return ($output,$count,$codebasecount);
                   12420:     } else {
                   12421:         return $output;
                   12422:     }
1.661     raeburn  12423: }
                   12424: 
                   12425: sub check_for_existing {
                   12426:     my ($path,$fname,$element) = @_;
                   12427:     my ($state,$msg);
                   12428:     if (-d $path.'/'.$fname) {
                   12429:         $state = 'exists';
                   12430:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12431:     } elsif (-e $path.'/'.$fname) {
                   12432:         $state = 'exists';
                   12433:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12434:     }
                   12435:     if ($state eq 'exists') {
                   12436:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12437:     }
                   12438:     return ($state,$msg);
                   12439: }
                   12440: 
                   12441: sub check_for_upload {
                   12442:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12443:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12444:     my $filesize = length($env{'form.'.$element});
                   12445:     if (!$filesize) {
                   12446:         my $msg = '<span class="LC_error">'.
                   12447:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12448:                       '<span class="LC_filename">'.$fname.'</span>',
                   12449:                       $filesize).'<br />'.
1.1007    raeburn  12450:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12451:                   '</span>';
                   12452:         return ('zero_bytes',$msg);
                   12453:     }
                   12454:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12455:     my $getpropath = 1;
1.1021    raeburn  12456:     my ($dirlistref,$listerror) =
                   12457:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12458:     my $found_file = 0;
                   12459:     my $locked_file = 0;
1.991     raeburn  12460:     my @lockers;
                   12461:     my $navmap;
                   12462:     if ($env{'request.course.id'}) {
                   12463:         $navmap = Apache::lonnavmaps::navmap->new();
                   12464:     }
1.1021    raeburn  12465:     if (ref($dirlistref) eq 'ARRAY') {
                   12466:         foreach my $line (@{$dirlistref}) {
                   12467:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12468:             if ($file_name eq $fname){
                   12469:                 $file_name = $path.$file_name;
                   12470:                 if ($group ne '') {
                   12471:                     $file_name = $group.$file_name;
                   12472:                 }
                   12473:                 $found_file = 1;
                   12474:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12475:                     foreach my $lock (@lockers) {
                   12476:                         if (ref($lock) eq 'ARRAY') {
                   12477:                             my ($symb,$crsid) = @{$lock};
                   12478:                             if ($crsid eq $env{'request.course.id'}) {
                   12479:                                 if (ref($navmap)) {
                   12480:                                     my $res = $navmap->getBySymb($symb);
                   12481:                                     foreach my $part (@{$res->parts()}) { 
                   12482:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12483:                                         unless (($slot_status == $res->RESERVED) ||
                   12484:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12485:                                             $locked_file = 1;
                   12486:                                         }
1.991     raeburn  12487:                                     }
1.1021    raeburn  12488:                                 } else {
                   12489:                                     $locked_file = 1;
1.991     raeburn  12490:                                 }
                   12491:                             } else {
                   12492:                                 $locked_file = 1;
                   12493:                             }
                   12494:                         }
1.1021    raeburn  12495:                    }
                   12496:                 } else {
                   12497:                     my @info = split(/\&/,$rest);
                   12498:                     my $currsize = $info[6]/1000;
                   12499:                     if ($currsize < $filesize) {
                   12500:                         my $extra = $filesize - $currsize;
                   12501:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   12502:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12503:                                       &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded if existing (smaller) file with same name (size = [_3] kilobytes) is replaced.',
1.1179    bisitz   12504:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12505:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12506:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12507:                             return ('will_exceed_quota',$msg);
                   12508:                         }
1.984     raeburn  12509:                     }
                   12510:                 }
1.661     raeburn  12511:             }
                   12512:         }
                   12513:     }
                   12514:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   12515:         my $msg = '<p class="LC_warning">'.
                   12516:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  12517:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12518:         return ('will_exceed_quota',$msg);
                   12519:     } elsif ($found_file) {
                   12520:         if ($locked_file) {
1.1179    bisitz   12521:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12522:             $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
1.1179    bisitz   12523:             $msg .= '</p>';
1.661     raeburn  12524:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12525:             return ('file_locked',$msg);
                   12526:         } else {
1.1179    bisitz   12527:             my $msg = '<p class="LC_error">';
1.984     raeburn  12528:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1179    bisitz   12529:             $msg .= '</p>';
1.984     raeburn  12530:             return ('existingfile',$msg);
1.661     raeburn  12531:         }
                   12532:     }
                   12533: }
                   12534: 
1.987     raeburn  12535: sub check_for_traversal {
                   12536:     my ($path,$url,$toplevel) = @_;
                   12537:     my @parts=split(/\//,$path);
                   12538:     my $cleanpath;
                   12539:     my $fullpath = $url;
                   12540:     for (my $i=0;$i<@parts;$i++) {
                   12541:         next if ($parts[$i] eq '.');
                   12542:         if ($parts[$i] eq '..') {
                   12543:             $fullpath =~ s{([^/]+/)$}{};
                   12544:         } else {
                   12545:             $fullpath .= $parts[$i].'/';
                   12546:         }
                   12547:     }
                   12548:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12549:         $cleanpath = $1;
                   12550:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12551:         my $curr_toprel = $1;
                   12552:         my @parts = split(/\//,$curr_toprel);
                   12553:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12554:         my @urlparts = split(/\//,$url_toprel);
                   12555:         my $doubledots;
                   12556:         my $startdiff = -1;
                   12557:         for (my $i=0; $i<@urlparts; $i++) {
                   12558:             if ($startdiff == -1) {
                   12559:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12560:                     $startdiff = $i;
                   12561:                     $doubledots .= '../';
                   12562:                 }
                   12563:             } else {
                   12564:                 $doubledots .= '../';
                   12565:             }
                   12566:         }
                   12567:         if ($startdiff > -1) {
                   12568:             $cleanpath = $doubledots;
                   12569:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12570:                 $cleanpath .= $parts[$i].'/';
                   12571:             }
                   12572:         }
                   12573:     }
                   12574:     $cleanpath =~ s{(/)$}{};
                   12575:     return $cleanpath;
                   12576: }
1.31      albertel 12577: 
1.1053    raeburn  12578: sub is_archive_file {
                   12579:     my ($mimetype) = @_;
                   12580:     if (($mimetype eq 'application/octet-stream') ||
                   12581:         ($mimetype eq 'application/x-stuffit') ||
                   12582:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12583:         return 1;
                   12584:     }
                   12585:     return;
                   12586: }
                   12587: 
                   12588: sub decompress_form {
1.1065    raeburn  12589:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12590:     my %lt = &Apache::lonlocal::texthash (
                   12591:         this => 'This file is an archive file.',
1.1067    raeburn  12592:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12593:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12594:         youm => 'You may wish to extract its contents.',
                   12595:         extr => 'Extract contents',
1.1067    raeburn  12596:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12597:         proa => 'Process automatically?',
1.1053    raeburn  12598:         yes  => 'Yes',
                   12599:         no   => 'No',
1.1067    raeburn  12600:         fold => 'Title for folder containing movie',
                   12601:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12602:     );
1.1065    raeburn  12603:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12604:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12605:     my $info = &list_archive_contents($fileloc,\@paths);
                   12606:     if (@paths) {
                   12607:         foreach my $path (@paths) {
                   12608:             $path =~ s{^/}{};
1.1067    raeburn  12609:             if ($path =~ m{^([^/]+)/$}) {
                   12610:                 $topdir = $1;
                   12611:             }
1.1065    raeburn  12612:             if ($path =~ m{^([^/]+)/}) {
                   12613:                 $toplevel{$1} = $path;
                   12614:             } else {
                   12615:                 $toplevel{$path} = $path;
                   12616:             }
                   12617:         }
                   12618:     }
1.1067    raeburn  12619:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  12620:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12621:                         "$topdir/media/",
                   12622:                         "$topdir/media/$topdir.mp4",
                   12623:                         "$topdir/media/FirstFrame.png",
                   12624:                         "$topdir/media/player.swf",
                   12625:                         "$topdir/media/swfobject.js",
                   12626:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  12627:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  12628:                          "$topdir/$topdir.mp4",
                   12629:                          "$topdir/$topdir\_config.xml",
                   12630:                          "$topdir/$topdir\_controller.swf",
                   12631:                          "$topdir/$topdir\_embed.css",
                   12632:                          "$topdir/$topdir\_First_Frame.png",
                   12633:                          "$topdir/$topdir\_player.html",
                   12634:                          "$topdir/$topdir\_Thumbnails.png",
                   12635:                          "$topdir/playerProductInstall.swf",
                   12636:                          "$topdir/scripts/",
                   12637:                          "$topdir/scripts/config_xml.js",
                   12638:                          "$topdir/scripts/handlebars.js",
                   12639:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12640:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12641:                          "$topdir/scripts/modernizr.js",
                   12642:                          "$topdir/scripts/player-min.js",
                   12643:                          "$topdir/scripts/swfobject.js",
                   12644:                          "$topdir/skins/",
                   12645:                          "$topdir/skins/configuration_express.xml",
                   12646:                          "$topdir/skins/express_show/",
                   12647:                          "$topdir/skins/express_show/player-min.css",
                   12648:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  12649:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12650:                          "$topdir/$topdir.mp4",
                   12651:                          "$topdir/$topdir\_config.xml",
                   12652:                          "$topdir/$topdir\_controller.swf",
                   12653:                          "$topdir/$topdir\_embed.css",
                   12654:                          "$topdir/$topdir\_First_Frame.png",
                   12655:                          "$topdir/$topdir\_player.html",
                   12656:                          "$topdir/$topdir\_Thumbnails.png",
                   12657:                          "$topdir/playerProductInstall.swf",
                   12658:                          "$topdir/scripts/",
                   12659:                          "$topdir/scripts/config_xml.js",
                   12660:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12661:                          "$topdir/skins/",
                   12662:                          "$topdir/skins/configuration_express.xml",
                   12663:                          "$topdir/skins/express_show/",
                   12664:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12665:                          "$topdir/skins/express_show/spritesheet.png",
                   12666:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  12667:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12668:         if (@diffs == 0) {
1.1164    raeburn  12669:             $is_camtasia = 6;
                   12670:         } else {
1.1197    raeburn  12671:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  12672:             if (@diffs == 0) {
                   12673:                 $is_camtasia = 8;
1.1197    raeburn  12674:             } else {
                   12675:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12676:                 if (@diffs == 0) {
                   12677:                     $is_camtasia = 8;
                   12678:                 }
1.1164    raeburn  12679:             }
1.1067    raeburn  12680:         }
                   12681:     }
                   12682:     my $output;
                   12683:     if ($is_camtasia) {
                   12684:         $output = <<"ENDCAM";
                   12685: <script type="text/javascript" language="Javascript">
                   12686: // <![CDATA[
                   12687: 
                   12688: function camtasiaToggle() {
                   12689:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12690:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  12691:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12692:                 document.getElementById('camtasia_titles').style.display='block';
                   12693:             } else {
                   12694:                 document.getElementById('camtasia_titles').style.display='none';
                   12695:             }
                   12696:         }
                   12697:     }
                   12698:     return;
                   12699: }
                   12700: 
                   12701: // ]]>
                   12702: </script>
                   12703: <p>$lt{'camt'}</p>
                   12704: ENDCAM
1.1065    raeburn  12705:     } else {
1.1067    raeburn  12706:         $output = '<p>'.$lt{'this'};
                   12707:         if ($info eq '') {
                   12708:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12709:         } else {
                   12710:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12711:                        '<div><pre>'.$info.'</pre></div>';
                   12712:         }
1.1065    raeburn  12713:     }
1.1067    raeburn  12714:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12715:     my $duplicates;
                   12716:     my $num = 0;
                   12717:     if (ref($dirlist) eq 'ARRAY') {
                   12718:         foreach my $item (@{$dirlist}) {
                   12719:             if (ref($item) eq 'ARRAY') {
                   12720:                 if (exists($toplevel{$item->[0]})) {
                   12721:                     $duplicates .= 
                   12722:                         &start_data_table_row().
                   12723:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12724:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12725:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12726:                         'value="1" />'.&mt('Yes').'</label>'.
                   12727:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12728:                         '<td>'.$item->[0].'</td>';
                   12729:                     if ($item->[2]) {
                   12730:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12731:                     } else {
                   12732:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12733:                     }
                   12734:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12735:                                    '<td>'.
                   12736:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12737:                                    '</td>'.
                   12738:                                    &end_data_table_row();
                   12739:                     $num ++;
                   12740:                 }
                   12741:             }
                   12742:         }
                   12743:     }
                   12744:     my $itemcount;
                   12745:     if (@paths > 0) {
                   12746:         $itemcount = scalar(@paths);
                   12747:     } else {
                   12748:         $itemcount = 1;
                   12749:     }
1.1067    raeburn  12750:     if ($is_camtasia) {
                   12751:         $output .= $lt{'auto'}.'<br />'.
                   12752:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  12753:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12754:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12755:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12756:                    $lt{'no'}.'</label></span><br />'.
                   12757:                    '<div id="camtasia_titles" style="display:block">'.
                   12758:                    &Apache::lonhtmlcommon::start_pick_box().
                   12759:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12760:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12761:                    &Apache::lonhtmlcommon::row_closure().
                   12762:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12763:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12764:                    &Apache::lonhtmlcommon::row_closure(1).
                   12765:                    &Apache::lonhtmlcommon::end_pick_box().
                   12766:                    '</div>';
                   12767:     }
1.1065    raeburn  12768:     $output .= 
                   12769:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12770:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12771:         "\n";
1.1065    raeburn  12772:     if ($duplicates ne '') {
                   12773:         $output .= '<p><span class="LC_warning">'.
                   12774:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12775:                    &start_data_table().
                   12776:                    &start_data_table_header_row().
                   12777:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12778:                    '<th>'.&mt('Name').'</th>'.
                   12779:                    '<th>'.&mt('Type').'</th>'.
                   12780:                    '<th>'.&mt('Size').'</th>'.
                   12781:                    '<th>'.&mt('Last modified').'</th>'.
                   12782:                    &end_data_table_header_row().
                   12783:                    $duplicates.
                   12784:                    &end_data_table().
                   12785:                    '</p>';
                   12786:     }
1.1067    raeburn  12787:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12788:     if (ref($hiddenelements) eq 'HASH') {
                   12789:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12790:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12791:         }
                   12792:     }
                   12793:     $output .= <<"END";
1.1067    raeburn  12794: <br />
1.1053    raeburn  12795: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12796: </form>
                   12797: $noextract
                   12798: END
                   12799:     return $output;
                   12800: }
                   12801: 
1.1065    raeburn  12802: sub decompression_utility {
                   12803:     my ($program) = @_;
                   12804:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12805:     my $location;
                   12806:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12807:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12808:                          '/usr/sbin/') {
                   12809:             if (-x $dir.$program) {
                   12810:                 $location = $dir.$program;
                   12811:                 last;
                   12812:             }
                   12813:         }
                   12814:     }
                   12815:     return $location;
                   12816: }
                   12817: 
                   12818: sub list_archive_contents {
                   12819:     my ($file,$pathsref) = @_;
                   12820:     my (@cmd,$output);
                   12821:     my $needsregexp;
                   12822:     if ($file =~ /\.zip$/) {
                   12823:         @cmd = (&decompression_utility('unzip'),"-l");
                   12824:         $needsregexp = 1;
                   12825:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12826:              ($file =~ /\.tgz$/)) {
                   12827:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12828:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12829:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12830:     } elsif ($file =~ m|\.tar$|) {
                   12831:         @cmd = (&decompression_utility('tar'),"-tf");
                   12832:     }
                   12833:     if (@cmd) {
                   12834:         undef($!);
                   12835:         undef($@);
                   12836:         if (open(my $fh,"-|", @cmd, $file)) {
                   12837:             while (my $line = <$fh>) {
                   12838:                 $output .= $line;
                   12839:                 chomp($line);
                   12840:                 my $item;
                   12841:                 if ($needsregexp) {
                   12842:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12843:                 } else {
                   12844:                     $item = $line;
                   12845:                 }
                   12846:                 if ($item ne '') {
                   12847:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12848:                         push(@{$pathsref},$item);
                   12849:                     } 
                   12850:                 }
                   12851:             }
                   12852:             close($fh);
                   12853:         }
                   12854:     }
                   12855:     return $output;
                   12856: }
                   12857: 
1.1053    raeburn  12858: sub decompress_uploaded_file {
                   12859:     my ($file,$dir) = @_;
                   12860:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12861:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12862:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12863:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12864:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12865:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12866:     my $decompressed = $env{'cgi.decompressed'};
                   12867:     &Apache::lonnet::delenv('cgi.file');
                   12868:     &Apache::lonnet::delenv('cgi.dir');
                   12869:     &Apache::lonnet::delenv('cgi.decompressed');
                   12870:     return ($decompressed,$result);
                   12871: }
                   12872: 
1.1055    raeburn  12873: sub process_decompression {
                   12874:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  12875:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12876:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12877:                &mt('Unexpected file path.').'</p>'."\n";
                   12878:     }
                   12879:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12880:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12881:                &mt('Unexpected course context.').'</p>'."\n";
                   12882:     }
1.1293    raeburn  12883:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  12884:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12885:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12886:     }
1.1055    raeburn  12887:     my ($dir,$error,$warning,$output);
1.1180    raeburn  12888:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   12889:         $error = &mt('Filename not a supported archive file type.').
                   12890:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12891:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12892:     } else {
                   12893:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12894:         if ($docuhome eq 'no_host') {
                   12895:             $error = &mt('Could not determine home server for course.');
                   12896:         } else {
                   12897:             my @ids=&Apache::lonnet::current_machine_ids();
                   12898:             my $currdir = "$dir_root/$destination";
                   12899:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12900:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12901:                        "$dir_root/$destination";
                   12902:             } else {
                   12903:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12904:                        "$dir_root/$docudom/$docuname/$destination";
                   12905:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12906:                     $error = &mt('Archive file not found.');
                   12907:                 }
                   12908:             }
1.1065    raeburn  12909:             my (@to_overwrite,@to_skip);
                   12910:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12911:                 my $total = $env{'form.archive_overwrite_total'};
                   12912:                 for (my $i=0; $i<$total; $i++) {
                   12913:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12914:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12915:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12916:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12917:                     }
                   12918:                 }
                   12919:             }
                   12920:             my $numskip = scalar(@to_skip);
1.1292    raeburn  12921:             my $numoverwrite = scalar(@to_overwrite);
                   12922:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  12923:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12924:             } elsif ($dir eq '') {
1.1055    raeburn  12925:                 $error = &mt('Directory containing archive file unavailable.');
                   12926:             } elsif (!$error) {
1.1065    raeburn  12927:                 my ($decompressed,$display);
1.1292    raeburn  12928:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12929:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12930:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  12931:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   12932:                         ($decompressed,$display) = 
                   12933:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   12934:                         foreach my $item (@to_skip) {
                   12935:                             if (($item ne '') && ($item !~ /\.\./)) {
                   12936:                                 if (-f "$dir/$tempdir/$item") { 
                   12937:                                     unlink("$dir/$tempdir/$item");
                   12938:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  12939:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  12940:                                 }
                   12941:                             }
                   12942:                         }
                   12943:                         foreach my $item (@to_overwrite) {
                   12944:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   12945:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   12946:                                     if (-f "$dir/$item") {
                   12947:                                         unlink("$dir/$item");
                   12948:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  12949:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  12950:                                     }
                   12951:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   12952:                                 }
1.1065    raeburn  12953:                             }
                   12954:                         }
1.1292    raeburn  12955:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  12956:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  12957:                         }
1.1065    raeburn  12958:                     }
                   12959:                 } else {
                   12960:                     ($decompressed,$display) = 
                   12961:                         &decompress_uploaded_file($file,$dir);
                   12962:                 }
1.1055    raeburn  12963:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12964:                     $output = '<p class="LC_info">'.
                   12965:                               &mt('Files extracted successfully from archive.').
                   12966:                               '</p>'."\n";
1.1055    raeburn  12967:                     my ($warning,$result,@contents);
                   12968:                     my ($newdirlistref,$newlisterror) =
                   12969:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12970:                                                  $docuname,1);
                   12971:                     my (%is_dir,%changes,@newitems);
                   12972:                     my $dirptr = 16384;
1.1065    raeburn  12973:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12974:                         foreach my $dir_line (@{$newdirlistref}) {
                   12975:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  12976:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  12977:                                 push(@newitems,$item);
                   12978:                                 if ($dirptr&$testdir) {
                   12979:                                     $is_dir{$item} = 1;
                   12980:                                 }
                   12981:                                 $changes{$item} = 1;
                   12982:                             }
                   12983:                         }
                   12984:                     }
                   12985:                     if (keys(%changes) > 0) {
                   12986:                         foreach my $item (sort(@newitems)) {
                   12987:                             if ($changes{$item}) {
                   12988:                                 push(@contents,$item);
                   12989:                             }
                   12990:                         }
                   12991:                     }
                   12992:                     if (@contents > 0) {
1.1067    raeburn  12993:                         my $wantform;
                   12994:                         unless ($env{'form.autoextract_camtasia'}) {
                   12995:                             $wantform = 1;
                   12996:                         }
1.1056    raeburn  12997:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12998:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12999:                                                                 $currdir,\%is_dir,
                   13000:                                                                 \%children,\%parent,
1.1056    raeburn  13001:                                                                 \@contents,\%dirorder,
                   13002:                                                                 \%titles,$wantform);
1.1055    raeburn  13003:                         if ($datatable ne '') {
                   13004:                             $output .= &archive_options_form('decompressed',$datatable,
                   13005:                                                              $count,$hiddenelem);
1.1065    raeburn  13006:                             my $startcount = 6;
1.1055    raeburn  13007:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13008:                                                            \%titles,\%children);
1.1055    raeburn  13009:                         }
1.1067    raeburn  13010:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  13011:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13012:                             my %displayed;
                   13013:                             my $total = 1;
                   13014:                             $env{'form.archive_directory'} = [];
                   13015:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13016:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13017:                                 $path =~ s{/$}{};
                   13018:                                 my $item;
                   13019:                                 if ($path ne '') {
                   13020:                                     $item = "$path/$titles{$i}";
                   13021:                                 } else {
                   13022:                                     $item = $titles{$i};
                   13023:                                 }
                   13024:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13025:                                 if ($item eq $contents[0]) {
                   13026:                                     push(@{$env{'form.archive_directory'}},$i);
                   13027:                                     $env{'form.archive_'.$i} = 'display';
                   13028:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13029:                                     $displayed{'folder'} = $i;
1.1164    raeburn  13030:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13031:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  13032:                                     $env{'form.archive_'.$i} = 'display';
                   13033:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13034:                                     $displayed{'web'} = $i;
                   13035:                                 } else {
1.1164    raeburn  13036:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13037:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13038:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13039:                                         push(@{$env{'form.archive_directory'}},$i);
                   13040:                                     }
                   13041:                                     $env{'form.archive_'.$i} = 'dependency';
                   13042:                                 }
                   13043:                                 $total ++;
                   13044:                             }
                   13045:                             for (my $i=1; $i<$total; $i++) {
                   13046:                                 next if ($i == $displayed{'web'});
                   13047:                                 next if ($i == $displayed{'folder'});
                   13048:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13049:                             }
                   13050:                             $env{'form.phase'} = 'decompress_cleanup';
                   13051:                             $env{'form.archivedelete'} = 1;
                   13052:                             $env{'form.archive_count'} = $total-1;
                   13053:                             $output .=
                   13054:                                 &process_extracted_files('coursedocs',$docudom,
                   13055:                                                          $docuname,$destination,
                   13056:                                                          $dir_root,$hiddenelem);
                   13057:                         }
1.1055    raeburn  13058:                     } else {
                   13059:                         $warning = &mt('No new items extracted from archive file.');
                   13060:                     }
                   13061:                 } else {
                   13062:                     $output = $display;
                   13063:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13064:                 }
                   13065:             }
                   13066:         }
                   13067:     }
                   13068:     if ($error) {
                   13069:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13070:                    $error.'</p>'."\n";
                   13071:     }
                   13072:     if ($warning) {
                   13073:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13074:     }
                   13075:     return $output;
                   13076: }
                   13077: 
                   13078: sub get_extracted {
1.1056    raeburn  13079:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13080:         $titles,$wantform) = @_;
1.1055    raeburn  13081:     my $count = 0;
                   13082:     my $depth = 0;
                   13083:     my $datatable;
1.1056    raeburn  13084:     my @hierarchy;
1.1055    raeburn  13085:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13086:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13087:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13088:     foreach my $item (@{$contents}) {
                   13089:         $count ++;
1.1056    raeburn  13090:         @{$dirorder->{$count}} = @hierarchy;
                   13091:         $titles->{$count} = $item;
1.1055    raeburn  13092:         &archive_hierarchy($depth,$count,$parent,$children);
                   13093:         if ($wantform) {
                   13094:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13095:                                        $currdir,$depth,$count);
                   13096:         }
                   13097:         if ($is_dir->{$item}) {
                   13098:             $depth ++;
1.1056    raeburn  13099:             push(@hierarchy,$count);
                   13100:             $parent->{$depth} = $count;
1.1055    raeburn  13101:             $datatable .=
                   13102:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13103:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13104:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13105:             $depth --;
1.1056    raeburn  13106:             pop(@hierarchy);
1.1055    raeburn  13107:         }
                   13108:     }
                   13109:     return ($count,$datatable);
                   13110: }
                   13111: 
                   13112: sub recurse_extracted_archive {
1.1056    raeburn  13113:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13114:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13115:     my $result='';
1.1056    raeburn  13116:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13117:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13118:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13119:         return $result;
                   13120:     }
                   13121:     my $dirptr = 16384;
                   13122:     my ($newdirlistref,$newlisterror) =
                   13123:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13124:     if (ref($newdirlistref) eq 'ARRAY') {
                   13125:         foreach my $dir_line (@{$newdirlistref}) {
                   13126:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13127:             unless ($item =~ /^\.+$/) {
                   13128:                 $$count ++;
1.1056    raeburn  13129:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13130:                 $titles->{$$count} = $item;
1.1055    raeburn  13131:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13132: 
1.1055    raeburn  13133:                 my $is_dir;
                   13134:                 if ($dirptr&$testdir) {
                   13135:                     $is_dir = 1;
                   13136:                 }
                   13137:                 if ($wantform) {
                   13138:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13139:                 }
                   13140:                 if ($is_dir) {
                   13141:                     $$depth ++;
1.1056    raeburn  13142:                     push(@{$hierarchy},$$count);
                   13143:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13144:                     $result .=
                   13145:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13146:                                                    $docuname,$depth,$count,
1.1056    raeburn  13147:                                                    $hierarchy,$dirorder,$children,
                   13148:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13149:                     $$depth --;
1.1056    raeburn  13150:                     pop(@{$hierarchy});
1.1055    raeburn  13151:                 }
                   13152:             }
                   13153:         }
                   13154:     }
                   13155:     return $result;
                   13156: }
                   13157: 
                   13158: sub archive_hierarchy {
                   13159:     my ($depth,$count,$parent,$children) =@_;
                   13160:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13161:         if (exists($parent->{$depth})) {
                   13162:              $children->{$parent->{$depth}} .= $count.':';
                   13163:         }
                   13164:     }
                   13165:     return;
                   13166: }
                   13167: 
                   13168: sub archive_row {
                   13169:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13170:     my ($name) = ($item =~ m{([^/]+)$});
                   13171:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13172:                                        'display'    => 'Add as file',
1.1055    raeburn  13173:                                        'dependency' => 'Include as dependency',
                   13174:                                        'discard'    => 'Discard',
                   13175:                                       );
                   13176:     if ($is_dir) {
1.1059    raeburn  13177:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13178:     }
1.1056    raeburn  13179:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13180:     my $offset = 0;
1.1055    raeburn  13181:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13182:         $offset ++;
1.1065    raeburn  13183:         if ($action ne 'display') {
                   13184:             $offset ++;
                   13185:         }  
1.1055    raeburn  13186:         $output .= '<td><span class="LC_nobreak">'.
                   13187:                    '<label><input type="radio" name="archive_'.$count.
                   13188:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13189:         my $text = $choices{$action};
                   13190:         if ($is_dir) {
                   13191:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13192:             if ($action eq 'display') {
1.1059    raeburn  13193:                 $text = &mt('Add as folder');
1.1055    raeburn  13194:             }
1.1056    raeburn  13195:         } else {
                   13196:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13197: 
                   13198:         }
                   13199:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13200:         if ($action eq 'dependency') {
                   13201:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13202:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13203:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13204:                        '<option value=""></option>'."\n".
                   13205:                        '</select>'."\n".
                   13206:                        '</div>';
1.1059    raeburn  13207:         } elsif ($action eq 'display') {
                   13208:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13209:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13210:                        '</div>';
1.1055    raeburn  13211:         }
1.1056    raeburn  13212:         $output .= '</td>';
1.1055    raeburn  13213:     }
                   13214:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13215:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13216:     for (my $i=0; $i<$depth; $i++) {
                   13217:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13218:     }
                   13219:     if ($is_dir) {
                   13220:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13221:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13222:     } else {
                   13223:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13224:     }
                   13225:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13226:                &end_data_table_row();
                   13227:     return $output;
                   13228: }
                   13229: 
                   13230: sub archive_options_form {
1.1065    raeburn  13231:     my ($form,$display,$count,$hiddenelem) = @_;
                   13232:     my %lt = &Apache::lonlocal::texthash(
                   13233:                perm => 'Permanently remove archive file?',
                   13234:                hows => 'How should each extracted item be incorporated in the course?',
                   13235:                cont => 'Content actions for all',
                   13236:                addf => 'Add as folder/file',
                   13237:                incd => 'Include as dependency for a displayed file',
                   13238:                disc => 'Discard',
                   13239:                no   => 'No',
                   13240:                yes  => 'Yes',
                   13241:                save => 'Save',
                   13242:     );
                   13243:     my $output = <<"END";
                   13244: <form name="$form" method="post" action="">
                   13245: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13246: <label>
                   13247:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13248: </label>
                   13249: &nbsp;
                   13250: <label>
                   13251:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13252: </span>
                   13253: </p>
                   13254: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13255: <br />$lt{'hows'}
                   13256: <div class="LC_columnSection">
                   13257:   <fieldset>
                   13258:     <legend>$lt{'cont'}</legend>
                   13259:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13260:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13261:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13262:   </fieldset>
                   13263: </div>
                   13264: END
                   13265:     return $output.
1.1055    raeburn  13266:            &start_data_table()."\n".
1.1065    raeburn  13267:            $display."\n".
1.1055    raeburn  13268:            &end_data_table()."\n".
                   13269:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13270:            $hiddenelem.
1.1065    raeburn  13271:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13272:            '</form>';
                   13273: }
                   13274: 
                   13275: sub archive_javascript {
1.1056    raeburn  13276:     my ($startcount,$numitems,$titles,$children) = @_;
                   13277:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13278:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13279:     my $scripttag = <<START;
                   13280: <script type="text/javascript">
                   13281: // <![CDATA[
                   13282: 
                   13283: function checkAll(form,prefix) {
                   13284:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13285:     for (var i=0; i < form.elements.length; i++) {
                   13286:         var id = form.elements[i].id;
                   13287:         if ((id != '') && (id != undefined)) {
                   13288:             if (idstr.test(id)) {
                   13289:                 if (form.elements[i].type == 'radio') {
                   13290:                     form.elements[i].checked = true;
1.1056    raeburn  13291:                     var nostart = i-$startcount;
1.1059    raeburn  13292:                     var offset = nostart%7;
                   13293:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13294:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13295:                 }
                   13296:             }
                   13297:         }
                   13298:     }
                   13299: }
                   13300: 
                   13301: function propagateCheck(form,count) {
                   13302:     if (count > 0) {
1.1059    raeburn  13303:         var startelement = $startcount + ((count-1) * 7);
                   13304:         for (var j=1; j<6; j++) {
                   13305:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13306:                 var item = startelement + j; 
                   13307:                 if (form.elements[item].type == 'radio') {
                   13308:                     if (form.elements[item].checked) {
                   13309:                         containerCheck(form,count,j);
                   13310:                         break;
                   13311:                     }
1.1055    raeburn  13312:                 }
                   13313:             }
                   13314:         }
                   13315:     }
                   13316: }
                   13317: 
                   13318: numitems = $numitems
1.1056    raeburn  13319: var titles = new Array(numitems);
                   13320: var parents = new Array(numitems);
1.1055    raeburn  13321: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13322:     parents[i] = new Array;
1.1055    raeburn  13323: }
1.1059    raeburn  13324: var maintitle = '$maintitle';
1.1055    raeburn  13325: 
                   13326: START
                   13327: 
1.1056    raeburn  13328:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13329:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13330:         for (my $i=0; $i<@contents; $i ++) {
                   13331:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13332:         }
                   13333:     }
                   13334: 
1.1056    raeburn  13335:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13336:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13337:     }
                   13338: 
1.1055    raeburn  13339:     $scripttag .= <<END;
                   13340: 
                   13341: function containerCheck(form,count,offset) {
                   13342:     if (count > 0) {
1.1056    raeburn  13343:         dependencyCheck(form,count,offset);
1.1059    raeburn  13344:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13345:         form.elements[item].checked = true;
                   13346:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13347:             if (parents[count].length > 0) {
                   13348:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13349:                     containerCheck(form,parents[count][j],offset);
                   13350:                 }
                   13351:             }
                   13352:         }
                   13353:     }
                   13354: }
                   13355: 
                   13356: function dependencyCheck(form,count,offset) {
                   13357:     if (count > 0) {
1.1059    raeburn  13358:         var chosen = (offset+$startcount)+7*(count-1);
                   13359:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13360:         var currtype = form.elements[depitem].type;
                   13361:         if (form.elements[chosen].value == 'dependency') {
                   13362:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13363:             form.elements[depitem].options.length = 0;
                   13364:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  13365:             for (var i=1; i<=numitems; i++) {
                   13366:                 if (i == count) {
                   13367:                     continue;
                   13368:                 }
1.1059    raeburn  13369:                 var startelement = $startcount + (i-1) * 7;
                   13370:                 for (var j=1; j<6; j++) {
                   13371:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13372:                         var item = startelement + j;
                   13373:                         if (form.elements[item].type == 'radio') {
                   13374:                             if (form.elements[item].checked) {
                   13375:                                 if (form.elements[item].value == 'display') {
                   13376:                                     var n = form.elements[depitem].options.length;
                   13377:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13378:                                 }
                   13379:                             }
                   13380:                         }
                   13381:                     }
                   13382:                 }
                   13383:             }
                   13384:         } else {
                   13385:             document.getElementById('arc_depon_'+count).style.display='none';
                   13386:             form.elements[depitem].options.length = 0;
                   13387:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13388:         }
1.1059    raeburn  13389:         titleCheck(form,count,offset);
1.1056    raeburn  13390:     }
                   13391: }
                   13392: 
                   13393: function propagateSelect(form,count,offset) {
                   13394:     if (count > 0) {
1.1065    raeburn  13395:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13396:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13397:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13398:             if (parents[count].length > 0) {
                   13399:                 for (var j=0; j<parents[count].length; j++) {
                   13400:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13401:                 }
                   13402:             }
                   13403:         }
                   13404:     }
                   13405: }
1.1056    raeburn  13406: 
                   13407: function containerSelect(form,count,offset,picked) {
                   13408:     if (count > 0) {
1.1065    raeburn  13409:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13410:         if (form.elements[item].type == 'radio') {
                   13411:             if (form.elements[item].value == 'dependency') {
                   13412:                 if (form.elements[item+1].type == 'select-one') {
                   13413:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13414:                         if (form.elements[item+1].options[i].value == picked) {
                   13415:                             form.elements[item+1].selectedIndex = i;
                   13416:                             break;
                   13417:                         }
                   13418:                     }
                   13419:                 }
                   13420:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13421:                     if (parents[count].length > 0) {
                   13422:                         for (var j=0; j<parents[count].length; j++) {
                   13423:                             containerSelect(form,parents[count][j],offset,picked);
                   13424:                         }
                   13425:                     }
                   13426:                 }
                   13427:             }
                   13428:         }
                   13429:     }
                   13430: }
                   13431: 
1.1059    raeburn  13432: function titleCheck(form,count,offset) {
                   13433:     if (count > 0) {
                   13434:         var chosen = (offset+$startcount)+7*(count-1);
                   13435:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13436:         var currtype = form.elements[depitem].type;
                   13437:         if (form.elements[chosen].value == 'display') {
                   13438:             document.getElementById('arc_title_'+count).style.display='block';
                   13439:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13440:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13441:             }
                   13442:         } else {
                   13443:             document.getElementById('arc_title_'+count).style.display='none';
                   13444:             if (currtype == 'text') { 
                   13445:                 document.getElementById('archive_title_'+count).value='';
                   13446:             }
                   13447:         }
                   13448:     }
                   13449:     return;
                   13450: }
                   13451: 
1.1055    raeburn  13452: // ]]>
                   13453: </script>
                   13454: END
                   13455:     return $scripttag;
                   13456: }
                   13457: 
                   13458: sub process_extracted_files {
1.1067    raeburn  13459:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13460:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  13461:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  13462:     my @ids=&Apache::lonnet::current_machine_ids();
                   13463:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13464:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13465:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13466:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13467:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13468:         $pathtocheck = "$dir_root/$destination";
                   13469:         $dir = $dir_root;
                   13470:         $ishome = 1;
                   13471:     } else {
                   13472:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13473:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  13474:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  13475:     }
                   13476:     my $currdir = "$dir_root/$destination";
                   13477:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13478:     if ($env{'form.folderpath'}) {
                   13479:         my @items = split('&',$env{'form.folderpath'});
                   13480:         $folders{'0'} = $items[-2];
1.1099    raeburn  13481:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13482:             $containers{'0'}='page';
                   13483:         } else {  
                   13484:             $containers{'0'}='sequence';
                   13485:         }
1.1055    raeburn  13486:     }
                   13487:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13488:     if ($numitems) {
                   13489:         for (my $i=1; $i<=$numitems; $i++) {
                   13490:             my $path = $env{'form.archive_content_'.$i};
                   13491:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13492:                 my $item = $1;
                   13493:                 $toplevelitems{$item} = $i;
                   13494:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13495:                     $is_dir{$item} = 1;
                   13496:                 }
                   13497:             }
                   13498:         }
                   13499:     }
1.1067    raeburn  13500:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13501:     if (keys(%toplevelitems) > 0) {
                   13502:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13503:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13504:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13505:     }
1.1066    raeburn  13506:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13507:     if ($numitems) {
                   13508:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  13509:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13510:             my $path = $env{'form.archive_content_'.$i};
                   13511:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13512:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13513:                     if ($prefix ne '' && $path ne '') {
                   13514:                         if (-e $prefix.$path) {
1.1066    raeburn  13515:                             if ((@archdirs > 0) && 
                   13516:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13517:                                 $todeletedir{$prefix.$path} = 1;
                   13518:                             } else {
                   13519:                                 $todelete{$prefix.$path} = 1;
                   13520:                             }
1.1055    raeburn  13521:                         }
                   13522:                     }
                   13523:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13524:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13525:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13526:                     $docstitle = $env{'form.archive_title_'.$i};
                   13527:                     if ($docstitle eq '') {
                   13528:                         $docstitle = $title;
                   13529:                     }
1.1055    raeburn  13530:                     $outer = 0;
1.1056    raeburn  13531:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13532:                         if (@{$dirorder{$i}} > 0) {
                   13533:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13534:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13535:                                     $outer = $item;
                   13536:                                     last;
                   13537:                                 }
                   13538:                             }
                   13539:                         }
                   13540:                     }
                   13541:                     my ($errtext,$fatal) = 
                   13542:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13543:                                                '/'.$folders{$outer}.'.'.
                   13544:                                                $containers{$outer});
                   13545:                     next if ($fatal);
                   13546:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13547:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13548:                             $mapinner{$i} = time;
1.1055    raeburn  13549:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13550:                             $containers{$i} = 'sequence';
                   13551:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13552:                                       $folders{$i}.'.'.$containers{$i};
                   13553:                             my $newidx = &LONCAPA::map::getresidx();
                   13554:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13555:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13556:                             push(@LONCAPA::map::order,$newidx);
                   13557:                             my ($outtext,$errtext) =
                   13558:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13559:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13560:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13561:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13562:                             unless ($errtext) {
1.1294    raeburn  13563:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13564:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   13565:                                             '</li>'."\n";
1.1067    raeburn  13566:                             }
1.1055    raeburn  13567:                         }
                   13568:                     } else {
                   13569:                         if ($context eq 'coursedocs') {
                   13570:                             my $newidx=&LONCAPA::map::getresidx();
                   13571:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13572:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13573:                                       $title;
1.1294    raeburn  13574:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   13575:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13576:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   13577:                                 }
                   13578:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13579:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13580:                                 }
                   13581:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13582:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   13583:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   13584:                                         unless ($ishome) {
                   13585:                                             my $fetch = "$newdest{$i}/$title";
                   13586:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   13587:                                             $prompttofetch{$fetch} = 1;
                   13588:                                         }
1.1292    raeburn  13589:                                     }
1.1067    raeburn  13590:                                 }
1.1294    raeburn  13591:                                 $LONCAPA::map::resources[$newidx]=
                   13592:                                     $docstitle.':'.$url.':false:normal:res';
                   13593:                                 push(@LONCAPA::map::order, $newidx);
                   13594:                                 my ($outtext,$errtext)=
                   13595:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13596:                                                             $docuname.'/'.$folders{$outer}.
                   13597:                                                             '.'.$containers{$outer},1,1);
                   13598:                                 unless ($errtext) {
                   13599:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13600:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   13601:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   13602:                                                    '</li>'."\n";
                   13603:                                     }
1.1067    raeburn  13604:                                 }
1.1294    raeburn  13605:                             } else {
                   13606:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13607:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  13608:                             }
1.1055    raeburn  13609:                         }
                   13610:                     }
1.1086    raeburn  13611:                 }
                   13612:             } else {
1.1294    raeburn  13613:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13614:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  13615:             }
                   13616:         }
                   13617:         for (my $i=1; $i<=$numitems; $i++) {
                   13618:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13619:             my $path = $env{'form.archive_content_'.$i};
                   13620:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13621:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13622:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13623:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13624:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13625:                         my ($itemidx,$fullpath,$relpath);
                   13626:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13627:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13628:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  13629:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13630:                                     $itemidx = $j;
1.1056    raeburn  13631:                                 }
                   13632:                             }
1.1086    raeburn  13633:                         }
                   13634:                         if ($itemidx eq '') {
                   13635:                             $itemidx =  0;
                   13636:                         } 
                   13637:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13638:                             if ($mapinner{$referrer{$i}}) {
                   13639:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13640:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13641:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13642:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13643:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13644:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13645:                                             if (!-e $fullpath) {
                   13646:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13647:                                             }
                   13648:                                         }
1.1086    raeburn  13649:                                     } else {
                   13650:                                         last;
1.1056    raeburn  13651:                                     }
1.1086    raeburn  13652:                                 }
                   13653:                             }
                   13654:                         } elsif ($newdest{$referrer{$i}}) {
                   13655:                             $fullpath = $newdest{$referrer{$i}};
                   13656:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13657:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13658:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13659:                                     last;
                   13660:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13661:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13662:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13663:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13664:                                         if (!-e $fullpath) {
                   13665:                                             mkdir($fullpath,0755);
1.1056    raeburn  13666:                                         }
                   13667:                                     }
1.1086    raeburn  13668:                                 } else {
                   13669:                                     last;
1.1056    raeburn  13670:                                 }
1.1055    raeburn  13671:                             }
                   13672:                         }
1.1086    raeburn  13673:                         if ($fullpath ne '') {
                   13674:                             if (-e "$prefix$path") {
1.1292    raeburn  13675:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13676:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13677:                                 }
1.1086    raeburn  13678:                             }
                   13679:                             if (-e "$fullpath/$title") {
                   13680:                                 my $showpath;
                   13681:                                 if ($relpath ne '') {
                   13682:                                     $showpath = "$relpath/$title";
                   13683:                                 } else {
                   13684:                                     $showpath = "/$title";
                   13685:                                 } 
1.1294    raeburn  13686:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13687:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13688:                                            '</li>'."\n";
1.1292    raeburn  13689:                                 unless ($ishome) {
                   13690:                                     my $fetch = "$fullpath/$title";
                   13691:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   13692:                                     $prompttofetch{$fetch} = 1;
                   13693:                                 }
1.1086    raeburn  13694:                             }
                   13695:                         }
1.1055    raeburn  13696:                     }
1.1086    raeburn  13697:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13698:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  13699:                                     &HTML::Entities::encode($path,'<>&"'),
                   13700:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13701:                                 '<br />';
1.1055    raeburn  13702:                 }
                   13703:             } else {
1.1294    raeburn  13704:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  13705:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13706:             }
                   13707:         }
                   13708:         if (keys(%todelete)) {
                   13709:             foreach my $key (keys(%todelete)) {
                   13710:                 unlink($key);
1.1066    raeburn  13711:             }
                   13712:         }
                   13713:         if (keys(%todeletedir)) {
                   13714:             foreach my $key (keys(%todeletedir)) {
                   13715:                 rmdir($key);
                   13716:             }
                   13717:         }
                   13718:         foreach my $dir (sort(keys(%is_dir))) {
                   13719:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13720:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13721:             }
                   13722:         }
1.1067    raeburn  13723:         if ($result ne '') {
                   13724:             $output .= '<ul>'."\n".
                   13725:                        $result."\n".
                   13726:                        '</ul>';
                   13727:         }
                   13728:         unless ($ishome) {
                   13729:             my $replicationfail;
                   13730:             foreach my $item (keys(%prompttofetch)) {
                   13731:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13732:                 unless ($fetchresult eq 'ok') {
                   13733:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13734:                 }
                   13735:             }
                   13736:             if ($replicationfail) {
                   13737:                 $output .= '<p class="LC_error">'.
                   13738:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13739:                            $replicationfail.
                   13740:                            '</ul></p>';
                   13741:             }
                   13742:         }
1.1055    raeburn  13743:     } else {
                   13744:         $warning = &mt('No items found in archive.');
                   13745:     }
                   13746:     if ($error) {
                   13747:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13748:                    $error.'</p>'."\n";
                   13749:     }
                   13750:     if ($warning) {
                   13751:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13752:     }
                   13753:     return $output;
                   13754: }
                   13755: 
1.1066    raeburn  13756: sub cleanup_empty_dirs {
                   13757:     my ($path) = @_;
                   13758:     if (($path ne '') && (-d $path)) {
                   13759:         if (opendir(my $dirh,$path)) {
                   13760:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13761:             my $numitems = 0;
                   13762:             foreach my $item (@dircontents) {
                   13763:                 if (-d "$path/$item") {
1.1111    raeburn  13764:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13765:                     if (-e "$path/$item") {
                   13766:                         $numitems ++;
                   13767:                     }
                   13768:                 } else {
                   13769:                     $numitems ++;
                   13770:                 }
                   13771:             }
                   13772:             if ($numitems == 0) {
                   13773:                 rmdir($path);
                   13774:             }
                   13775:             closedir($dirh);
                   13776:         }
                   13777:     }
                   13778:     return;
                   13779: }
                   13780: 
1.41      ng       13781: =pod
1.45      matthew  13782: 
1.1162    raeburn  13783: =item * &get_folder_hierarchy()
1.1068    raeburn  13784: 
                   13785: Provides hierarchy of names of folders/sub-folders containing the current
                   13786: item,
                   13787: 
                   13788: Inputs: 3
                   13789:      - $navmap - navmaps object
                   13790: 
                   13791:      - $map - url for map (either the trigger itself, or map containing
                   13792:                            the resource, which is the trigger).
                   13793: 
                   13794:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13795: 
                   13796: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13797: 
                   13798: =cut
                   13799: 
                   13800: sub get_folder_hierarchy {
                   13801:     my ($navmap,$map,$showitem) = @_;
                   13802:     my @pathitems;
                   13803:     if (ref($navmap)) {
                   13804:         my $mapres = $navmap->getResourceByUrl($map);
                   13805:         if (ref($mapres)) {
                   13806:             my $pcslist = $mapres->map_hierarchy();
                   13807:             if ($pcslist ne '') {
                   13808:                 my @pcs = split(/,/,$pcslist);
                   13809:                 foreach my $pc (@pcs) {
                   13810:                     if ($pc == 1) {
1.1129    raeburn  13811:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13812:                     } else {
                   13813:                         my $res = $navmap->getByMapPc($pc);
                   13814:                         if (ref($res)) {
                   13815:                             my $title = $res->compTitle();
                   13816:                             $title =~ s/\W+/_/g;
                   13817:                             if ($title ne '') {
                   13818:                                 push(@pathitems,$title);
                   13819:                             }
                   13820:                         }
                   13821:                     }
                   13822:                 }
                   13823:             }
1.1071    raeburn  13824:             if ($showitem) {
                   13825:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  13826:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13827:                 } else {
                   13828:                     my $maptitle = $mapres->compTitle();
                   13829:                     $maptitle =~ s/\W+/_/g;
                   13830:                     if ($maptitle ne '') {
                   13831:                         push(@pathitems,$maptitle);
                   13832:                     }
1.1068    raeburn  13833:                 }
                   13834:             }
                   13835:         }
                   13836:     }
                   13837:     return @pathitems;
                   13838: }
                   13839: 
                   13840: =pod
                   13841: 
1.1015    raeburn  13842: =item * &get_turnedin_filepath()
                   13843: 
                   13844: Determines path in a user's portfolio file for storage of files uploaded
                   13845: to a specific essayresponse or dropbox item.
                   13846: 
                   13847: Inputs: 3 required + 1 optional.
                   13848: $symb is symb for resource, $uname and $udom are for current user (required).
                   13849: $caller is optional (can be "submission", if routine is called when storing
                   13850: an upoaded file when "Submit Answer" button was pressed).
                   13851: 
                   13852: Returns array containing $path and $multiresp. 
                   13853: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13854: than one file upload item.  Callers of routine should append partid as a 
                   13855: subdirectory to $path in cases where $multiresp is 1.
                   13856: 
                   13857: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13858: 
                   13859: =cut
                   13860: 
                   13861: sub get_turnedin_filepath {
                   13862:     my ($symb,$uname,$udom,$caller) = @_;
                   13863:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13864:     my $turnindir;
                   13865:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13866:     $turnindir = $userhash{'turnindir'};
                   13867:     my ($path,$multiresp);
                   13868:     if ($turnindir eq '') {
                   13869:         if ($caller eq 'submission') {
                   13870:             $turnindir = &mt('turned in');
                   13871:             $turnindir =~ s/\W+/_/g;
                   13872:             my %newhash = (
                   13873:                             'turnindir' => $turnindir,
                   13874:                           );
                   13875:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13876:         }
                   13877:     }
                   13878:     if ($turnindir ne '') {
                   13879:         $path = '/'.$turnindir.'/';
                   13880:         my ($multipart,$turnin,@pathitems);
                   13881:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13882:         if (defined($navmap)) {
                   13883:             my $mapres = $navmap->getResourceByUrl($map);
                   13884:             if (ref($mapres)) {
                   13885:                 my $pcslist = $mapres->map_hierarchy();
                   13886:                 if ($pcslist ne '') {
                   13887:                     foreach my $pc (split(/,/,$pcslist)) {
                   13888:                         my $res = $navmap->getByMapPc($pc);
                   13889:                         if (ref($res)) {
                   13890:                             my $title = $res->compTitle();
                   13891:                             $title =~ s/\W+/_/g;
                   13892:                             if ($title ne '') {
1.1149    raeburn  13893:                                 if (($pc > 1) && (length($title) > 12)) {
                   13894:                                     $title = substr($title,0,12);
                   13895:                                 }
1.1015    raeburn  13896:                                 push(@pathitems,$title);
                   13897:                             }
                   13898:                         }
                   13899:                     }
                   13900:                 }
                   13901:                 my $maptitle = $mapres->compTitle();
                   13902:                 $maptitle =~ s/\W+/_/g;
                   13903:                 if ($maptitle ne '') {
1.1149    raeburn  13904:                     if (length($maptitle) > 12) {
                   13905:                         $maptitle = substr($maptitle,0,12);
                   13906:                     }
1.1015    raeburn  13907:                     push(@pathitems,$maptitle);
                   13908:                 }
                   13909:                 unless ($env{'request.state'} eq 'construct') {
                   13910:                     my $res = $navmap->getBySymb($symb);
                   13911:                     if (ref($res)) {
                   13912:                         my $partlist = $res->parts();
                   13913:                         my $totaluploads = 0;
                   13914:                         if (ref($partlist) eq 'ARRAY') {
                   13915:                             foreach my $part (@{$partlist}) {
                   13916:                                 my @types = $res->responseType($part);
                   13917:                                 my @ids = $res->responseIds($part);
                   13918:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13919:                                     if ($types[$i] eq 'essay') {
                   13920:                                         my $partid = $part.'_'.$ids[$i];
                   13921:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13922:                                             $totaluploads ++;
                   13923:                                         }
                   13924:                                     }
                   13925:                                 }
                   13926:                             }
                   13927:                             if ($totaluploads > 1) {
                   13928:                                 $multiresp = 1;
                   13929:                             }
                   13930:                         }
                   13931:                     }
                   13932:                 }
                   13933:             } else {
                   13934:                 return;
                   13935:             }
                   13936:         } else {
                   13937:             return;
                   13938:         }
                   13939:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13940:         $restitle =~ s/\W+/_/g;
                   13941:         if ($restitle eq '') {
                   13942:             $restitle = ($resurl =~ m{/[^/]+$});
                   13943:             if ($restitle eq '') {
                   13944:                 $restitle = time;
                   13945:             }
                   13946:         }
1.1149    raeburn  13947:         if (length($restitle) > 12) {
                   13948:             $restitle = substr($restitle,0,12);
                   13949:         }
1.1015    raeburn  13950:         push(@pathitems,$restitle);
                   13951:         $path .= join('/',@pathitems);
                   13952:     }
                   13953:     return ($path,$multiresp);
                   13954: }
                   13955: 
                   13956: =pod
                   13957: 
1.464     albertel 13958: =back
1.41      ng       13959: 
1.112     bowersj2 13960: =head1 CSV Upload/Handling functions
1.38      albertel 13961: 
1.41      ng       13962: =over 4
                   13963: 
1.648     raeburn  13964: =item * &upfile_store($r)
1.41      ng       13965: 
                   13966: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13967: needs $env{'form.upfile'}
1.41      ng       13968: returns $datatoken to be put into hidden field
                   13969: 
                   13970: =cut
1.31      albertel 13971: 
                   13972: sub upfile_store {
                   13973:     my $r=shift;
1.258     albertel 13974:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13975:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13976:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13977:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13978: 
1.1299    raeburn  13979:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   13980:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   13981:                                      time.'_'.$$);
                   13982:     return if ($datatoken eq '');
                   13983: 
1.31      albertel 13984:     {
1.158     raeburn  13985:         my $datafile = $r->dir_config('lonDaemons').
                   13986:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  13987:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 13988:             print $fh $env{'form.upfile'};
1.158     raeburn  13989:             close($fh);
                   13990:         }
1.31      albertel 13991:     }
                   13992:     return $datatoken;
                   13993: }
                   13994: 
1.56      matthew  13995: =pod
                   13996: 
1.1290    raeburn  13997: =item * &load_tmp_file($r,$datatoken)
1.41      ng       13998: 
                   13999: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  14000: $datatoken is the name to assign to the temporary file.
1.258     albertel 14001: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14002: 
                   14003: =cut
1.31      albertel 14004: 
                   14005: sub load_tmp_file {
1.1290    raeburn  14006:     my ($r,$datatoken) = @_;
                   14007:     return if ($datatoken eq '');
1.31      albertel 14008:     my @studentdata=();
                   14009:     {
1.158     raeburn  14010:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  14011:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14012:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14013:             @studentdata=<$fh>;
                   14014:             close($fh);
                   14015:         }
1.31      albertel 14016:     }
1.258     albertel 14017:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14018: }
                   14019: 
1.1290    raeburn  14020: sub valid_datatoken {
                   14021:     my ($datatoken) = @_;
1.1325    raeburn  14022:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  14023:         return $datatoken;
                   14024:     }
                   14025:     return;
                   14026: }
                   14027: 
1.56      matthew  14028: =pod
                   14029: 
1.648     raeburn  14030: =item * &upfile_record_sep()
1.41      ng       14031: 
                   14032: Separate uploaded file into records
                   14033: returns array of records,
1.258     albertel 14034: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14035: 
                   14036: =cut
1.31      albertel 14037: 
                   14038: sub upfile_record_sep {
1.258     albertel 14039:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14040:     } else {
1.248     albertel 14041: 	my @records;
1.258     albertel 14042: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14043: 	    if ($line=~/^\s*$/) { next; }
                   14044: 	    push(@records,$line);
                   14045: 	}
                   14046: 	return @records;
1.31      albertel 14047:     }
                   14048: }
                   14049: 
1.56      matthew  14050: =pod
                   14051: 
1.648     raeburn  14052: =item * &record_sep($record)
1.41      ng       14053: 
1.258     albertel 14054: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14055: 
                   14056: =cut
                   14057: 
1.263     www      14058: sub takeleft {
                   14059:     my $index=shift;
                   14060:     return substr('0000'.$index,-4,4);
                   14061: }
                   14062: 
1.31      albertel 14063: sub record_sep {
                   14064:     my $record=shift;
                   14065:     my %components=();
1.258     albertel 14066:     if ($env{'form.upfiletype'} eq 'xml') {
                   14067:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14068:         my $i=0;
1.356     albertel 14069:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14070:             $field=~s/^(\"|\')//;
                   14071:             $field=~s/(\"|\')$//;
1.263     www      14072:             $components{&takeleft($i)}=$field;
1.31      albertel 14073:             $i++;
                   14074:         }
1.258     albertel 14075:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14076:         my $i=0;
1.356     albertel 14077:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14078:             $field=~s/^(\"|\')//;
                   14079:             $field=~s/(\"|\')$//;
1.263     www      14080:             $components{&takeleft($i)}=$field;
1.31      albertel 14081:             $i++;
                   14082:         }
                   14083:     } else {
1.561     www      14084:         my $separator=',';
1.480     banghart 14085:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14086:             $separator=';';
1.480     banghart 14087:         }
1.31      albertel 14088:         my $i=0;
1.561     www      14089: # the character we are looking for to indicate the end of a quote or a record 
                   14090:         my $looking_for=$separator;
                   14091: # do not add the characters to the fields
                   14092:         my $ignore=0;
                   14093: # we just encountered a separator (or the beginning of the record)
                   14094:         my $just_found_separator=1;
                   14095: # store the field we are working on here
                   14096:         my $field='';
                   14097: # work our way through all characters in record
                   14098:         foreach my $character ($record=~/(.)/g) {
                   14099:             if ($character eq $looking_for) {
                   14100:                if ($character ne $separator) {
                   14101: # Found the end of a quote, again looking for separator
                   14102:                   $looking_for=$separator;
                   14103:                   $ignore=1;
                   14104:                } else {
                   14105: # Found a separator, store away what we got
                   14106:                   $components{&takeleft($i)}=$field;
                   14107: 	          $i++;
                   14108:                   $just_found_separator=1;
                   14109:                   $ignore=0;
                   14110:                   $field='';
                   14111:                }
                   14112:                next;
                   14113:             }
                   14114: # single or double quotation marks after a separator indicate beginning of a quote
                   14115: # we are now looking for the end of the quote and need to ignore separators
                   14116:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14117:                $looking_for=$character;
                   14118:                next;
                   14119:             }
                   14120: # ignore would be true after we reached the end of a quote
                   14121:             if ($ignore) { next; }
                   14122:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14123:             $field.=$character;
                   14124:             $just_found_separator=0; 
1.31      albertel 14125:         }
1.561     www      14126: # catch the very last entry, since we never encountered the separator
                   14127:         $components{&takeleft($i)}=$field;
1.31      albertel 14128:     }
                   14129:     return %components;
                   14130: }
                   14131: 
1.144     matthew  14132: ######################################################
                   14133: ######################################################
                   14134: 
1.56      matthew  14135: =pod
                   14136: 
1.648     raeburn  14137: =item * &upfile_select_html()
1.41      ng       14138: 
1.144     matthew  14139: Return HTML code to select a file from the users machine and specify 
                   14140: the file type.
1.41      ng       14141: 
                   14142: =cut
                   14143: 
1.144     matthew  14144: ######################################################
                   14145: ######################################################
1.31      albertel 14146: sub upfile_select_html {
1.144     matthew  14147:     my %Types = (
                   14148:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14149:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14150:                  space => &mt('Space separated'),
                   14151:                  tab   => &mt('Tabulator separated'),
                   14152: #                 xml   => &mt('HTML/XML'),
                   14153:                  );
                   14154:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14155:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14156:     foreach my $type (sort(keys(%Types))) {
                   14157:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14158:     }
                   14159:     $Str .= "</select>\n";
                   14160:     return $Str;
1.31      albertel 14161: }
                   14162: 
1.301     albertel 14163: sub get_samples {
                   14164:     my ($records,$toget) = @_;
                   14165:     my @samples=({});
                   14166:     my $got=0;
                   14167:     foreach my $rec (@$records) {
                   14168: 	my %temp = &record_sep($rec);
                   14169: 	if (! grep(/\S/, values(%temp))) { next; }
                   14170: 	if (%temp) {
                   14171: 	    $samples[$got]=\%temp;
                   14172: 	    $got++;
                   14173: 	    if ($got == $toget) { last; }
                   14174: 	}
                   14175:     }
                   14176:     return \@samples;
                   14177: }
                   14178: 
1.144     matthew  14179: ######################################################
                   14180: ######################################################
                   14181: 
1.56      matthew  14182: =pod
                   14183: 
1.648     raeburn  14184: =item * &csv_print_samples($r,$records)
1.41      ng       14185: 
                   14186: Prints a table of sample values from each column uploaded $r is an
                   14187: Apache Request ref, $records is an arrayref from
                   14188: &Apache::loncommon::upfile_record_sep
                   14189: 
                   14190: =cut
                   14191: 
1.144     matthew  14192: ######################################################
                   14193: ######################################################
1.31      albertel 14194: sub csv_print_samples {
                   14195:     my ($r,$records) = @_;
1.662     bisitz   14196:     my $samples = &get_samples($records,5);
1.301     albertel 14197: 
1.594     raeburn  14198:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14199:               &start_data_table_header_row());
1.356     albertel 14200:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14201:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14202:     $r->print(&end_data_table_header_row());
1.301     albertel 14203:     foreach my $hash (@$samples) {
1.594     raeburn  14204: 	$r->print(&start_data_table_row());
1.356     albertel 14205: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14206: 	    $r->print('<td>');
1.356     albertel 14207: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14208: 	    $r->print('</td>');
                   14209: 	}
1.594     raeburn  14210: 	$r->print(&end_data_table_row());
1.31      albertel 14211:     }
1.594     raeburn  14212:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14213: }
                   14214: 
1.144     matthew  14215: ######################################################
                   14216: ######################################################
                   14217: 
1.56      matthew  14218: =pod
                   14219: 
1.648     raeburn  14220: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14221: 
                   14222: Prints a table to create associations between values and table columns.
1.144     matthew  14223: 
1.41      ng       14224: $r is an Apache Request ref,
                   14225: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14226: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14227: 
                   14228: =cut
                   14229: 
1.144     matthew  14230: ######################################################
                   14231: ######################################################
1.31      albertel 14232: sub csv_print_select_table {
                   14233:     my ($r,$records,$d) = @_;
1.301     albertel 14234:     my $i=0;
                   14235:     my $samples = &get_samples($records,1);
1.144     matthew  14236:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14237: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14238:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14239:               '<th>'.&mt('Column').'</th>'.
                   14240:               &end_data_table_header_row()."\n");
1.356     albertel 14241:     foreach my $array_ref (@$d) {
                   14242: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14243: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14244: 
1.875     bisitz   14245: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14246: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14247: 	$r->print('<option value="none"></option>');
1.356     albertel 14248: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14249: 	    $r->print('<option value="'.$sample.'"'.
                   14250:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14251:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14252: 	}
1.594     raeburn  14253: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14254: 	$i++;
                   14255:     }
1.594     raeburn  14256:     $r->print(&end_data_table());
1.31      albertel 14257:     $i--;
                   14258:     return $i;
                   14259: }
1.56      matthew  14260: 
1.144     matthew  14261: ######################################################
                   14262: ######################################################
                   14263: 
1.56      matthew  14264: =pod
1.31      albertel 14265: 
1.648     raeburn  14266: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14267: 
                   14268: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14269: 
                   14270: $r is an Apache Request ref,
                   14271: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14272: $d is an array of 2 element arrays (internal name, displayed name)
                   14273: 
                   14274: =cut
                   14275: 
1.144     matthew  14276: ######################################################
                   14277: ######################################################
1.31      albertel 14278: sub csv_samples_select_table {
                   14279:     my ($r,$records,$d) = @_;
                   14280:     my $i=0;
1.144     matthew  14281:     #
1.662     bisitz   14282:     my $max_samples = 5;
                   14283:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14284:     $r->print(&start_data_table().
                   14285:               &start_data_table_header_row().'<th>'.
                   14286:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14287:               &end_data_table_header_row());
1.301     albertel 14288: 
                   14289:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14290: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14291: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14292: 	foreach my $option (@$d) {
                   14293: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14294: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14295:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14296:                       $display.'</option>');
1.31      albertel 14297: 	}
                   14298: 	$r->print('</select></td><td>');
1.662     bisitz   14299: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14300: 	    if (defined($samples->[$line]{$key})) { 
                   14301: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14302: 	    }
                   14303: 	}
1.594     raeburn  14304: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14305: 	$i++;
                   14306:     }
1.594     raeburn  14307:     $r->print(&end_data_table());
1.31      albertel 14308:     $i--;
                   14309:     return($i);
1.115     matthew  14310: }
                   14311: 
1.144     matthew  14312: ######################################################
                   14313: ######################################################
                   14314: 
1.115     matthew  14315: =pod
                   14316: 
1.648     raeburn  14317: =item * &clean_excel_name($name)
1.115     matthew  14318: 
                   14319: Returns a replacement for $name which does not contain any illegal characters.
                   14320: 
                   14321: =cut
                   14322: 
1.144     matthew  14323: ######################################################
                   14324: ######################################################
1.115     matthew  14325: sub clean_excel_name {
                   14326:     my ($name) = @_;
                   14327:     $name =~ s/[:\*\?\/\\]//g;
                   14328:     if (length($name) > 31) {
                   14329:         $name = substr($name,0,31);
                   14330:     }
                   14331:     return $name;
1.25      albertel 14332: }
1.84      albertel 14333: 
1.85      albertel 14334: =pod
                   14335: 
1.648     raeburn  14336: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14337: 
                   14338: Returns either 1 or undef
                   14339: 
                   14340: 1 if the part is to be hidden, undef if it is to be shown
                   14341: 
                   14342: Arguments are:
                   14343: 
                   14344: $id the id of the part to be checked
                   14345: $symb, optional the symb of the resource to check
                   14346: $udom, optional the domain of the user to check for
                   14347: $uname, optional the username of the user to check for
                   14348: 
                   14349: =cut
1.84      albertel 14350: 
                   14351: sub check_if_partid_hidden {
                   14352:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14353:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14354: 					 $symb,$udom,$uname);
1.141     albertel 14355:     my $truth=1;
                   14356:     #if the string starts with !, then the list is the list to show not hide
                   14357:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14358:     my @hiddenlist=split(/,/,$hiddenparts);
                   14359:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14360: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14361:     }
1.141     albertel 14362:     return !$truth;
1.84      albertel 14363: }
1.127     matthew  14364: 
1.138     matthew  14365: 
                   14366: ############################################################
                   14367: ############################################################
                   14368: 
                   14369: =pod
                   14370: 
1.157     matthew  14371: =back 
                   14372: 
1.138     matthew  14373: =head1 cgi-bin script and graphing routines
                   14374: 
1.157     matthew  14375: =over 4
                   14376: 
1.648     raeburn  14377: =item * &get_cgi_id()
1.138     matthew  14378: 
                   14379: Inputs: none
                   14380: 
                   14381: Returns an id which can be used to pass environment variables
                   14382: to various cgi-bin scripts.  These environment variables will
                   14383: be removed from the users environment after a given time by
                   14384: the routine &Apache::lonnet::transfer_profile_to_env.
                   14385: 
                   14386: =cut
                   14387: 
                   14388: ############################################################
                   14389: ############################################################
1.152     albertel 14390: my $uniq=0;
1.136     matthew  14391: sub get_cgi_id {
1.154     albertel 14392:     $uniq=($uniq+1)%100000;
1.280     albertel 14393:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14394: }
                   14395: 
1.127     matthew  14396: ############################################################
                   14397: ############################################################
                   14398: 
                   14399: =pod
                   14400: 
1.648     raeburn  14401: =item * &DrawBarGraph()
1.127     matthew  14402: 
1.138     matthew  14403: Facilitates the plotting of data in a (stacked) bar graph.
                   14404: Puts plot definition data into the users environment in order for 
                   14405: graph.png to plot it.  Returns an <img> tag for the plot.
                   14406: The bars on the plot are labeled '1','2',...,'n'.
                   14407: 
                   14408: Inputs:
                   14409: 
                   14410: =over 4
                   14411: 
                   14412: =item $Title: string, the title of the plot
                   14413: 
                   14414: =item $xlabel: string, text describing the X-axis of the plot
                   14415: 
                   14416: =item $ylabel: string, text describing the Y-axis of the plot
                   14417: 
                   14418: =item $Max: scalar, the maximum Y value to use in the plot
                   14419: If $Max is < any data point, the graph will not be rendered.
                   14420: 
1.140     matthew  14421: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14422: they are plotted.  If undefined, default values will be used.
                   14423: 
1.178     matthew  14424: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14425: 
1.138     matthew  14426: =item @Values: An array of array references.  Each array reference holds data
                   14427: to be plotted in a stacked bar chart.
                   14428: 
1.239     matthew  14429: =item If the final element of @Values is a hash reference the key/value
                   14430: pairs will be added to the graph definition.
                   14431: 
1.138     matthew  14432: =back
                   14433: 
                   14434: Returns:
                   14435: 
                   14436: An <img> tag which references graph.png and the appropriate identifying
                   14437: information for the plot.
                   14438: 
1.127     matthew  14439: =cut
                   14440: 
                   14441: ############################################################
                   14442: ############################################################
1.134     matthew  14443: sub DrawBarGraph {
1.178     matthew  14444:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14445:     #
                   14446:     if (! defined($colors)) {
                   14447:         $colors = ['#33ff00', 
                   14448:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14449:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14450:                   ]; 
                   14451:     }
1.228     matthew  14452:     my $extra_settings = {};
                   14453:     if (ref($Values[-1]) eq 'HASH') {
                   14454:         $extra_settings = pop(@Values);
                   14455:     }
1.127     matthew  14456:     #
1.136     matthew  14457:     my $identifier = &get_cgi_id();
                   14458:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14459:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14460:         return '';
                   14461:     }
1.225     matthew  14462:     #
                   14463:     my @Labels;
                   14464:     if (defined($labels)) {
                   14465:         @Labels = @$labels;
                   14466:     } else {
                   14467:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  14468:             push(@Labels,$i+1);
1.225     matthew  14469:         }
                   14470:     }
                   14471:     #
1.129     matthew  14472:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14473:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14474:     my %ValuesHash;
                   14475:     my $NumSets=1;
                   14476:     foreach my $array (@Values) {
                   14477:         next if (! ref($array));
1.136     matthew  14478:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14479:             join(',',@$array);
1.129     matthew  14480:     }
1.127     matthew  14481:     #
1.136     matthew  14482:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14483:     if ($NumBars < 3) {
                   14484:         $width = 120+$NumBars*32;
1.220     matthew  14485:         $xskip = 1;
1.225     matthew  14486:         $bar_width = 30;
                   14487:     } elsif ($NumBars < 5) {
                   14488:         $width = 120+$NumBars*20;
                   14489:         $xskip = 1;
                   14490:         $bar_width = 20;
1.220     matthew  14491:     } elsif ($NumBars < 10) {
1.136     matthew  14492:         $width = 120+$NumBars*15;
                   14493:         $xskip = 1;
                   14494:         $bar_width = 15;
                   14495:     } elsif ($NumBars <= 25) {
                   14496:         $width = 120+$NumBars*11;
                   14497:         $xskip = 5;
                   14498:         $bar_width = 8;
                   14499:     } elsif ($NumBars <= 50) {
                   14500:         $width = 120+$NumBars*8;
                   14501:         $xskip = 5;
                   14502:         $bar_width = 4;
                   14503:     } else {
                   14504:         $width = 120+$NumBars*8;
                   14505:         $xskip = 5;
                   14506:         $bar_width = 4;
                   14507:     }
                   14508:     #
1.137     matthew  14509:     $Max = 1 if ($Max < 1);
                   14510:     if ( int($Max) < $Max ) {
                   14511:         $Max++;
                   14512:         $Max = int($Max);
                   14513:     }
1.127     matthew  14514:     $Title  = '' if (! defined($Title));
                   14515:     $xlabel = '' if (! defined($xlabel));
                   14516:     $ylabel = '' if (! defined($ylabel));
1.369     www      14517:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14518:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14519:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14520:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14521:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14522:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14523:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14524:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14525:     $ValuesHash{$id.'.height'}   = $height;
                   14526:     $ValuesHash{$id.'.width'}    = $width;
                   14527:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14528:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14529:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14530:     #
1.228     matthew  14531:     # Deal with other parameters
                   14532:     while (my ($key,$value) = each(%$extra_settings)) {
                   14533:         $ValuesHash{$id.'.'.$key} = $value;
                   14534:     }
                   14535:     #
1.646     raeburn  14536:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14537:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14538: }
                   14539: 
                   14540: ############################################################
                   14541: ############################################################
                   14542: 
                   14543: =pod
                   14544: 
1.648     raeburn  14545: =item * &DrawXYGraph()
1.137     matthew  14546: 
1.138     matthew  14547: Facilitates the plotting of data in an XY graph.
                   14548: Puts plot definition data into the users environment in order for 
                   14549: graph.png to plot it.  Returns an <img> tag for the plot.
                   14550: 
                   14551: Inputs:
                   14552: 
                   14553: =over 4
                   14554: 
                   14555: =item $Title: string, the title of the plot
                   14556: 
                   14557: =item $xlabel: string, text describing the X-axis of the plot
                   14558: 
                   14559: =item $ylabel: string, text describing the Y-axis of the plot
                   14560: 
                   14561: =item $Max: scalar, the maximum Y value to use in the plot
                   14562: If $Max is < any data point, the graph will not be rendered.
                   14563: 
                   14564: =item $colors: Array ref containing the hex color codes for the data to be 
                   14565: plotted in.  If undefined, default values will be used.
                   14566: 
                   14567: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14568: 
                   14569: =item $Ydata: Array ref containing Array refs.  
1.185     www      14570: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14571: 
                   14572: =item %Values: hash indicating or overriding any default values which are 
                   14573: passed to graph.png.  
                   14574: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14575: 
                   14576: =back
                   14577: 
                   14578: Returns:
                   14579: 
                   14580: An <img> tag which references graph.png and the appropriate identifying
                   14581: information for the plot.
                   14582: 
1.137     matthew  14583: =cut
                   14584: 
                   14585: ############################################################
                   14586: ############################################################
                   14587: sub DrawXYGraph {
                   14588:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14589:     #
                   14590:     # Create the identifier for the graph
                   14591:     my $identifier = &get_cgi_id();
                   14592:     my $id = 'cgi.'.$identifier;
                   14593:     #
                   14594:     $Title  = '' if (! defined($Title));
                   14595:     $xlabel = '' if (! defined($xlabel));
                   14596:     $ylabel = '' if (! defined($ylabel));
                   14597:     my %ValuesHash = 
                   14598:         (
1.369     www      14599:          $id.'.title'  => &escape($Title),
                   14600:          $id.'.xlabel' => &escape($xlabel),
                   14601:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14602:          $id.'.y_max_value'=> $Max,
                   14603:          $id.'.labels'     => join(',',@$Xlabels),
                   14604:          $id.'.PlotType'   => 'XY',
                   14605:          );
                   14606:     #
                   14607:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14608:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14609:     }
                   14610:     #
                   14611:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14612:         return '';
                   14613:     }
                   14614:     my $NumSets=1;
1.138     matthew  14615:     foreach my $array (@{$Ydata}){
1.137     matthew  14616:         next if (! ref($array));
                   14617:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14618:     }
1.138     matthew  14619:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14620:     #
                   14621:     # Deal with other parameters
                   14622:     while (my ($key,$value) = each(%Values)) {
                   14623:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14624:     }
                   14625:     #
1.646     raeburn  14626:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14627:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14628: }
                   14629: 
                   14630: ############################################################
                   14631: ############################################################
                   14632: 
                   14633: =pod
                   14634: 
1.648     raeburn  14635: =item * &DrawXYYGraph()
1.138     matthew  14636: 
                   14637: Facilitates the plotting of data in an XY graph with two Y axes.
                   14638: Puts plot definition data into the users environment in order for 
                   14639: graph.png to plot it.  Returns an <img> tag for the plot.
                   14640: 
                   14641: Inputs:
                   14642: 
                   14643: =over 4
                   14644: 
                   14645: =item $Title: string, the title of the plot
                   14646: 
                   14647: =item $xlabel: string, text describing the X-axis of the plot
                   14648: 
                   14649: =item $ylabel: string, text describing the Y-axis of the plot
                   14650: 
                   14651: =item $colors: Array ref containing the hex color codes for the data to be 
                   14652: plotted in.  If undefined, default values will be used.
                   14653: 
                   14654: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14655: 
                   14656: =item $Ydata1: The first data set
                   14657: 
                   14658: =item $Min1: The minimum value of the left Y-axis
                   14659: 
                   14660: =item $Max1: The maximum value of the left Y-axis
                   14661: 
                   14662: =item $Ydata2: The second data set
                   14663: 
                   14664: =item $Min2: The minimum value of the right Y-axis
                   14665: 
                   14666: =item $Max2: The maximum value of the left Y-axis
                   14667: 
                   14668: =item %Values: hash indicating or overriding any default values which are 
                   14669: passed to graph.png.  
                   14670: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14671: 
                   14672: =back
                   14673: 
                   14674: Returns:
                   14675: 
                   14676: An <img> tag which references graph.png and the appropriate identifying
                   14677: information for the plot.
1.136     matthew  14678: 
                   14679: =cut
                   14680: 
                   14681: ############################################################
                   14682: ############################################################
1.137     matthew  14683: sub DrawXYYGraph {
                   14684:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14685:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14686:     #
                   14687:     # Create the identifier for the graph
                   14688:     my $identifier = &get_cgi_id();
                   14689:     my $id = 'cgi.'.$identifier;
                   14690:     #
                   14691:     $Title  = '' if (! defined($Title));
                   14692:     $xlabel = '' if (! defined($xlabel));
                   14693:     $ylabel = '' if (! defined($ylabel));
                   14694:     my %ValuesHash = 
                   14695:         (
1.369     www      14696:          $id.'.title'  => &escape($Title),
                   14697:          $id.'.xlabel' => &escape($xlabel),
                   14698:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14699:          $id.'.labels' => join(',',@$Xlabels),
                   14700:          $id.'.PlotType' => 'XY',
                   14701:          $id.'.NumSets' => 2,
1.137     matthew  14702:          $id.'.two_axes' => 1,
                   14703:          $id.'.y1_max_value' => $Max1,
                   14704:          $id.'.y1_min_value' => $Min1,
                   14705:          $id.'.y2_max_value' => $Max2,
                   14706:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14707:          );
                   14708:     #
1.137     matthew  14709:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14710:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14711:     }
                   14712:     #
                   14713:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14714:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14715:         return '';
                   14716:     }
                   14717:     my $NumSets=1;
1.137     matthew  14718:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14719:         next if (! ref($array));
                   14720:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14721:     }
                   14722:     #
                   14723:     # Deal with other parameters
                   14724:     while (my ($key,$value) = each(%Values)) {
                   14725:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14726:     }
                   14727:     #
1.646     raeburn  14728:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14729:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14730: }
                   14731: 
                   14732: ############################################################
                   14733: ############################################################
                   14734: 
                   14735: =pod
                   14736: 
1.157     matthew  14737: =back 
                   14738: 
1.139     matthew  14739: =head1 Statistics helper routines?  
                   14740: 
                   14741: Bad place for them but what the hell.
                   14742: 
1.157     matthew  14743: =over 4
                   14744: 
1.648     raeburn  14745: =item * &chartlink()
1.139     matthew  14746: 
                   14747: Returns a link to the chart for a specific student.  
                   14748: 
                   14749: Inputs:
                   14750: 
                   14751: =over 4
                   14752: 
                   14753: =item $linktext: The text of the link
                   14754: 
                   14755: =item $sname: The students username
                   14756: 
                   14757: =item $sdomain: The students domain
                   14758: 
                   14759: =back
                   14760: 
1.157     matthew  14761: =back
                   14762: 
1.139     matthew  14763: =cut
                   14764: 
                   14765: ############################################################
                   14766: ############################################################
                   14767: sub chartlink {
                   14768:     my ($linktext, $sname, $sdomain) = @_;
                   14769:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14770:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14771:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14772:        '">'.$linktext.'</a>';
1.153     matthew  14773: }
                   14774: 
                   14775: #######################################################
                   14776: #######################################################
                   14777: 
                   14778: =pod
                   14779: 
                   14780: =head1 Course Environment Routines
1.157     matthew  14781: 
                   14782: =over 4
1.153     matthew  14783: 
1.648     raeburn  14784: =item * &restore_course_settings()
1.153     matthew  14785: 
1.648     raeburn  14786: =item * &store_course_settings()
1.153     matthew  14787: 
                   14788: Restores/Store indicated form parameters from the course environment.
                   14789: Will not overwrite existing values of the form parameters.
                   14790: 
                   14791: Inputs: 
                   14792: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14793: 
                   14794: a hash ref describing the data to be stored.  For example:
                   14795:    
                   14796: %Save_Parameters = ('Status' => 'scalar',
                   14797:     'chartoutputmode' => 'scalar',
                   14798:     'chartoutputdata' => 'scalar',
                   14799:     'Section' => 'array',
1.373     raeburn  14800:     'Group' => 'array',
1.153     matthew  14801:     'StudentData' => 'array',
                   14802:     'Maps' => 'array');
                   14803: 
                   14804: Returns: both routines return nothing
                   14805: 
1.631     raeburn  14806: =back
                   14807: 
1.153     matthew  14808: =cut
                   14809: 
                   14810: #######################################################
                   14811: #######################################################
                   14812: sub store_course_settings {
1.496     albertel 14813:     return &store_settings($env{'request.course.id'},@_);
                   14814: }
                   14815: 
                   14816: sub store_settings {
1.153     matthew  14817:     # save to the environment
                   14818:     # appenv the same items, just to be safe
1.300     albertel 14819:     my $udom  = $env{'user.domain'};
                   14820:     my $uname = $env{'user.name'};
1.496     albertel 14821:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14822:     my %SaveHash;
                   14823:     my %AppHash;
                   14824:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14825:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14826:         my $envname = 'environment.'.$basename;
1.258     albertel 14827:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14828:             # Save this value away
                   14829:             if ($type eq 'scalar' &&
1.258     albertel 14830:                 (! exists($env{$envname}) || 
                   14831:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14832:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14833:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14834:             } elsif ($type eq 'array') {
                   14835:                 my $stored_form;
1.258     albertel 14836:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14837:                     $stored_form = join(',',
                   14838:                                         map {
1.369     www      14839:                                             &escape($_);
1.258     albertel 14840:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14841:                 } else {
                   14842:                     $stored_form = 
1.369     www      14843:                         &escape($env{'form.'.$setting});
1.153     matthew  14844:                 }
                   14845:                 # Determine if the array contents are the same.
1.258     albertel 14846:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14847:                     $SaveHash{$basename} = $stored_form;
                   14848:                     $AppHash{$envname}   = $stored_form;
                   14849:                 }
                   14850:             }
                   14851:         }
                   14852:     }
                   14853:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14854:                                           $udom,$uname);
1.153     matthew  14855:     if ($put_result !~ /^(ok|delayed)/) {
                   14856:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14857:                                  'got error:'.$put_result);
                   14858:     }
                   14859:     # Make sure these settings stick around in this session, too
1.646     raeburn  14860:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14861:     return;
                   14862: }
                   14863: 
                   14864: sub restore_course_settings {
1.499     albertel 14865:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14866: }
                   14867: 
                   14868: sub restore_settings {
                   14869:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14870:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14871:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14872:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14873:             '.'.$setting;
1.258     albertel 14874:         if (exists($env{$envname})) {
1.153     matthew  14875:             if ($type eq 'scalar') {
1.258     albertel 14876:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14877:             } elsif ($type eq 'array') {
1.258     albertel 14878:                 $env{'form.'.$setting} = [ 
1.153     matthew  14879:                                            map { 
1.369     www      14880:                                                &unescape($_); 
1.258     albertel 14881:                                            } split(',',$env{$envname})
1.153     matthew  14882:                                            ];
                   14883:             }
                   14884:         }
                   14885:     }
1.127     matthew  14886: }
                   14887: 
1.618     raeburn  14888: #######################################################
                   14889: #######################################################
                   14890: 
                   14891: =pod
                   14892: 
                   14893: =head1 Domain E-mail Routines  
                   14894: 
                   14895: =over 4
                   14896: 
1.648     raeburn  14897: =item * &build_recipient_list()
1.618     raeburn  14898: 
1.1144    raeburn  14899: Build recipient lists for following types of e-mail:
1.766     raeburn  14900: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  14901: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14902: module change checking, student/employee ID conflict checks, as
                   14903: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14904: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14905: 
                   14906: Inputs:
1.619     raeburn  14907: defmail (scalar - email address of default recipient), 
1.1144    raeburn  14908: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14909: requestsmail, updatesmail, or idconflictsmail).
                   14910: 
1.619     raeburn  14911: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  14912: 
1.619     raeburn  14913: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  14914: i.e., predates configuration by DC via domainprefs.pm
                   14915: 
                   14916: $requname username of requester (if mailing type is helpdeskmail)
                   14917: 
                   14918: $requdom domain of requester (if mailing type is helpdeskmail)
                   14919: 
                   14920: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   14921: 
1.618     raeburn  14922: 
1.655     raeburn  14923: Returns: comma separated list of addresses to which to send e-mail.
                   14924: 
                   14925: =back
1.618     raeburn  14926: 
                   14927: =cut
                   14928: 
                   14929: ############################################################
                   14930: ############################################################
                   14931: sub build_recipient_list {
1.1297    raeburn  14932:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  14933:     my @recipients;
1.1270    raeburn  14934:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14935:     my %domconfig =
1.1270    raeburn  14936:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14937:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14938:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14939:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14940:                 my @contacts = ('adminemail','supportemail');
                   14941:                 foreach my $item (@contacts) {
                   14942:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14943:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14944:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14945:                             push(@recipients,$addr);
                   14946:                         }
1.619     raeburn  14947:                     }
1.1270    raeburn  14948:                 }
                   14949:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14950:                 if ($mailing eq 'helpdeskmail') {
                   14951:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14952:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14953:                         my @ok_bccs;
                   14954:                         foreach my $bcc (@bccs) {
                   14955:                             $bcc =~ s/^\s+//g;
                   14956:                             $bcc =~ s/\s+$//g;
                   14957:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14958:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14959:                                     push(@ok_bccs,$bcc);
                   14960:                                 }
                   14961:                             }
                   14962:                         }
                   14963:                         if (@ok_bccs > 0) {
                   14964:                             $allbcc = join(', ',@ok_bccs);
                   14965:                         }
                   14966:                     }
                   14967:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14968:                 }
                   14969:             }
1.766     raeburn  14970:         } elsif ($origmail ne '') {
1.1270    raeburn  14971:             $lastresort = $origmail;
1.618     raeburn  14972:         }
1.1297    raeburn  14973:         if ($mailing eq 'helpdeskmail') {
                   14974:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   14975:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   14976:                 my ($inststatus,$inststatus_checked);
                   14977:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   14978:                     ($env{'user.domain'} ne 'public')) {
                   14979:                     $inststatus_checked = 1;
                   14980:                     $inststatus = $env{'environment.inststatus'};
                   14981:                 }
                   14982:                 unless ($inststatus_checked) {
                   14983:                     if (($requname ne '') && ($requdom ne '')) {
                   14984:                         if (($requname =~ /^$match_username$/) &&
                   14985:                             ($requdom =~ /^$match_domain$/) &&
                   14986:                             (&Apache::lonnet::domain($requdom))) {
                   14987:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   14988:                                                                       $requdom);
                   14989:                             unless ($requhome eq 'no_host') {
                   14990:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   14991:                                 $inststatus = $userenv{'inststatus'};
                   14992:                                 $inststatus_checked = 1;
                   14993:                             }
                   14994:                         }
                   14995:                     }
                   14996:                 }
                   14997:                 unless ($inststatus_checked) {
                   14998:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   14999:                         my %srch = (srchby     => 'email',
                   15000:                                     srchdomain => $defdom,
                   15001:                                     srchterm   => $reqemail,
                   15002:                                     srchtype   => 'exact');
                   15003:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15004:                         foreach my $uname (keys(%srch_results)) {
                   15005:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15006:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15007:                                 $inststatus_checked = 1;
                   15008:                                 last;
                   15009:                             }
                   15010:                         }
                   15011:                         unless ($inststatus_checked) {
                   15012:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15013:                             if ($dirsrchres eq 'ok') {
                   15014:                                 foreach my $uname (keys(%srch_results)) {
                   15015:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15016:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15017:                                         $inststatus_checked = 1;
                   15018:                                         last;
                   15019:                                     }
                   15020:                                 }
                   15021:                             }
                   15022:                         }
                   15023:                     }
                   15024:                 }
                   15025:                 if ($inststatus ne '') {
                   15026:                     foreach my $status (split(/\:/,$inststatus)) {
                   15027:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15028:                             my @contacts = ('adminemail','supportemail');
                   15029:                             foreach my $item (@contacts) {
                   15030:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15031:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15032:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15033:                                         push(@recipients,$addr);
                   15034:                                     }
                   15035:                                 }
                   15036:                             }
                   15037:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15038:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15039:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15040:                                 my @ok_bccs;
                   15041:                                 foreach my $bcc (@bccs) {
                   15042:                                     $bcc =~ s/^\s+//g;
                   15043:                                     $bcc =~ s/\s+$//g;
                   15044:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15045:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15046:                                             push(@ok_bccs,$bcc);
                   15047:                                         }
                   15048:                                     }
                   15049:                                 }
                   15050:                                 if (@ok_bccs > 0) {
                   15051:                                     $allbcc = join(', ',@ok_bccs);
                   15052:                                 }
                   15053:                             }
                   15054:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15055:                             last;
                   15056:                         }
                   15057:                     }
                   15058:                 }
                   15059:             }
                   15060:         }
1.619     raeburn  15061:     } elsif ($origmail ne '') {
1.1270    raeburn  15062:         $lastresort = $origmail;
                   15063:     }
1.1297    raeburn  15064:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  15065:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15066:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15067:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15068:             my %what = (
                   15069:                           perlvar => 1,
                   15070:                        );
                   15071:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15072:             if ($primary) {
                   15073:                 my $gotaddr;
                   15074:                 my ($result,$returnhash) =
                   15075:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15076:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15077:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15078:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15079:                         $gotaddr = 1;
                   15080:                     }
                   15081:                 }
                   15082:                 unless ($gotaddr) {
                   15083:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15084:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15085:                     unless ($uintdom eq $intdom) {
                   15086:                         my %domconfig =
                   15087:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15088:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15089:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15090:                                 my @contacts = ('adminemail','supportemail');
                   15091:                                 foreach my $item (@contacts) {
                   15092:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15093:                                         my $addr = $domconfig{'contacts'}{$item};
                   15094:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15095:                                             push(@recipients,$addr);
                   15096:                                         }
                   15097:                                     }
                   15098:                                 }
                   15099:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15100:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15101:                                 }
                   15102:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15103:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15104:                                     my @ok_bccs;
                   15105:                                     foreach my $bcc (@bccs) {
                   15106:                                         $bcc =~ s/^\s+//g;
                   15107:                                         $bcc =~ s/\s+$//g;
                   15108:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15109:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15110:                                                 push(@ok_bccs,$bcc);
                   15111:                                             }
                   15112:                                         }
                   15113:                                     }
                   15114:                                     if (@ok_bccs > 0) {
                   15115:                                         $allbcc = join(', ',@ok_bccs);
                   15116:                                     }
                   15117:                                 }
                   15118:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15119:                             }
                   15120:                         }
                   15121:                     }
                   15122:                 }
                   15123:             }
                   15124:         }
1.618     raeburn  15125:     }
1.688     raeburn  15126:     if (defined($defmail)) {
                   15127:         if ($defmail ne '') {
                   15128:             push(@recipients,$defmail);
                   15129:         }
1.618     raeburn  15130:     }
                   15131:     if ($otheremails) {
1.619     raeburn  15132:         my @others;
                   15133:         if ($otheremails =~ /,/) {
                   15134:             @others = split(/,/,$otheremails);
1.618     raeburn  15135:         } else {
1.619     raeburn  15136:             push(@others,$otheremails);
                   15137:         }
                   15138:         foreach my $addr (@others) {
                   15139:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15140:                 push(@recipients,$addr);
                   15141:             }
1.618     raeburn  15142:         }
                   15143:     }
1.1298    raeburn  15144:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  15145:         if ((!@recipients) && ($lastresort ne '')) {
                   15146:             push(@recipients,$lastresort);
                   15147:         }
                   15148:     } elsif ($lastresort ne '') {
                   15149:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15150:             push(@recipients,$lastresort);
                   15151:         }
                   15152:     }
1.1271    raeburn  15153:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  15154:     if (wantarray) {
                   15155:         return ($recipientlist,$allbcc,$addtext);
                   15156:     } else {
                   15157:         return $recipientlist;
                   15158:     }
1.618     raeburn  15159: }
                   15160: 
1.127     matthew  15161: ############################################################
                   15162: ############################################################
1.154     albertel 15163: 
1.655     raeburn  15164: =pod
                   15165: 
1.1224    musolffc 15166: =over 4
                   15167: 
1.1223    musolffc 15168: =item * &mime_email()
                   15169: 
                   15170: Sends an email with a possible attachment
                   15171: 
                   15172: Inputs:
                   15173: 
                   15174: =over 4
                   15175: 
                   15176: from -              Sender's email address
                   15177: 
                   15178: to -                Email address of recipient
                   15179: 
                   15180: subject -           Subject of email
                   15181: 
                   15182: body -              Body of email
                   15183: 
                   15184: cc_string -         Carbon copy email address
                   15185: 
                   15186: bcc -               Blind carbon copy email address
                   15187: 
                   15188: type -              File type of attachment
                   15189: 
                   15190: attachment_path -   Path of file to be attached
                   15191: 
                   15192: file_name -         Name of file to be attached
                   15193: 
                   15194: attachment_text -   The body of an attachment of type "TEXT"
                   15195: 
                   15196: =back
                   15197: 
                   15198: =back
                   15199: 
                   15200: =cut
                   15201: 
                   15202: ############################################################
                   15203: ############################################################
                   15204: 
                   15205: sub mime_email {
                   15206:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
                   15207:         $file_name, $attachment_text) = @_;
                   15208:     my $msg = MIME::Lite->new(
                   15209:              From    => $from,
                   15210:              To      => $to,
                   15211:              Subject => $subject,
                   15212:              Type    =>'TEXT',
                   15213:              Data    => $body,
                   15214:              );
                   15215:     if ($cc_string ne '') {
                   15216:         $msg->add("Cc" => $cc_string);
                   15217:     }
                   15218:     if ($bcc ne '') {
                   15219:         $msg->add("Bcc" => $bcc);
                   15220:     }
                   15221:     $msg->attr("content-type"         => "text/plain");
                   15222:     $msg->attr("content-type.charset" => "UTF-8");
                   15223:     # Attach file if given
                   15224:     if ($attachment_path) {
                   15225:         unless ($file_name) {
                   15226:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   15227:         }
                   15228:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   15229:         $msg->attach(Type     => $type,
                   15230:                      Path     => $attachment_path,
                   15231:                      Filename => $file_name
                   15232:                      );
                   15233:     # Otherwise attach text if given
                   15234:     } elsif ($attachment_text) {
                   15235:         $msg->attach(Type => 'TEXT',
                   15236:                      Data => $attachment_text);
                   15237:     }
                   15238:     # Send it
                   15239:     $msg->send('sendmail');
                   15240: }
                   15241: 
                   15242: ############################################################
                   15243: ############################################################
                   15244: 
                   15245: =pod
                   15246: 
1.655     raeburn  15247: =head1 Course Catalog Routines
                   15248: 
                   15249: =over 4
                   15250: 
                   15251: =item * &gather_categories()
                   15252: 
                   15253: Converts category definitions - keys of categories hash stored in  
                   15254: coursecategories in configuration.db on the primary library server in a 
                   15255: domain - to an array.  Also generates javascript and idx hash used to 
                   15256: generate Domain Coordinator interface for editing Course Categories.
                   15257: 
                   15258: Inputs:
1.663     raeburn  15259: 
1.655     raeburn  15260: categories (reference to hash of category definitions).
1.663     raeburn  15261: 
1.655     raeburn  15262: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15263:       categories and subcategories).
1.663     raeburn  15264: 
1.655     raeburn  15265: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15266:       editing Course Categories).
1.663     raeburn  15267: 
1.655     raeburn  15268: jsarray (reference to array of categories used to create Javascript arrays for
                   15269:          Domain Coordinator interface for editing Course Categories).
                   15270: 
                   15271: Returns: nothing
                   15272: 
                   15273: Side effects: populates cats, idx and jsarray. 
                   15274: 
                   15275: =cut
                   15276: 
                   15277: sub gather_categories {
                   15278:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15279:     my %counters;
                   15280:     my $num = 0;
                   15281:     foreach my $item (keys(%{$categories})) {
                   15282:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15283:         if ($container eq '' && $depth == 0) {
                   15284:             $cats->[$depth][$categories->{$item}] = $cat;
                   15285:         } else {
                   15286:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15287:         }
                   15288:         my ($escitem,$tail) = split(/:/,$item,2);
                   15289:         if ($counters{$tail} eq '') {
                   15290:             $counters{$tail} = $num;
                   15291:             $num ++;
                   15292:         }
                   15293:         if (ref($idx) eq 'HASH') {
                   15294:             $idx->{$item} = $counters{$tail};
                   15295:         }
                   15296:         if (ref($jsarray) eq 'ARRAY') {
                   15297:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15298:         }
                   15299:     }
                   15300:     return;
                   15301: }
                   15302: 
                   15303: =pod
                   15304: 
                   15305: =item * &extract_categories()
                   15306: 
                   15307: Used to generate breadcrumb trails for course categories.
                   15308: 
                   15309: Inputs:
1.663     raeburn  15310: 
1.655     raeburn  15311: categories (reference to hash of category definitions).
1.663     raeburn  15312: 
1.655     raeburn  15313: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15314:       categories and subcategories).
1.663     raeburn  15315: 
1.655     raeburn  15316: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15317: 
1.655     raeburn  15318: allitems (reference to hash - key is category key 
                   15319:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15320: 
1.655     raeburn  15321: idx (reference to hash of counters used in Domain Coordinator interface for
                   15322:       editing Course Categories).
1.663     raeburn  15323: 
1.655     raeburn  15324: jsarray (reference to array of categories used to create Javascript arrays for
                   15325:          Domain Coordinator interface for editing Course Categories).
                   15326: 
1.665     raeburn  15327: subcats (reference to hash of arrays containing all subcategories within each 
                   15328:          category, -recursive)
                   15329: 
1.1321    raeburn  15330: maxd (reference to hash used to hold max depth for all top-level categories).
                   15331: 
1.655     raeburn  15332: Returns: nothing
                   15333: 
                   15334: Side effects: populates trails and allitems hash references.
                   15335: 
                   15336: =cut
                   15337: 
                   15338: sub extract_categories {
1.1321    raeburn  15339:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15340:     if (ref($categories) eq 'HASH') {
                   15341:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15342:         if (ref($cats->[0]) eq 'ARRAY') {
                   15343:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15344:                 my $name = $cats->[0][$i];
                   15345:                 my $item = &escape($name).'::0';
                   15346:                 my $trailstr;
                   15347:                 if ($name eq 'instcode') {
                   15348:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15349:                 } elsif ($name eq 'communities') {
                   15350:                     $trailstr = &mt('Communities');
1.1239    raeburn  15351:                 } elsif ($name eq 'placement') {
                   15352:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  15353:                 } else {
                   15354:                     $trailstr = $name;
                   15355:                 }
                   15356:                 if ($allitems->{$item} eq '') {
                   15357:                     push(@{$trails},$trailstr);
                   15358:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15359:                 }
                   15360:                 my @parents = ($name);
                   15361:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15362:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15363:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15364:                         if (ref($subcats) eq 'HASH') {
                   15365:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15366:                         }
1.1321    raeburn  15367:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15368:                     }
                   15369:                 } else {
                   15370:                     if (ref($subcats) eq 'HASH') {
                   15371:                         $subcats->{$item} = [];
1.655     raeburn  15372:                     }
1.1321    raeburn  15373:                     if (ref($maxd) eq 'HASH') {
                   15374:                         $maxd->{$name} = 1;
                   15375:                     }
1.655     raeburn  15376:                 }
                   15377:             }
                   15378:         }
                   15379:     }
                   15380:     return;
                   15381: }
                   15382: 
                   15383: =pod
                   15384: 
1.1162    raeburn  15385: =item * &recurse_categories()
1.655     raeburn  15386: 
                   15387: Recursively used to generate breadcrumb trails for course categories.
                   15388: 
                   15389: Inputs:
1.663     raeburn  15390: 
1.655     raeburn  15391: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15392:       categories and subcategories).
1.663     raeburn  15393: 
1.655     raeburn  15394: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15395: 
                   15396: category (current course category, for which breadcrumb trail is being generated).
                   15397: 
                   15398: trails (reference to array of breadcrumb trails for each category).
                   15399: 
1.655     raeburn  15400: allitems (reference to hash - key is category key
                   15401:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15402: 
1.655     raeburn  15403: parents (array containing containers directories for current category, 
                   15404:          back to top level). 
                   15405: 
                   15406: Returns: nothing
                   15407: 
                   15408: Side effects: populates trails and allitems hash references
                   15409: 
                   15410: =cut
                   15411: 
                   15412: sub recurse_categories {
1.1321    raeburn  15413:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  15414:     my $shallower = $depth - 1;
                   15415:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15416:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   15417:             my $name = $cats->[$depth]{$category}[$k];
                   15418:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  15419:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15420:             if ($allitems->{$item} eq '') {
                   15421:                 push(@{$trails},$trailstr);
                   15422:                 $allitems->{$item} = scalar(@{$trails})-1;
                   15423:             }
                   15424:             my $deeper = $depth+1;
                   15425:             push(@{$parents},$category);
1.665     raeburn  15426:             if (ref($subcats) eq 'HASH') {
                   15427:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   15428:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   15429:                     my $higher;
                   15430:                     if ($j > 0) {
                   15431:                         $higher = &escape($parents->[$j]).':'.
                   15432:                                   &escape($parents->[$j-1]).':'.$j;
                   15433:                     } else {
                   15434:                         $higher = &escape($parents->[$j]).'::'.$j;
                   15435:                     }
                   15436:                     push(@{$subcats->{$higher}},$subcat);
                   15437:                 }
                   15438:             }
                   15439:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  15440:                                 $subcats,$maxd);
1.655     raeburn  15441:             pop(@{$parents});
                   15442:         }
                   15443:     } else {
                   15444:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  15445:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15446:         if ($allitems->{$item} eq '') {
                   15447:             push(@{$trails},$trailstr);
                   15448:             $allitems->{$item} = scalar(@{$trails})-1;
                   15449:         }
1.1321    raeburn  15450:         if (ref($maxd) eq 'HASH') {
                   15451:             if ($depth > $maxd->{$parents->[0]}) {
                   15452:                 $maxd->{$parents->[0]} = $depth;
                   15453:             }
                   15454:         }
1.655     raeburn  15455:     }
                   15456:     return;
                   15457: }
                   15458: 
1.663     raeburn  15459: =pod
                   15460: 
1.1162    raeburn  15461: =item * &assign_categories_table()
1.663     raeburn  15462: 
                   15463: Create a datatable for display of hierarchical categories in a domain,
                   15464: with checkboxes to allow a course to be categorized. 
                   15465: 
                   15466: Inputs:
                   15467: 
                   15468: cathash - reference to hash of categories defined for the domain (from
                   15469:           configuration.db)
                   15470: 
                   15471: currcat - scalar with an & separated list of categories assigned to a course. 
                   15472: 
1.919     raeburn  15473: type    - scalar contains course type (Course or Community).
                   15474: 
1.1260    raeburn  15475: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15476:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15477: 
1.663     raeburn  15478: Returns: $output (markup to be displayed) 
                   15479: 
                   15480: =cut
                   15481: 
                   15482: sub assign_categories_table {
1.1259    raeburn  15483:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  15484:     my $output;
                   15485:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  15486:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   15487:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  15488:         $maxdepth = scalar(@cats);
                   15489:         if (@cats > 0) {
                   15490:             my $itemcount = 0;
                   15491:             if (ref($cats[0]) eq 'ARRAY') {
                   15492:                 my @currcategories;
                   15493:                 if ($currcat ne '') {
                   15494:                     @currcategories = split('&',$currcat);
                   15495:                 }
1.919     raeburn  15496:                 my $table;
1.663     raeburn  15497:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15498:                     my $parent = $cats[0][$i];
1.919     raeburn  15499:                     next if ($parent eq 'instcode');
                   15500:                     if ($type eq 'Community') {
                   15501:                         next unless ($parent eq 'communities');
1.1239    raeburn  15502:                     } elsif ($type eq 'Placement') {
                   15503:                         next unless ($parent eq 'placement');
1.919     raeburn  15504:                     } else {
1.1239    raeburn  15505:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  15506:                     }
1.663     raeburn  15507:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15508:                     my $item = &escape($parent).'::0';
                   15509:                     my $checked = '';
                   15510:                     if (@currcategories > 0) {
                   15511:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15512:                             $checked = ' checked="checked"';
1.663     raeburn  15513:                         }
                   15514:                     }
1.919     raeburn  15515:                     my $parent_title = $parent;
                   15516:                     if ($parent eq 'communities') {
                   15517:                         $parent_title = &mt('Communities');
1.1239    raeburn  15518:                     } elsif ($parent eq 'placement') {
                   15519:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  15520:                     }
                   15521:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15522:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15523:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15524:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15525:                     my $depth = 1;
                   15526:                     push(@path,$parent);
1.1259    raeburn  15527:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15528:                     pop(@path);
1.919     raeburn  15529:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15530:                     $itemcount ++;
                   15531:                 }
1.919     raeburn  15532:                 if ($itemcount) {
                   15533:                     $output = &Apache::loncommon::start_data_table().
                   15534:                               $table.
                   15535:                               &Apache::loncommon::end_data_table();
                   15536:                 }
1.663     raeburn  15537:             }
                   15538:         }
                   15539:     }
                   15540:     return $output;
                   15541: }
                   15542: 
                   15543: =pod
                   15544: 
1.1162    raeburn  15545: =item * &assign_category_rows()
1.663     raeburn  15546: 
                   15547: Create a datatable row for display of nested categories in a domain,
                   15548: with checkboxes to allow a course to be categorized,called recursively.
                   15549: 
                   15550: Inputs:
                   15551: 
                   15552: itemcount - track row number for alternating colors
                   15553: 
                   15554: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15555:       categories and subcategories.
                   15556: 
                   15557: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15558: 
                   15559: parent - parent of current category item
                   15560: 
                   15561: path - Array containing all categories back up through the hierarchy from the
                   15562:        current category to the top level.
                   15563: 
                   15564: currcategories - reference to array of current categories assigned to the course
                   15565: 
1.1260    raeburn  15566: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15567:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15568: 
1.663     raeburn  15569: Returns: $output (markup to be displayed).
                   15570: 
                   15571: =cut
                   15572: 
                   15573: sub assign_category_rows {
1.1259    raeburn  15574:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15575:     my ($text,$name,$item,$chgstr);
                   15576:     if (ref($cats) eq 'ARRAY') {
                   15577:         my $maxdepth = scalar(@{$cats});
                   15578:         if (ref($cats->[$depth]) eq 'HASH') {
                   15579:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15580:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15581:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  15582:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15583:                 for (my $j=0; $j<$numchildren; $j++) {
                   15584:                     $name = $cats->[$depth]{$parent}[$j];
                   15585:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15586:                     my $deeper = $depth+1;
                   15587:                     my $checked = '';
                   15588:                     if (ref($currcategories) eq 'ARRAY') {
                   15589:                         if (@{$currcategories} > 0) {
                   15590:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15591:                                 $checked = ' checked="checked"';
1.663     raeburn  15592:                             }
                   15593:                         }
                   15594:                     }
1.664     raeburn  15595:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15596:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15597:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15598:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15599:                              '</td><td>';
1.663     raeburn  15600:                     if (ref($path) eq 'ARRAY') {
                   15601:                         push(@{$path},$name);
1.1259    raeburn  15602:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15603:                         pop(@{$path});
                   15604:                     }
                   15605:                     $text .= '</td></tr>';
                   15606:                 }
                   15607:                 $text .= '</table></td>';
                   15608:             }
                   15609:         }
                   15610:     }
                   15611:     return $text;
                   15612: }
                   15613: 
1.1181    raeburn  15614: =pod
                   15615: 
                   15616: =back
                   15617: 
                   15618: =cut
                   15619: 
1.655     raeburn  15620: ############################################################
                   15621: ############################################################
                   15622: 
                   15623: 
1.443     albertel 15624: sub commit_customrole {
1.664     raeburn  15625:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15626:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15627:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15628:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15629:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15630:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15631:                  '</b><br />';
                   15632:     return $output;
                   15633: }
                   15634: 
                   15635: sub commit_standardrole {
1.1116    raeburn  15636:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15637:     my ($output,$logmsg,$linefeed);
                   15638:     if ($context eq 'auto') {
                   15639:         $linefeed = "\n";
                   15640:     } else {
                   15641:         $linefeed = "<br />\n";
                   15642:     }  
1.443     albertel 15643:     if ($three eq 'st') {
1.541     raeburn  15644:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  15645:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15646:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15647:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15648:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15649:         } else {
1.541     raeburn  15650:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15651:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15652:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15653:             if ($context eq 'auto') {
                   15654:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15655:             } else {
                   15656:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15657:                &mt('Add to classlist').': <b>ok</b>';
                   15658:             }
                   15659:             $output .= $linefeed;
1.443     albertel 15660:         }
                   15661:     } else {
                   15662:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15663:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15664:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15665:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15666:         if ($context eq 'auto') {
                   15667:             $output .= $result.$linefeed;
                   15668:         } else {
                   15669:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15670:         }
1.443     albertel 15671:     }
                   15672:     return $output;
                   15673: }
                   15674: 
                   15675: sub commit_studentrole {
1.1116    raeburn  15676:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15677:         $credits) = @_;
1.626     raeburn  15678:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15679:     if ($context eq 'auto') {
                   15680:         $linefeed = "\n";
                   15681:     } else {
                   15682:         $linefeed = '<br />'."\n";
                   15683:     }
1.443     albertel 15684:     if (defined($one) && defined($two)) {
                   15685:         my $cid=$one.'_'.$two;
                   15686:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15687:         my $secchange = 0;
                   15688:         my $expire_role_result;
                   15689:         my $modify_section_result;
1.628     raeburn  15690:         if ($oldsec ne '-1') { 
                   15691:             if ($oldsec ne $sec) {
1.443     albertel 15692:                 $secchange = 1;
1.628     raeburn  15693:                 my $now = time;
1.443     albertel 15694:                 my $uurl='/'.$cid;
                   15695:                 $uurl=~s/\_/\//g;
                   15696:                 if ($oldsec) {
                   15697:                     $uurl.='/'.$oldsec;
                   15698:                 }
1.626     raeburn  15699:                 $oldsecurl = $uurl;
1.628     raeburn  15700:                 $expire_role_result = 
1.652     raeburn  15701:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15702:                 if ($env{'request.course.sec'} ne '') { 
                   15703:                     if ($expire_role_result eq 'refused') {
                   15704:                         my @roles = ('st');
                   15705:                         my @statuses = ('previous');
                   15706:                         my @roledoms = ($one);
                   15707:                         my $withsec = 1;
                   15708:                         my %roleshash = 
                   15709:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15710:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15711:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15712:                             my ($oldstart,$oldend) = 
                   15713:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15714:                             if ($oldend > 0 && $oldend <= $now) {
                   15715:                                 $expire_role_result = 'ok';
                   15716:                             }
                   15717:                         }
                   15718:                     }
                   15719:                 }
1.443     albertel 15720:                 $result = $expire_role_result;
                   15721:             }
                   15722:         }
                   15723:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  15724:             $modify_section_result = 
                   15725:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15726:                                                            undef,undef,undef,$sec,
                   15727:                                                            $end,$start,'','',$cid,
                   15728:                                                            '',$context,$credits);
1.443     albertel 15729:             if ($modify_section_result =~ /^ok/) {
                   15730:                 if ($secchange == 1) {
1.628     raeburn  15731:                     if ($sec eq '') {
                   15732:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15733:                     } else {
                   15734:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15735:                     }
1.443     albertel 15736:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15737:                     if ($sec eq '') {
                   15738:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15739:                     } else {
                   15740:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15741:                     }
1.443     albertel 15742:                 } else {
1.628     raeburn  15743:                     if ($sec eq '') {
                   15744:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15745:                     } else {
                   15746:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15747:                     }
1.443     albertel 15748:                 }
                   15749:             } else {
1.1115    raeburn  15750:                 if ($secchange) { 
1.628     raeburn  15751:                     $$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;
                   15752:                 } else {
                   15753:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15754:                 }
1.443     albertel 15755:             }
                   15756:             $result = $modify_section_result;
                   15757:         } elsif ($secchange == 1) {
1.628     raeburn  15758:             if ($oldsec eq '') {
1.1103    raeburn  15759:                 $$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  15760:             } else {
                   15761:                 $$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;
                   15762:             }
1.626     raeburn  15763:             if ($expire_role_result eq 'refused') {
                   15764:                 my $newsecurl = '/'.$cid;
                   15765:                 $newsecurl =~ s/\_/\//g;
                   15766:                 if ($sec ne '') {
                   15767:                     $newsecurl.='/'.$sec;
                   15768:                 }
                   15769:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15770:                     if ($sec eq '') {
                   15771:                         $$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;
                   15772:                     } else {
                   15773:                         $$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;
                   15774:                     }
                   15775:                 }
                   15776:             }
1.443     albertel 15777:         }
                   15778:     } else {
1.626     raeburn  15779:         $$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 15780:         $result = "error: incomplete course id\n";
                   15781:     }
                   15782:     return $result;
                   15783: }
                   15784: 
1.1108    raeburn  15785: sub show_role_extent {
                   15786:     my ($scope,$context,$role) = @_;
                   15787:     $scope =~ s{^/}{};
                   15788:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15789:     push(@courseroles,'co');
                   15790:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15791:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15792:         $scope =~ s{/}{_};
                   15793:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15794:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15795:         my ($audom,$auname) = split(/\//,$scope);
                   15796:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15797:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15798:     } else {
                   15799:         $scope =~ s{/$}{};
                   15800:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15801:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15802:     }
                   15803: }
                   15804: 
1.443     albertel 15805: ############################################################
                   15806: ############################################################
                   15807: 
1.566     albertel 15808: sub check_clone {
1.578     raeburn  15809:     my ($args,$linefeed) = @_;
1.566     albertel 15810:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15811:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15812:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   15813:     my $clonemsg;
                   15814:     my $can_clone = 0;
1.944     raeburn  15815:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15816:     if ($lctype ne 'community') {
                   15817:         $lctype = 'course';
                   15818:     }
1.566     albertel 15819:     if ($clonehome eq 'no_host') {
1.944     raeburn  15820:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15821:             $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'});
                   15822:         } else {
                   15823:             $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'});
                   15824:         }     
1.566     albertel 15825:     } else {
                   15826: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  15827:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15828:             if ($clonedesc{'type'} ne 'Community') {
1.1262    raeburn  15829:                 $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
1.908     raeburn  15830:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15831:             }
                   15832:         }
1.1262    raeburn  15833: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15834:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15835: 	    $can_clone = 1;
                   15836: 	} else {
1.1221    raeburn  15837: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15838: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  15839:             if ($clonehash{'cloners'} eq '') {
                   15840:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15841:                 if ($domdefs{'canclone'}) {
                   15842:                     unless ($domdefs{'canclone'} eq 'none') {
                   15843:                         if ($domdefs{'canclone'} eq 'domain') {
                   15844:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15845:                                 $can_clone = 1;
                   15846:                             }
                   15847:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15848:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15849:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15850:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15851:                                 $can_clone = 1;
                   15852:                             }
                   15853:                         }
                   15854:                     }
                   15855:                 }
1.578     raeburn  15856:             } else {
1.1221    raeburn  15857: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15858:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15859:                     $can_clone = 1;
1.1221    raeburn  15860:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15861:                     $can_clone = 1;
1.1225    raeburn  15862:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15863:                     $can_clone = 1;
1.1221    raeburn  15864:                 }
                   15865:                 unless ($can_clone) {
1.1225    raeburn  15866:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15867:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  15868:                         my (%gotdomdefaults,%gotcodedefaults);
                   15869:                         foreach my $cloner (@cloners) {
                   15870:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15871:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15872:                                 my (%codedefaults,@code_order);
                   15873:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15874:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15875:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15876:                                     }
                   15877:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15878:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15879:                                     }
                   15880:                                 } else {
                   15881:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15882:                                                                             \%codedefaults,
                   15883:                                                                             \@code_order);
                   15884:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15885:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15886:                                 }
                   15887:                                 if (@code_order > 0) {
                   15888:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15889:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15890:                                                                                 $args->{'crscode'})) {
                   15891:                                         $can_clone = 1;
                   15892:                                         last;
                   15893:                                     }
                   15894:                                 }
                   15895:                             }
                   15896:                         }
                   15897:                     }
1.1225    raeburn  15898:                 }
                   15899:             }
                   15900:             unless ($can_clone) {
                   15901:                 my $ccrole = 'cc';
                   15902:                 if ($args->{'crstype'} eq 'Community') {
                   15903:                     $ccrole = 'co';
                   15904:                 }
                   15905: 	        my %roleshash =
                   15906: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15907: 					          $args->{'ccdomain'},
                   15908:                                                   'userroles',['active'],[$ccrole],
                   15909: 					          [$args->{'clonedomain'}]);
                   15910: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15911:                     $can_clone = 1;
                   15912:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15913:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15914:                     $can_clone = 1;
1.1221    raeburn  15915:                 }
                   15916:             }
                   15917:             unless ($can_clone) {
                   15918:                 if ($args->{'crstype'} eq 'Community') {
                   15919:                     $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
1.942     raeburn  15920:                 } else {
1.1221    raeburn  15921:                     $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'});
                   15922:                 }
1.566     albertel 15923: 	    }
1.578     raeburn  15924:         }
1.566     albertel 15925:     }
                   15926:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15927: }
                   15928: 
1.444     albertel 15929: sub construct_course {
1.1262    raeburn  15930:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   15931:         $cnum,$category,$coderef) = @_;
1.444     albertel 15932:     my $outcome;
1.541     raeburn  15933:     my $linefeed =  '<br />'."\n";
                   15934:     if ($context eq 'auto') {
                   15935:         $linefeed = "\n";
                   15936:     }
1.566     albertel 15937: 
                   15938: #
                   15939: # Are we cloning?
                   15940: #
                   15941:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15942:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  15943: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 15944: 	if ($context ne 'auto') {
1.578     raeburn  15945:             if ($clonemsg ne '') {
                   15946: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   15947:             }
1.566     albertel 15948: 	}
                   15949: 	$outcome .= $clonemsg.$linefeed;
                   15950: 
                   15951:         if (!$can_clone) {
                   15952: 	    return (0,$outcome);
                   15953: 	}
                   15954:     }
                   15955: 
1.444     albertel 15956: #
                   15957: # Open course
                   15958: #
1.1239    raeburn  15959:     my $showncrstype;
                   15960:     if ($args->{'crstype'} eq 'Placement') {
                   15961:         $showncrstype = 'placement test'; 
                   15962:     } else {  
                   15963:         $showncrstype = lc($args->{'crstype'});
                   15964:     }
1.444     albertel 15965:     my %cenv=();
                   15966:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15967:                                              $args->{'cdescr'},
                   15968:                                              $args->{'curl'},
                   15969:                                              $args->{'course_home'},
                   15970:                                              $args->{'nonstandard'},
                   15971:                                              $args->{'crscode'},
                   15972:                                              $args->{'ccuname'}.':'.
                   15973:                                              $args->{'ccdomain'},
1.882     raeburn  15974:                                              $args->{'crstype'},
1.885     raeburn  15975:                                              $cnum,$context,$category);
1.444     albertel 15976: 
                   15977:     # Note: The testing routines depend on this being output; see 
                   15978:     # Utils::Course. This needs to at least be output as a comment
                   15979:     # if anyone ever decides to not show this, and Utils::Course::new
                   15980:     # will need to be suitably modified.
1.1239    raeburn  15981:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
1.943     raeburn  15982:     if ($$courseid =~ /^error:/) {
                   15983:         return (0,$outcome);
                   15984:     }
                   15985: 
1.444     albertel 15986: #
                   15987: # Check if created correctly
                   15988: #
1.479     albertel 15989:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15990:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15991:     if ($crsuhome eq 'no_host') {
                   15992:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   15993:         return (0,$outcome);
                   15994:     }
1.541     raeburn  15995:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15996: 
1.444     albertel 15997: #
1.566     albertel 15998: # Do the cloning
                   15999: #   
                   16000:     if ($can_clone && $cloneid) {
1.1239    raeburn  16001: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
1.566     albertel 16002: 	if ($context ne 'auto') {
                   16003: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   16004: 	}
                   16005: 	$outcome .= $clonemsg.$linefeed;
                   16006: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16007: # Copy all files
1.637     www      16008: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 16009: # Restore URL
1.566     albertel 16010: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16011: # Restore title
1.566     albertel 16012: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16013: # Restore creation date, creator and creation context.
                   16014:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16015:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16016:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16017: # Mark as cloned
1.566     albertel 16018: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16019: # Need to clone grading mode
                   16020:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16021:         $cenv{'grading'}=$newenv{'grading'};
                   16022: # Do not clone these environment entries
                   16023:         &Apache::lonnet::del('environment',
                   16024:                   ['default_enrollment_start_date',
                   16025:                    'default_enrollment_end_date',
                   16026:                    'question.email',
                   16027:                    'policy.email',
                   16028:                    'comment.email',
                   16029:                    'pch.users.denied',
1.725     raeburn  16030:                    'plc.users.denied',
                   16031:                    'hidefromcat',
1.1121    raeburn  16032:                    'checkforpriv',
1.1166    raeburn  16033:                    'categories',
                   16034:                    'internal.uniquecode'],
1.638     www      16035:                    $$crsudom,$$crsunum);
1.1170    raeburn  16036:         if ($args->{'textbook'}) {
                   16037:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16038:         }
1.444     albertel 16039:     }
1.566     albertel 16040: 
1.444     albertel 16041: #
                   16042: # Set environment (will override cloned, if existing)
                   16043: #
                   16044:     my @sections = ();
                   16045:     my @xlists = ();
                   16046:     if ($args->{'crstype'}) {
                   16047:         $cenv{'type'}=$args->{'crstype'};
                   16048:     }
                   16049:     if ($args->{'crsid'}) {
                   16050:         $cenv{'courseid'}=$args->{'crsid'};
                   16051:     }
                   16052:     if ($args->{'crscode'}) {
                   16053:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16054:     }
                   16055:     if ($args->{'crsquota'} ne '') {
                   16056:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16057:     } else {
                   16058:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16059:     }
                   16060:     if ($args->{'ccuname'}) {
                   16061:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16062:                                         ':'.$args->{'ccdomain'};
                   16063:     } else {
                   16064:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16065:     }
1.1116    raeburn  16066:     if ($args->{'defaultcredits'}) {
                   16067:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16068:     }
1.444     albertel 16069:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   16070:     if ($args->{'crssections'}) {
                   16071:         $cenv{'internal.sectionnums'} = '';
                   16072:         if ($args->{'crssections'} =~ m/,/) {
                   16073:             @sections = split/,/,$args->{'crssections'};
                   16074:         } else {
                   16075:             $sections[0] = $args->{'crssections'};
                   16076:         }
                   16077:         if (@sections > 0) {
                   16078:             foreach my $item (@sections) {
                   16079:                 my ($sec,$gp) = split/:/,$item;
                   16080:                 my $class = $args->{'crscode'}.$sec;
                   16081:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16082:                 $cenv{'internal.sectionnums'} .= $item.',';
                   16083:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16084:                     push(@badclasses,$class);
1.444     albertel 16085:                 }
                   16086:             }
                   16087:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16088:         }
                   16089:     }
                   16090: # do not hide course coordinator from staff listing, 
                   16091: # even if privileged
                   16092:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  16093: # add course coordinator's domain to domains to check for privileged users
                   16094: # if different to course domain
                   16095:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16096:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16097:     }
1.444     albertel 16098: # add crosslistings
                   16099:     if ($args->{'crsxlist'}) {
                   16100:         $cenv{'internal.crosslistings'}='';
                   16101:         if ($args->{'crsxlist'} =~ m/,/) {
                   16102:             @xlists = split/,/,$args->{'crsxlist'};
                   16103:         } else {
                   16104:             $xlists[0] = $args->{'crsxlist'};
                   16105:         }
                   16106:         if (@xlists > 0) {
                   16107:             foreach my $item (@xlists) {
                   16108:                 my ($xl,$gp) = split/:/,$item;
                   16109:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16110:                 $cenv{'internal.crosslistings'} .= $item.',';
                   16111:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16112:                     push(@badclasses,$xl);
1.444     albertel 16113:                 }
                   16114:             }
                   16115:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16116:         }
                   16117:     }
                   16118:     if ($args->{'autoadds'}) {
                   16119:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16120:     }
                   16121:     if ($args->{'autodrops'}) {
                   16122:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16123:     }
                   16124: # check for notification of enrollment changes
                   16125:     my @notified = ();
                   16126:     if ($args->{'notify_owner'}) {
                   16127:         if ($args->{'ccuname'} ne '') {
                   16128:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16129:         }
                   16130:     }
                   16131:     if ($args->{'notify_dc'}) {
                   16132:         if ($uname ne '') { 
1.630     raeburn  16133:             push(@notified,$uname.':'.$udom);
1.444     albertel 16134:         }
                   16135:     }
                   16136:     if (@notified > 0) {
                   16137:         my $notifylist;
                   16138:         if (@notified > 1) {
                   16139:             $notifylist = join(',',@notified);
                   16140:         } else {
                   16141:             $notifylist = $notified[0];
                   16142:         }
                   16143:         $cenv{'internal.notifylist'} = $notifylist;
                   16144:     }
                   16145:     if (@badclasses > 0) {
                   16146:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  16147:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16148:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16149:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16150:         );
1.1264    raeburn  16151:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16152:                            &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  16153:         if ($context eq 'auto') {
                   16154:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  16155:         } else {
1.566     albertel 16156:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  16157:         }
                   16158:         foreach my $item (@badclasses) {
1.541     raeburn  16159:             if ($context eq 'auto') {
1.1261    raeburn  16160:                 $outcome .= " - $item\n";
1.541     raeburn  16161:             } else {
1.1261    raeburn  16162:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16163:             }
1.1261    raeburn  16164:         }
                   16165:         if ($context eq 'auto') {
                   16166:             $outcome .= $linefeed;
                   16167:         } else {
                   16168:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  16169:         } 
1.444     albertel 16170:     }
                   16171:     if ($args->{'no_end_date'}) {
                   16172:         $args->{'endaccess'} = 0;
                   16173:     }
                   16174:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16175:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16176:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16177:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16178:     if ($args->{'showphotos'}) {
                   16179:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16180:     }
                   16181:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16182:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16183:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16184:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16185:             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'); 
                   16186:             if ($context eq 'auto') {
                   16187:                 $outcome .= $krb_msg;
                   16188:             } else {
1.566     albertel 16189:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16190:             }
                   16191:             $outcome .= $linefeed;
1.444     albertel 16192:         }
                   16193:     }
                   16194:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16195:        if ($args->{'setpolicy'}) {
                   16196:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16197:        }
                   16198:        if ($args->{'setcontent'}) {
                   16199:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16200:        }
1.1251    raeburn  16201:        if ($args->{'setcomment'}) {
                   16202:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16203:        }
1.444     albertel 16204:     }
                   16205:     if ($args->{'reshome'}) {
                   16206: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16207: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16208:     }
                   16209: #
                   16210: # course has keyed access
                   16211: #
                   16212:     if ($args->{'setkeys'}) {
                   16213:        $cenv{'keyaccess'}='yes';
                   16214:     }
                   16215: # if specified, key authority is not course, but user
                   16216: # only active if keyaccess is yes
                   16217:     if ($args->{'keyauth'}) {
1.487     albertel 16218: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16219: 	$user = &LONCAPA::clean_username($user);
                   16220: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16221: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16222: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16223: 	}
                   16224:     }
                   16225: 
1.1166    raeburn  16226: #
1.1167    raeburn  16227: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  16228: #
                   16229:     if ($args->{'uniquecode'}) {
                   16230:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16231:         if ($code) {
                   16232:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  16233:             my %crsinfo =
                   16234:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16235:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16236:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16237:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16238:             } 
1.1166    raeburn  16239:             if (ref($coderef)) {
                   16240:                 $$coderef = $code;
                   16241:             }
                   16242:         }
                   16243:     }
                   16244: 
1.444     albertel 16245:     if ($args->{'disresdis'}) {
                   16246:         $cenv{'pch.roles.denied'}='st';
                   16247:     }
                   16248:     if ($args->{'disablechat'}) {
                   16249:         $cenv{'plc.roles.denied'}='st';
                   16250:     }
                   16251: 
                   16252:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16253:     # course
                   16254:     $cenv{'course.helper.not.run'} = 1;
                   16255:     #
                   16256:     # Use new Randomseed
                   16257:     #
                   16258:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16259:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16260:     #
                   16261:     # The encryption code and receipt prefix for this course
                   16262:     #
                   16263:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16264:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16265:     #
                   16266:     # By default, use standard grading
                   16267:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16268: 
1.541     raeburn  16269:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16270:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16271: #
                   16272: # Open all assignments
                   16273: #
                   16274:     if ($args->{'openall'}) {
                   16275:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   16276:        my %storecontent = ($storeunder         => time,
                   16277:                            $storeunder.'.type' => 'date_start');
                   16278:        
                   16279:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  16280:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16281:    }
                   16282: #
                   16283: # Set first page
                   16284: #
                   16285:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16286: 	    || ($cloneid)) {
1.445     albertel 16287: 	use LONCAPA::map;
1.444     albertel 16288: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16289: 
                   16290: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16291:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16292: 
1.444     albertel 16293:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16294:         my $title; my $url;
                   16295:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16296: 	    $title=&mt('Syllabus');
1.444     albertel 16297:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16298:         } else {
1.963     raeburn  16299:             $title=&mt('Table of Contents');
1.444     albertel 16300:             $url='/adm/navmaps';
                   16301:         }
1.445     albertel 16302: 
                   16303:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16304: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16305: 
                   16306: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16307:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16308:     }
1.566     albertel 16309: 
1.1237    raeburn  16310: # 
                   16311: # Set params for Placement Tests
                   16312: #
1.1239    raeburn  16313:     if ($args->{'crstype'} eq 'Placement') {
                   16314:        my %storecontent; 
                   16315:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   16316:        my %defaults = (
                   16317:                         buttonshide   => { value => 'yes',
                   16318:                                            type => 'string_yesno',},
                   16319:                         type          => { value => 'randomizetry',
                   16320:                                            type  => 'string_questiontype',},
                   16321:                         maxtries      => { value => 1,
                   16322:                                            type => 'int_pos',},
                   16323:                         problemstatus => { value => 'no',
                   16324:                                            type  => 'string_problemstatus',},
                   16325:                       );
                   16326:        foreach my $key (keys(%defaults)) {
                   16327:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   16328:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   16329:        }
1.1237    raeburn  16330:        &Apache::lonnet::cput
                   16331:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   16332:     }
                   16333: 
1.566     albertel 16334:     return (1,$outcome);
1.444     albertel 16335: }
                   16336: 
1.1166    raeburn  16337: sub make_unique_code {
                   16338:     my ($cdom,$cnum) = @_;
                   16339:     # get lock on uniquecodes db
                   16340:     my $lockhash = {
                   16341:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16342:                                                   ':'.$env{'user.domain'},
                   16343:                    };
                   16344:     my $tries = 0;
                   16345:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16346:     my ($code,$error);
                   16347:   
                   16348:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16349:         $tries ++;
                   16350:         sleep 1;
                   16351:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16352:     }
                   16353:     if ($gotlock eq 'ok') {
                   16354:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16355:         my $gotcode;
                   16356:         my $attempts = 0;
                   16357:         while ((!$gotcode) && ($attempts < 100)) {
                   16358:             $code = &generate_code();
                   16359:             if (!exists($currcodes{$code})) {
                   16360:                 $gotcode = 1;
                   16361:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   16362:                     $error = 'nostore';
                   16363:                 }
                   16364:             }
                   16365:             $attempts ++;
                   16366:         }
                   16367:         my @del_lock = ($cnum."\0".'uniquecodes');
                   16368:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   16369:     } else {
                   16370:         $error = 'nolock';
                   16371:     }
                   16372:     return ($code,$error);
                   16373: }
                   16374: 
                   16375: sub generate_code {
                   16376:     my $code;
                   16377:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   16378:     for (my $i=0; $i<6; $i++) {
                   16379:         my $lettnum = int (rand 2);
                   16380:         my $item = '';
                   16381:         if ($lettnum) {
                   16382:             $item = $letts[int( rand(18) )];
                   16383:         } else {
                   16384:             $item = 1+int( rand(8) );
                   16385:         }
                   16386:         $code .= $item;
                   16387:     }
                   16388:     return $code;
                   16389: }
                   16390: 
1.444     albertel 16391: ############################################################
                   16392: ############################################################
                   16393: 
1.1237    raeburn  16394: # Community, Course and Placement Test
1.378     raeburn  16395: sub course_type {
                   16396:     my ($cid) = @_;
                   16397:     if (!defined($cid)) {
                   16398:         $cid = $env{'request.course.id'};
                   16399:     }
1.404     albertel 16400:     if (defined($env{'course.'.$cid.'.type'})) {
                   16401:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  16402:     } else {
                   16403:         return 'Course';
1.377     raeburn  16404:     }
                   16405: }
1.156     albertel 16406: 
1.406     raeburn  16407: sub group_term {
                   16408:     my $crstype = &course_type();
                   16409:     my %names = (
                   16410:                   'Course' => 'group',
1.865     raeburn  16411:                   'Community' => 'group',
1.1237    raeburn  16412:                   'Placement' => 'group',
1.406     raeburn  16413:                 );
                   16414:     return $names{$crstype};
                   16415: }
                   16416: 
1.902     raeburn  16417: sub course_types {
1.1310    raeburn  16418:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  16419:     my %typename = (
                   16420:                          official   => 'Official course',
                   16421:                          unofficial => 'Unofficial course',
                   16422:                          community  => 'Community',
1.1165    raeburn  16423:                          textbook   => 'Textbook course',
1.1237    raeburn  16424:                          placement  => 'Placement test',
1.1310    raeburn  16425:                          lti        => 'LTI provider',
1.902     raeburn  16426:                    );
                   16427:     return (\@types,\%typename);
                   16428: }
                   16429: 
1.156     albertel 16430: sub icon {
                   16431:     my ($file)=@_;
1.505     albertel 16432:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 16433:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 16434:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 16435:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   16436: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   16437: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16438: 	            $curfext.".gif") {
                   16439: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16440: 		$curfext.".gif";
                   16441: 	}
                   16442:     }
1.249     albertel 16443:     return &lonhttpdurl($iconname);
1.154     albertel 16444: } 
1.84      albertel 16445: 
1.575     albertel 16446: sub lonhttpdurl {
1.692     www      16447: #
                   16448: # Had been used for "small fry" static images on separate port 8080.
                   16449: # Modify here if lightweight http functionality desired again.
                   16450: # Currently eliminated due to increasing firewall issues.
                   16451: #
1.575     albertel 16452:     my ($url)=@_;
1.692     www      16453:     return $url;
1.215     albertel 16454: }
                   16455: 
1.213     albertel 16456: sub connection_aborted {
                   16457:     my ($r)=@_;
                   16458:     $r->print(" ");$r->rflush();
                   16459:     my $c = $r->connection;
                   16460:     return $c->aborted();
                   16461: }
                   16462: 
1.221     foxr     16463: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     16464: #    strings as 'strings'.
                   16465: sub escape_single {
1.221     foxr     16466:     my ($input) = @_;
1.223     albertel 16467:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     16468:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   16469:     return $input;
                   16470: }
1.223     albertel 16471: 
1.222     foxr     16472: #  Same as escape_single, but escape's "'s  This 
                   16473: #  can be used for  "strings"
                   16474: sub escape_double {
                   16475:     my ($input) = @_;
                   16476:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   16477:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   16478:     return $input;
                   16479: }
1.223     albertel 16480:  
1.222     foxr     16481: #   Escapes the last element of a full URL.
                   16482: sub escape_url {
                   16483:     my ($url)   = @_;
1.238     raeburn  16484:     my @urlslices = split(/\//, $url,-1);
1.369     www      16485:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  16486:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     16487: }
1.462     albertel 16488: 
1.820     raeburn  16489: sub compare_arrays {
                   16490:     my ($arrayref1,$arrayref2) = @_;
                   16491:     my (@difference,%count);
                   16492:     @difference = ();
                   16493:     %count = ();
                   16494:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16495:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16496:         foreach my $element (keys(%count)) {
                   16497:             if ($count{$element} == 1) {
                   16498:                 push(@difference,$element);
                   16499:             }
                   16500:         }
                   16501:     }
                   16502:     return @difference;
                   16503: }
                   16504: 
1.1322    raeburn  16505: sub lon_status_items {
                   16506:     my %defaults = (
                   16507:                      E         => 100,
                   16508:                      W         => 4,
                   16509:                      N         => 1,
1.1324    raeburn  16510:                      U         => 5,
1.1322    raeburn  16511:                      threshold => 200,
                   16512:                      sysmail   => 2500,
                   16513:                    );
                   16514:     my %names = (
                   16515:                    E => 'Errors',
                   16516:                    W => 'Warnings',
                   16517:                    N => 'Notices',
1.1324    raeburn  16518:                    U => 'Unsent',
1.1322    raeburn  16519:                 );
                   16520:     return (\%defaults,\%names);
                   16521: }
                   16522: 
1.817     bisitz   16523: # -------------------------------------------------------- Initialize user login
1.462     albertel 16524: sub init_user_environment {
1.463     albertel 16525:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 16526:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   16527: 
                   16528:     my $public=($username eq 'public' && $domain eq 'public');
                   16529: 
1.1062    raeburn  16530:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 16531:     my $now=time;
                   16532: 
                   16533:     if ($public) {
                   16534: 	my $max_public=100;
                   16535: 	my $oldest;
                   16536: 	my $oldest_time=0;
                   16537: 	for(my $next=1;$next<=$max_public;$next++) {
                   16538: 	    if (-e $lonids."/publicuser_$next.id") {
                   16539: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   16540: 		if ($mtime<$oldest_time || !$oldest_time) {
                   16541: 		    $oldest_time=$mtime;
                   16542: 		    $oldest=$next;
                   16543: 		}
                   16544: 	    } else {
                   16545: 		$cookie="publicuser_$next";
                   16546: 		last;
                   16547: 	    }
                   16548: 	}
                   16549: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16550:     } else {
1.1275    raeburn  16551: 	# See if old ID present, if so, remove if this isn't a robot,
                   16552: 	# killing any existing non-robot sessions
1.463     albertel 16553: 	if (!$args->{'robot'}) {
                   16554: 	    opendir(DIR,$lonids);
                   16555: 	    while ($filename=readdir(DIR)) {
                   16556: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  16557:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   16558:                             &GDBM_READER(),0640)) {
1.1295    raeburn  16559:                         my $linkedfile;
1.1320    raeburn  16560:                         if (exists($oldenv{'user.linkedenv'})) {
                   16561:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  16562:                         }
1.1320    raeburn  16563:                         untie(%oldenv);
                   16564:                         if (unlink("$lonids/$filename")) {
                   16565:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   16566:                                 if (-l "$lonids/$linkedfile.id") {
                   16567:                                     unlink("$lonids/$linkedfile.id");
                   16568:                                 }
1.1295    raeburn  16569:                             }
                   16570:                         }
                   16571:                     } else {
                   16572:                         unlink($lonids.'/'.$filename);
                   16573:                     }
1.463     albertel 16574: 		}
1.462     albertel 16575: 	    }
1.463     albertel 16576: 	    closedir(DIR);
1.1204    raeburn  16577: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16578:             my $namespace = 'nohist_courseeditor';
                   16579:             my $lockingkey = 'paste'."\0".'locked_num';
                   16580:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16581:                                                 $domain,$username);
                   16582:             if (exists($lockhash{$lockingkey})) {
                   16583:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16584:                 unless ($delresult eq 'ok') {
                   16585:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16586:                 }
                   16587:             }
1.462     albertel 16588: 	}
                   16589: # Give them a new cookie
1.463     albertel 16590: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16591: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16592: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16593:     
                   16594: # Initialize roles
                   16595: 
1.1062    raeburn  16596: 	($userroles,$firstaccenv,$timerintenv) = 
                   16597:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16598:     }
                   16599: # ------------------------------------ Check browser type and MathML capability
                   16600: 
1.1194    raeburn  16601:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   16602:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 16603: 
                   16604: # ------------------------------------------------------------- Get environment
                   16605: 
                   16606:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   16607:     my ($tmp) = keys(%userenv);
1.1275    raeburn  16608:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 16609: 	undef(%userenv);
                   16610:     }
                   16611:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   16612: 	$form->{'interface'}=$userenv{'interface'};
                   16613:     }
                   16614:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   16615: 
                   16616: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   16617:     foreach my $option ('interface','localpath','localres') {
                   16618:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 16619:     }
                   16620: # --------------------------------------------------------- Write first profile
                   16621: 
                   16622:     {
                   16623: 	my %initial_env = 
                   16624: 	    ("user.name"          => $username,
                   16625: 	     "user.domain"        => $domain,
                   16626: 	     "user.home"          => $authhost,
                   16627: 	     "browser.type"       => $clientbrowser,
                   16628: 	     "browser.version"    => $clientversion,
                   16629: 	     "browser.mathml"     => $clientmathml,
                   16630: 	     "browser.unicode"    => $clientunicode,
                   16631: 	     "browser.os"         => $clientos,
1.1137    raeburn  16632:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  16633:              "browser.info"       => $clientinfo,
1.1194    raeburn  16634:              "browser.osversion"  => $clientosversion,
1.462     albertel 16635: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   16636: 	     "request.course.fn"  => '',
                   16637: 	     "request.course.uri" => '',
                   16638: 	     "request.course.sec" => '',
                   16639: 	     "request.role"       => 'cm',
                   16640: 	     "request.role.adv"   => $env{'user.adv'},
                   16641: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   16642: 
                   16643:         if ($form->{'localpath'}) {
                   16644: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   16645: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   16646:         }
                   16647: 	
                   16648: 	if ($form->{'interface'}) {
                   16649: 	    $form->{'interface'}=~s/\W//gs;
                   16650: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   16651: 	    $env{'browser.interface'}=$form->{'interface'};
                   16652: 	}
                   16653: 
1.1157    raeburn  16654:         if ($form->{'iptoken'}) {
                   16655:             my $lonhost = $r->dir_config('lonHostID');
                   16656:             $initial_env{"user.noloadbalance"} = $lonhost;
                   16657:             $env{'user.noloadbalance'} = $lonhost;
                   16658:         }
                   16659: 
1.1268    raeburn  16660:         if ($form->{'noloadbalance'}) {
                   16661:             my @hosts = &Apache::lonnet::current_machine_ids();
                   16662:             my $hosthere = $form->{'noloadbalance'};
                   16663:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   16664:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   16665:                 $env{'user.noloadbalance'} = $hosthere;
                   16666:             }
                   16667:         }
                   16668: 
1.1016    raeburn  16669:         unless ($domain eq 'public') {
1.1273    raeburn  16670:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   16671:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   16672: 
                   16673:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   16674:                 $userenv{'availabletools.'.$tool} = 
                   16675:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16676:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   16677:             }
1.980     raeburn  16678: 
1.1311    raeburn  16679:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  16680:                 $userenv{'canrequest.'.$crstype} =
                   16681:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   16682:                                                       'reload','requestcourses',
                   16683:                                                       \%userenv,\%domdef,\%is_adv);
                   16684:             }
1.724     raeburn  16685: 
1.1273    raeburn  16686:             $userenv{'canrequest.author'} =
                   16687:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16688:                                                   'reload','requestauthor',
1.980     raeburn  16689:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  16690:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16691:                                                  $domain,$username);
                   16692:             my $reqstatus = $reqauthor{'author_status'};
                   16693:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   16694:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   16695:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16696:                                                       $reqauthor{'author'}{'timestamp'};
                   16697:                 }
1.1092    raeburn  16698:             }
1.1287    raeburn  16699:             my ($types,$typename) = &course_types();
                   16700:             if (ref($types) eq 'ARRAY') {
                   16701:                 my @options = ('approval','validate','autolimit');
                   16702:                 my $optregex = join('|',@options);
                   16703:                 my (%willtrust,%trustchecked);
                   16704:                 foreach my $type (@{$types}) {
                   16705:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   16706:                     if ($dom_str ne '') {
                   16707:                         my $updatedstr = '';
                   16708:                         my @possdomains = split(',',$dom_str);
                   16709:                         foreach my $entry (@possdomains) {
                   16710:                             my ($extdom,$extopt) = split(':',$entry);
                   16711:                             unless ($trustchecked{$extdom}) {
                   16712:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   16713:                                 $trustchecked{$extdom} = 1;
                   16714:                             }
                   16715:                             if ($willtrust{$extdom}) {
                   16716:                                 $updatedstr .= $entry.',';
                   16717:                             }
                   16718:                         }
                   16719:                         $updatedstr =~ s/,$//;
                   16720:                         if ($updatedstr) {
                   16721:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   16722:                         } else {
                   16723:                             delete($userenv{'reqcrsotherdom.'.$type});
                   16724:                         }
                   16725:                     }
                   16726:                 }
                   16727:             }
1.1092    raeburn  16728:         }
1.462     albertel 16729: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16730: 
1.462     albertel 16731: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16732: 		 &GDBM_WRCREAT(),0640)) {
                   16733: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16734: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16735: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16736:             if (ref($firstaccenv) eq 'HASH') {
                   16737:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16738:             }
                   16739:             if (ref($timerintenv) eq 'HASH') {
                   16740:                 &_add_to_env(\%disk_env,$timerintenv);
                   16741:             }
1.463     albertel 16742: 	    if (ref($args->{'extra_env'})) {
                   16743: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16744: 	    }
1.462     albertel 16745: 	    untie(%disk_env);
                   16746: 	} else {
1.705     tempelho 16747: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16748: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16749: 	    return 'error: '.$!;
                   16750: 	}
                   16751:     }
                   16752:     $env{'request.role'}='cm';
                   16753:     $env{'request.role.adv'}=$env{'user.adv'};
                   16754:     $env{'browser.type'}=$clientbrowser;
                   16755: 
                   16756:     return $cookie;
                   16757: 
                   16758: }
                   16759: 
                   16760: sub _add_to_env {
                   16761:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16762:     if (ref($env_data) eq 'HASH') {
                   16763:         while (my ($key,$value) = each(%$env_data)) {
                   16764: 	    $idf->{$prefix.$key} = $value;
                   16765: 	    $env{$prefix.$key}   = $value;
                   16766:         }
1.462     albertel 16767:     }
                   16768: }
                   16769: 
1.685     tempelho 16770: # --- Get the symbolic name of a problem and the url
                   16771: sub get_symb {
                   16772:     my ($request,$silent) = @_;
1.726     raeburn  16773:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16774:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16775:     if ($symb eq '') {
                   16776:         if (!$silent) {
1.1071    raeburn  16777:             if (ref($request)) { 
                   16778:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16779:             }
1.685     tempelho 16780:             return ();
                   16781:         }
                   16782:     }
                   16783:     &Apache::lonenc::check_decrypt(\$symb);
                   16784:     return ($symb);
                   16785: }
                   16786: 
                   16787: # --------------------------------------------------------------Get annotation
                   16788: 
                   16789: sub get_annotation {
                   16790:     my ($symb,$enc) = @_;
                   16791: 
                   16792:     my $key = $symb;
                   16793:     if (!$enc) {
                   16794:         $key =
                   16795:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16796:     }
                   16797:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16798:     return $annotation{$key};
                   16799: }
                   16800: 
                   16801: sub clean_symb {
1.731     raeburn  16802:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16803: 
                   16804:     &Apache::lonenc::check_decrypt(\$symb);
                   16805:     my $enc = $env{'request.enc'};
1.731     raeburn  16806:     if ($delete_enc) {
1.730     raeburn  16807:         delete($env{'request.enc'});
                   16808:     }
1.685     tempelho 16809: 
                   16810:     return ($symb,$enc);
                   16811: }
1.462     albertel 16812: 
1.1181    raeburn  16813: ############################################################
                   16814: ############################################################
                   16815: 
                   16816: =pod
                   16817: 
                   16818: =head1 Routines for building display used to search for courses
                   16819: 
                   16820: 
                   16821: =over 4
                   16822: 
                   16823: =item * &build_filters()
                   16824: 
                   16825: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  16826: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16827: and quotacheck.pl
                   16828: 
1.1181    raeburn  16829: 
                   16830: Inputs:
                   16831: 
                   16832: filterlist - anonymous array of fields to include as potential filters 
                   16833: 
                   16834: crstype - course type
                   16835: 
                   16836: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16837:               to pop-open a course selector (will contain "extra element"). 
                   16838: 
                   16839: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16840: 
                   16841: filter - anonymous hash of criteria and their values
                   16842: 
                   16843: action - form action
                   16844: 
                   16845: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16846: 
1.1182    raeburn  16847: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  16848: 
                   16849: cloneruname - username of owner of new course who wants to clone
                   16850: 
                   16851: clonerudom - domain of owner of new course who wants to clone
                   16852: 
                   16853: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   16854: 
                   16855: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16856: 
                   16857: codedom - domain
                   16858: 
                   16859: formname - value of form element named "form". 
                   16860: 
                   16861: fixeddom - domain, if fixed.
                   16862: 
                   16863: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   16864: 
                   16865: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   16866: 
                   16867: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16868: 
                   16869: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16870: 
                   16871: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16872: 
                   16873: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16874: 
                   16875: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16876: 
1.1182    raeburn  16877: 
1.1181    raeburn  16878: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16879: 
1.1182    raeburn  16880: 
1.1181    raeburn  16881: Side Effects: None
                   16882: 
                   16883: =cut
                   16884: 
                   16885: # ---------------------------------------------- search for courses based on last activity etc.
                   16886: 
                   16887: sub build_filters {
                   16888:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16889:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16890:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16891:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16892:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  16893:     my ($list,$jscript);
1.1181    raeburn  16894:     my $onchange = 'javascript:updateFilters(this)';
                   16895:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16896:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16897:         $typeselectform,$instcodetitle);
                   16898:     if ($formname eq '') {
                   16899:         $formname = $caller;
                   16900:     }
                   16901:     foreach my $item (@{$filterlist}) {
                   16902:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16903:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16904:             if ($item eq 'domainfilter') {
                   16905:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16906:             } elsif ($item eq 'coursefilter') {
                   16907:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16908:             } elsif ($item eq 'ownerfilter') {
                   16909:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16910:             } elsif ($item eq 'ownerdomfilter') {
                   16911:                 $filter->{'ownerdomfilter'} =
                   16912:                     &LONCAPA::clean_domain($filter->{$item});
                   16913:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16914:                                                        'ownerdomfilter',1);
                   16915:             } elsif ($item eq 'personfilter') {
                   16916:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16917:             } elsif ($item eq 'persondomfilter') {
                   16918:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16919:                                                         'persondomfilter',1);
                   16920:             } else {
                   16921:                 $filter->{$item} =~ s/\W//g;
                   16922:             }
                   16923:             if (!$filter->{$item}) {
                   16924:                 $filter->{$item} = '';
                   16925:             }
                   16926:         }
                   16927:         if ($item eq 'domainfilter') {
                   16928:             my $allow_blank = 1;
                   16929:             if ($formname eq 'portform') {
                   16930:                 $allow_blank=0;
                   16931:             } elsif ($formname eq 'studentform') {
                   16932:                 $allow_blank=0;
                   16933:             }
                   16934:             if ($fixeddom) {
                   16935:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16936:                                     ' value="'.$codedom.'" />'.
                   16937:                                     &Apache::lonnet::domain($codedom,'description');
                   16938:             } else {
                   16939:                 $domainselectform = &select_dom_form($filter->{$item},
                   16940:                                                      'domainfilter',
                   16941:                                                       $allow_blank,'',$onchange);
                   16942:             }
                   16943:         } else {
                   16944:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16945:         }
                   16946:     }
                   16947: 
                   16948:     # last course activity filter and selection
                   16949:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16950: 
                   16951:     # course created filter and selection
                   16952:     if (exists($filter->{'createdfilter'})) {
                   16953:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16954:     }
                   16955: 
1.1239    raeburn  16956:     my $prefix = $crstype;
                   16957:     if ($crstype eq 'Placement') {
                   16958:         $prefix = 'Placement Test'
                   16959:     }
1.1181    raeburn  16960:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  16961:                 'cac' => "$prefix Activity",
                   16962:                 'ccr' => "$prefix Created",
                   16963:                 'cde' => "$prefix Title",
                   16964:                 'cdo' => "$prefix Domain",
1.1181    raeburn  16965:                 'ins' => 'Institutional Code',
                   16966:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  16967:                 'cow' => "$prefix Owner/Co-owner",
                   16968:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  16969:                 'cog' => 'Type',
                   16970:              );
                   16971: 
                   16972:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16973:         my $typeval = 'Course';
                   16974:         if ($crstype eq 'Community') {
                   16975:             $typeval = 'Community';
1.1239    raeburn  16976:         } elsif ($crstype eq 'Placement') {
                   16977:             $typeval = 'Placement';
1.1181    raeburn  16978:         }
                   16979:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16980:     } else {
                   16981:         $typeselectform =  '<select name="type" size="1"';
                   16982:         if ($onchange) {
                   16983:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16984:         }
                   16985:         $typeselectform .= '>'."\n";
1.1237    raeburn  16986:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  16987:             my $shown;
                   16988:             if ($posstype eq 'Placement') {
                   16989:                 $shown = &mt('Placement Test');
                   16990:             } else {
                   16991:                 $shown = &mt($posstype);
                   16992:             }
1.1181    raeburn  16993:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  16994:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  16995:         }
                   16996:         $typeselectform.="</select>";
                   16997:     }
                   16998: 
                   16999:     my ($cloneableonlyform,$cloneabletitle);
                   17000:     if (exists($filter->{'cloneableonly'})) {
                   17001:         my $cloneableon = '';
                   17002:         my $cloneableoff = ' checked="checked"';
                   17003:         if ($filter->{'cloneableonly'}) {
                   17004:             $cloneableon = $cloneableoff;
                   17005:             $cloneableoff = '';
                   17006:         }
                   17007:         $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>';
                   17008:         if ($formname eq 'ccrs') {
1.1187    bisitz   17009:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  17010:         } else {
                   17011:             $cloneabletitle = &mt('Cloneable by you');
                   17012:         }
                   17013:     }
                   17014:     my $officialjs;
                   17015:     if ($crstype eq 'Course') {
                   17016:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  17017: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17018: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17019:             if ($codedom) { 
1.1181    raeburn  17020:                 $officialjs = 1;
                   17021:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17022:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17023:                                                                   $officialjs,$codetitlesref);
                   17024:                 if ($jscript) {
1.1182    raeburn  17025:                     $jscript = '<script type="text/javascript">'."\n".
                   17026:                                '// <![CDATA['."\n".
                   17027:                                $jscript."\n".
                   17028:                                '// ]]>'."\n".
                   17029:                                '</script>'."\n";
1.1181    raeburn  17030:                 }
                   17031:             }
                   17032:             if ($instcodeform eq '') {
                   17033:                 $instcodeform =
                   17034:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17035:                     $list->{'instcodefilter'}.'" />';
                   17036:                 $instcodetitle = $lt{'ins'};
                   17037:             } else {
                   17038:                 $instcodetitle = $lt{'inc'};
                   17039:             }
                   17040:             if ($fixeddom) {
                   17041:                 $instcodetitle .= '<br />('.$codedom.')';
                   17042:             }
                   17043:         }
                   17044:     }
                   17045:     my $output = qq|
                   17046: <form method="post" name="filterpicker" action="$action">
                   17047: <input type="hidden" name="form" value="$formname" />
                   17048: |;
                   17049:     if ($formname eq 'modifycourse') {
                   17050:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17051:                    '<input type="hidden" name="prevphase" value="'.
                   17052:                    $prevphase.'" />'."\n";
1.1198    musolffc 17053:     } elsif ($formname eq 'quotacheck') {
                   17054:         $output .= qq|
                   17055: <input type="hidden" name="sortby" value="" />
                   17056: <input type="hidden" name="sortorder" value="" />
                   17057: |;
                   17058:     } else {
1.1181    raeburn  17059:         my $name_input;
                   17060:         if ($cnameelement ne '') {
                   17061:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17062:                           $cnameelement.'" />';
                   17063:         }
                   17064:         $output .= qq|
1.1182    raeburn  17065: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17066: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  17067: $name_input
                   17068: $roleelement
                   17069: $multelement
                   17070: $typeelement
                   17071: |;
                   17072:         if ($formname eq 'portform') {
                   17073:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17074:         }
                   17075:     }
                   17076:     if ($fixeddom) {
                   17077:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17078:     }
                   17079:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17080:     if ($sincefilterform) {
                   17081:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17082:                   .$sincefilterform
                   17083:                   .&Apache::lonhtmlcommon::row_closure();
                   17084:     }
                   17085:     if ($createdfilterform) {
                   17086:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17087:                   .$createdfilterform
                   17088:                   .&Apache::lonhtmlcommon::row_closure();
                   17089:     }
                   17090:     if ($domainselectform) {
                   17091:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17092:                   .$domainselectform
                   17093:                   .&Apache::lonhtmlcommon::row_closure();
                   17094:     }
                   17095:     if ($typeselectform) {
                   17096:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17097:             $output .= $typeselectform;
                   17098:         } else {
                   17099:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17100:                       .$typeselectform
                   17101:                       .&Apache::lonhtmlcommon::row_closure();
                   17102:         }
                   17103:     }
                   17104:     if ($instcodeform) {
                   17105:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17106:                   .$instcodeform
                   17107:                   .&Apache::lonhtmlcommon::row_closure();
                   17108:     }
                   17109:     if (exists($filter->{'ownerfilter'})) {
                   17110:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17111:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17112:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17113:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17114:                    $ownerdomselectform.'</td></tr></table>'.
                   17115:                    &Apache::lonhtmlcommon::row_closure();
                   17116:     }
                   17117:     if (exists($filter->{'personfilter'})) {
                   17118:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17119:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17120:                    '<input type="text" name="personfilter" size="20" value="'.
                   17121:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17122:                    $persondomselectform.'</td></tr></table>'.
                   17123:                    &Apache::lonhtmlcommon::row_closure();
                   17124:     }
                   17125:     if (exists($filter->{'coursefilter'})) {
                   17126:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17127:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17128:                   .$list->{'coursefilter'}.'" />'
                   17129:                   .&Apache::lonhtmlcommon::row_closure();
                   17130:     }
                   17131:     if ($cloneableonlyform) {
                   17132:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17133:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17134:     }
                   17135:     if (exists($filter->{'descriptfilter'})) {
                   17136:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17137:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17138:                   .$list->{'descriptfilter'}.'" />'
                   17139:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17140:     }
                   17141:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17142:                '<input type="hidden" name="updater" value="" />'."\n".
                   17143:                '<input type="submit" name="gosearch" value="'.
                   17144:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17145:     return $jscript.$clonewarning.$output;
                   17146: }
                   17147: 
                   17148: =pod 
                   17149: 
                   17150: =item * &timebased_select_form()
                   17151: 
1.1182    raeburn  17152: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  17153: filter e.g., Course Activity, Course Created, when searching for courses
                   17154: or communities
                   17155: 
                   17156: Inputs:
                   17157: 
                   17158: item - name of form element (sincefilter or createdfilter)
                   17159: 
                   17160: filter - anonymous hash of criteria and their values
                   17161: 
                   17162: Returns: HTML for a select box contained a blank, then six time selections,
                   17163:          with value set in incoming form variables currently selected. 
                   17164: 
                   17165: Side Effects: None
                   17166: 
                   17167: =cut
                   17168: 
                   17169: sub timebased_select_form {
                   17170:     my ($item,$filter) = @_;
                   17171:     if (ref($filter) eq 'HASH') {
                   17172:         $filter->{$item} =~ s/[^\d-]//g;
                   17173:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17174:         return &select_form(
                   17175:                             $filter->{$item},
                   17176:                             $item,
                   17177:                             {      '-1' => '',
                   17178:                                 '86400' => &mt('today'),
                   17179:                                '604800' => &mt('last week'),
                   17180:                               '2592000' => &mt('last month'),
                   17181:                               '7776000' => &mt('last three months'),
                   17182:                              '15552000' => &mt('last six months'),
                   17183:                              '31104000' => &mt('last year'),
                   17184:                     'select_form_order' =>
                   17185:                            ['-1','86400','604800','2592000','7776000',
                   17186:                             '15552000','31104000']});
                   17187:     }
                   17188: }
                   17189: 
                   17190: =pod
                   17191: 
                   17192: =item * &js_changer()
                   17193: 
                   17194: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  17195: when course type or domain is changed, and also to hide 'Searching ...' on
                   17196: page load completion for page showing search result.
1.1181    raeburn  17197: 
                   17198: Inputs: None
                   17199: 
1.1183    raeburn  17200: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  17201: 
                   17202: Side Effects: None
                   17203: 
                   17204: =cut
                   17205: 
                   17206: sub js_changer {
                   17207:     return <<ENDJS;
                   17208: <script type="text/javascript">
                   17209: // <![CDATA[
                   17210: function updateFilters(caller) {
                   17211:     if (typeof(caller) != "undefined") {
                   17212:         document.filterpicker.updater.value = caller.name;
                   17213:     }
                   17214:     document.filterpicker.submit();
                   17215: }
1.1183    raeburn  17216: 
                   17217: function hideSearching() {
                   17218:     if (document.getElementById('searching')) {
                   17219:         document.getElementById('searching').style.display = 'none';
                   17220:     }
                   17221:     return;
                   17222: }
                   17223: 
1.1181    raeburn  17224: // ]]>
                   17225: </script>
                   17226: 
                   17227: ENDJS
                   17228: }
                   17229: 
                   17230: =pod
                   17231: 
1.1182    raeburn  17232: =item * &search_courses()
                   17233: 
                   17234: Process selected filters form course search form and pass to lonnet::courseiddump
                   17235: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17236: 
                   17237: Inputs:
                   17238: 
                   17239: dom - domain being searched 
                   17240: 
                   17241: type - course type ('Course' or 'Community' or '.' if any).
                   17242: 
                   17243: filter - anonymous hash of criteria and their values
                   17244: 
                   17245: numtitles - for institutional codes - number of categories
                   17246: 
                   17247: cloneruname - optional username of new course owner
                   17248: 
                   17249: clonerudom - optional domain of new course owner
                   17250: 
1.1221    raeburn  17251: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  17252:             (used when DC is using course creation form)
                   17253: 
                   17254: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17255: 
1.1221    raeburn  17256: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17257:            (and so can clone automatically)
                   17258: 
                   17259: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17260: 
                   17261: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   17262:               courses to clone 
1.1182    raeburn  17263: 
                   17264: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17265: 
                   17266: 
                   17267: Side Effects: None
                   17268: 
                   17269: =cut
                   17270: 
                   17271: 
                   17272: sub search_courses {
1.1221    raeburn  17273:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17274:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  17275:     my (%courses,%showcourses,$cloner);
                   17276:     if (($filter->{'ownerfilter'} ne '') ||
                   17277:         ($filter->{'ownerdomfilter'} ne '')) {
                   17278:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17279:                                        $filter->{'ownerdomfilter'};
                   17280:     }
                   17281:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17282:         if (!$filter->{$item}) {
                   17283:             $filter->{$item}='.';
                   17284:         }
                   17285:     }
                   17286:     my $now = time;
                   17287:     my $timefilter =
                   17288:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17289:     my ($createdbefore,$createdafter);
                   17290:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17291:         $createdbefore = $now;
                   17292:         $createdafter = $now-$filter->{'createdfilter'};
                   17293:     }
                   17294:     my ($instcodefilter,$regexpok);
                   17295:     if ($numtitles) {
                   17296:         if ($env{'form.official'} eq 'on') {
                   17297:             $instcodefilter =
                   17298:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17299:             $regexpok = 1;
                   17300:         } elsif ($env{'form.official'} eq 'off') {
                   17301:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17302:             unless ($instcodefilter eq '') {
                   17303:                 $regexpok = -1;
                   17304:             }
                   17305:         }
                   17306:     } else {
                   17307:         $instcodefilter = $filter->{'instcodefilter'};
                   17308:     }
                   17309:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17310:     if ($type eq '') { $type = '.'; }
                   17311: 
                   17312:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17313:         $cloner = $cloneruname.':'.$clonerudom;
                   17314:     }
                   17315:     %courses = &Apache::lonnet::courseiddump($dom,
                   17316:                                              $filter->{'descriptfilter'},
                   17317:                                              $timefilter,
                   17318:                                              $instcodefilter,
                   17319:                                              $filter->{'combownerfilter'},
                   17320:                                              $filter->{'coursefilter'},
                   17321:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  17322:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  17323:                                              $filter->{'cloneableonly'},
                   17324:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  17325:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  17326:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17327:         my $ccrole;
                   17328:         if ($type eq 'Community') {
                   17329:             $ccrole = 'co';
                   17330:         } else {
                   17331:             $ccrole = 'cc';
                   17332:         }
                   17333:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17334:                                                      $filter->{'persondomfilter'},
                   17335:                                                      'userroles',undef,
                   17336:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17337:                                                      $dom);
                   17338:         foreach my $role (keys(%rolehash)) {
                   17339:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17340:             my $cid = $cdom.'_'.$cnum;
                   17341:             if (exists($courses{$cid})) {
                   17342:                 if (ref($courses{$cid}) eq 'HASH') {
                   17343:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17344:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  17345:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  17346:                         }
                   17347:                     } else {
                   17348:                         $courses{$cid}{roles} = [$courserole];
                   17349:                     }
                   17350:                     $showcourses{$cid} = $courses{$cid};
                   17351:                 }
                   17352:             }
                   17353:         }
                   17354:         %courses = %showcourses;
                   17355:     }
                   17356:     return %courses;
                   17357: }
                   17358: 
                   17359: =pod
                   17360: 
1.1181    raeburn  17361: =back
                   17362: 
1.1207    raeburn  17363: =head1 Routines for version requirements for current course.
                   17364: 
                   17365: =over 4
                   17366: 
                   17367: =item * &check_release_required()
                   17368: 
                   17369: Compares required LON-CAPA version with version on server, and
                   17370: if required version is newer looks for a server with the required version.
                   17371: 
                   17372: Looks first at servers in user's owen domain; if none suitable, looks at
                   17373: servers in course's domain are permitted to host sessions for user's domain.
                   17374: 
                   17375: Inputs:
                   17376: 
                   17377: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17378: 
                   17379: $courseid - Course ID of current course
                   17380: 
                   17381: $rolecode - User's current role in course (for switchserver query string).
                   17382: 
                   17383: $required - LON-CAPA version needed by course (format: Major.Minor).
                   17384: 
                   17385: 
                   17386: Returns:
                   17387: 
                   17388: $switchserver - query string tp append to /adm/switchserver call (if 
                   17389:                 current server's LON-CAPA version is too old. 
                   17390: 
                   17391: $warning - Message is displayed if no suitable server could be found.
                   17392: 
                   17393: =cut
                   17394: 
                   17395: sub check_release_required {
                   17396:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   17397:     my ($switchserver,$warning);
                   17398:     if ($required ne '') {
                   17399:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   17400:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17401:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   17402:             my $otherserver;
                   17403:             if (($major eq '' && $minor eq '') ||
                   17404:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   17405:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   17406:                 my $switchlcrev =
                   17407:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   17408:                                                            $userdomserver);
                   17409:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17410:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   17411:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   17412:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   17413:                     if ($cdom ne $env{'user.domain'}) {
                   17414:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   17415:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   17416:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17417:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   17418:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   17419:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   17420:                         my $canhost =
                   17421:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   17422:                                                               $coursedomserver,
                   17423:                                                               $remoterev,
                   17424:                                                               $udomdefaults{'remotesessions'},
                   17425:                                                               $defdomdefaults{'hostedsessions'});
                   17426: 
                   17427:                         if ($canhost) {
                   17428:                             $otherserver = $coursedomserver;
                   17429:                         } else {
                   17430:                             $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.");
                   17431:                         }
                   17432:                     } else {
                   17433:                         $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).");
                   17434:                     }
                   17435:                 } else {
                   17436:                     $otherserver = $userdomserver;
                   17437:                 }
                   17438:             }
                   17439:             if ($otherserver ne '') {
                   17440:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   17441:             }
                   17442:         }
                   17443:     }
                   17444:     return ($switchserver,$warning);
                   17445: }
                   17446: 
                   17447: =pod
                   17448: 
                   17449: =item * &check_release_result()
                   17450: 
                   17451: Inputs:
                   17452: 
                   17453: $switchwarning - Warning message if no suitable server found to host session.
                   17454: 
                   17455: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17456:                 and current role.
                   17457: 
                   17458: Returns: HTML to display with information about requirement to switch server.
                   17459:          Either displaying warning with link to Roles/Courses screen or
                   17460:          display link to switchserver.
                   17461: 
1.1181    raeburn  17462: =cut
                   17463: 
1.1207    raeburn  17464: sub check_release_result {
                   17465:     my ($switchwarning,$switchserver) = @_;
                   17466:     my $output = &start_page('Selected course unavailable on this server').
                   17467:                  '<p class="LC_warning">';
                   17468:     if ($switchwarning) {
                   17469:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   17470:         if (&show_course()) {
                   17471:             $output .= &mt('Display courses');
                   17472:         } else {
                   17473:             $output .= &mt('Display roles');
                   17474:         }
                   17475:         $output .= '</a>';
                   17476:     } elsif ($switchserver) {
                   17477:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   17478:                    '<br />'.
                   17479:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   17480:                    &mt('Switch Server').
                   17481:                    '</a>';
                   17482:     }
                   17483:     $output .= '</p>'.&end_page();
                   17484:     return $output;
                   17485: }
                   17486: 
                   17487: =pod
                   17488: 
                   17489: =item * &needs_coursereinit()
                   17490: 
                   17491: Determine if course contents stored for user's session needs to be
                   17492: refreshed, because content has changed since "Big Hash" last tied.
                   17493: 
                   17494: Check for change is made if time last checked is more than 10 minutes ago
                   17495: (by default).
                   17496: 
                   17497: Inputs:
                   17498: 
                   17499: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17500: 
                   17501: $interval (optional) - Time which may elapse (in s) between last check for content
                   17502:                        change in current course. (default: 600 s).  
                   17503: 
                   17504: Returns: an array; first element is:
                   17505: 
                   17506: =over 4
                   17507: 
                   17508: 'switch' - if content updates mean user's session
                   17509:            needs to be switched to a server running a newer LON-CAPA version
                   17510:  
                   17511: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   17512:            on current server hosting user's session                
                   17513: 
                   17514: ''       - if no action required.
                   17515: 
                   17516: =back
                   17517: 
                   17518: If first item element is 'switch':
                   17519: 
                   17520: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   17521: 
                   17522: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17523:                               and current role. 
                   17524: 
                   17525: otherwise: no other elements returned.
                   17526: 
                   17527: =back
                   17528: 
                   17529: =cut
                   17530: 
                   17531: sub needs_coursereinit {
                   17532:     my ($loncaparev,$interval) = @_;
                   17533:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   17534:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17535:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17536:     my $now = time;
                   17537:     if ($interval eq '') {
                   17538:         $interval = 600;
                   17539:     }
                   17540:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  17541:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1283    raeburn  17542:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
1.1282    raeburn  17543:         if ($blocked) {
                   17544:             return ();
                   17545:         }
1.1207    raeburn  17546:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17547:         if ($lastchange > $env{'request.course.tied'}) {
                   17548:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17549:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   17550:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   17551:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   17552:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   17553:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   17554:                     my ($switchserver,$switchwarning) =
                   17555:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   17556:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   17557:                     if ($switchwarning ne '' || $switchserver ne '') {
                   17558:                         return ('switch',$switchwarning,$switchserver);
                   17559:                     }
                   17560:                 }
                   17561:             }
                   17562:             return ('update');
                   17563:         }
                   17564:     }
                   17565:     return ();
                   17566: }
1.1181    raeburn  17567: 
1.1083    raeburn  17568: sub update_content_constraints {
1.1326    raeburn  17569:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
1.1083    raeburn  17570:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17571:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  17572:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  17573:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  17574:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  17575:         if ($item eq 'resourcetag') {
                   17576:             if ($name eq 'responsetype') {
                   17577:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   17578:             }
1.1307    raeburn  17579:         } elsif ($item eq 'course') {
                   17580:             if ($name eq 'courserestype') {
                   17581:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   17582:             }
1.1083    raeburn  17583:         }
                   17584:     }
                   17585:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17586:     if (defined($navmap)) {
1.1307    raeburn  17587:         my (%allresponses,%allcrsrestypes);
                   17588:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   17589:             if ($res->is_tool()) {
                   17590:                 if ($allcrsrestypes{'exttool'}) {
                   17591:                     $allcrsrestypes{'exttool'} ++;
                   17592:                 } else {
                   17593:                     $allcrsrestypes{'exttool'} = 1;
                   17594:                 }
                   17595:                 next;
                   17596:             }
1.1083    raeburn  17597:             my %responses = $res->responseTypes();
                   17598:             foreach my $key (keys(%responses)) {
                   17599:                 next unless(exists($checkresponsetypes{$key}));
                   17600:                 $allresponses{$key} += $responses{$key};
                   17601:             }
                   17602:         }
                   17603:         foreach my $key (keys(%allresponses)) {
                   17604:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   17605:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17606:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17607:             }
                   17608:         }
1.1307    raeburn  17609:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  17610:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  17611:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17612:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17613:             }
                   17614:         }
1.1083    raeburn  17615:         undef($navmap);
                   17616:     }
1.1326    raeburn  17617:     my (@resources,@order,@resparms,@zombies);
                   17618:     if ($keeporder) {
                   17619:         use LONCAPA::map;
                   17620:         @resources = @LONCAPA::map::resources;
                   17621:         @order = @LONCAPA::map::order;
                   17622:         @resparms = @LONCAPA::map::resparms;
                   17623:         @zombies = @LONCAPA::map::zombies;
                   17624:     }
1.1308    raeburn  17625:     my $suppmap = 'supplemental.sequence';
                   17626:     my ($suppcount,$supptools,$errors) = (0,0,0);
                   17627:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
                   17628:                                                             $suppcount,$supptools,$errors);
1.1326    raeburn  17629:     if ($keeporder) {
                   17630:         @LONCAPA::map::resources = @resources;
                   17631:         @LONCAPA::map::order = @order;
                   17632:         @LONCAPA::map::resparms = @resparms;
                   17633:         @LONCAPA::map::zombies = @zombies;
                   17634:     }
1.1308    raeburn  17635:     if ($supptools) {
                   17636:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   17637:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17638:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   17639:         }
                   17640:     }
1.1083    raeburn  17641:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   17642:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   17643:     }
                   17644:     return;
                   17645: }
                   17646: 
1.1110    raeburn  17647: sub allmaps_incourse {
                   17648:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17649:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   17650:         $cid = $env{'request.course.id'};
                   17651:         $cdom = $env{'course.'.$cid.'.domain'};
                   17652:         $cnum = $env{'course.'.$cid.'.num'};
                   17653:         $chome = $env{'course.'.$cid.'.home'};
                   17654:     }
                   17655:     my %allmaps = ();
                   17656:     my $lastchange =
                   17657:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17658:     if ($lastchange > $env{'request.course.tied'}) {
                   17659:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   17660:         unless ($ferr) {
1.1326    raeburn  17661:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
1.1110    raeburn  17662:         }
                   17663:     }
                   17664:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17665:     if (defined($navmap)) {
                   17666:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   17667:             $allmaps{$res->src()} = 1;
                   17668:         }
                   17669:     }
                   17670:     return \%allmaps;
                   17671: }
                   17672: 
1.1083    raeburn  17673: sub parse_supplemental_title {
                   17674:     my ($title) = @_;
                   17675: 
                   17676:     my ($foldertitle,$renametitle);
                   17677:     if ($title =~ /&amp;&amp;&amp;/) {
                   17678:         $title = &HTML::Entites::decode($title);
                   17679:     }
                   17680:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   17681:         $renametitle=$4;
                   17682:         my ($time,$uname,$udom) = ($1,$2,$3);
                   17683:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   17684:         my $name =  &plainname($uname,$udom);
                   17685:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   17686:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   17687:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   17688:             $name.': <br />'.$foldertitle;
                   17689:     }
                   17690:     if (wantarray) {
                   17691:         return ($title,$foldertitle,$renametitle);
                   17692:     }
                   17693:     return $title;
                   17694: }
                   17695: 
1.1143    raeburn  17696: sub recurse_supplemental {
1.1308    raeburn  17697:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
1.1143    raeburn  17698:     if ($suppmap) {
                   17699:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   17700:         if ($fatal) {
                   17701:             $errors ++;
                   17702:         } else {
                   17703:             if ($#LONCAPA::map::resources > 0) {
                   17704:                 foreach my $res (@LONCAPA::map::resources) {
                   17705:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   17706:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  17707:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1308    raeburn  17708:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
                   17709:                                                                    $numfiles,$numexttools,$errors);
1.1143    raeburn  17710:                         } else {
1.1308    raeburn  17711:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   17712:                                 $numexttools ++;
                   17713:                             }
1.1143    raeburn  17714:                             $numfiles ++;
                   17715:                         }
                   17716:                     }
                   17717:                 }
                   17718:             }
                   17719:         }
                   17720:     }
1.1308    raeburn  17721:     return ($numfiles,$numexttools,$errors);
1.1143    raeburn  17722: }
                   17723: 
1.1101    raeburn  17724: sub symb_to_docspath {
1.1267    raeburn  17725:     my ($symb,$navmapref) = @_;
                   17726:     return unless ($symb && ref($navmapref));
1.1101    raeburn  17727:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   17728:     if ($resurl=~/\.(sequence|page)$/) {
                   17729:         $mapurl=$resurl;
                   17730:     } elsif ($resurl eq 'adm/navmaps') {
                   17731:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   17732:     }
                   17733:     my $mapresobj;
1.1267    raeburn  17734:     unless (ref($$navmapref)) {
                   17735:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   17736:     }
                   17737:     if (ref($$navmapref)) {
                   17738:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  17739:     }
                   17740:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   17741:     my $type=$2;
                   17742:     my $path;
                   17743:     if (ref($mapresobj)) {
                   17744:         my $pcslist = $mapresobj->map_hierarchy();
                   17745:         if ($pcslist ne '') {
                   17746:             foreach my $pc (split(/,/,$pcslist)) {
                   17747:                 next if ($pc <= 1);
1.1267    raeburn  17748:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  17749:                 if (ref($res)) {
                   17750:                     my $thisurl = $res->src();
                   17751:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   17752:                     my $thistitle = $res->title();
                   17753:                     $path .= '&'.
                   17754:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  17755:                              &escape($thistitle).
1.1101    raeburn  17756:                              ':'.$res->randompick().
                   17757:                              ':'.$res->randomout().
                   17758:                              ':'.$res->encrypted().
                   17759:                              ':'.$res->randomorder().
                   17760:                              ':'.$res->is_page();
                   17761:                 }
                   17762:             }
                   17763:         }
                   17764:         $path =~ s/^\&//;
                   17765:         my $maptitle = $mapresobj->title();
                   17766:         if ($mapurl eq 'default') {
1.1129    raeburn  17767:             $maptitle = 'Main Content';
1.1101    raeburn  17768:         }
                   17769:         $path .= (($path ne '')? '&' : '').
                   17770:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17771:                  &escape($maptitle).
1.1101    raeburn  17772:                  ':'.$mapresobj->randompick().
                   17773:                  ':'.$mapresobj->randomout().
                   17774:                  ':'.$mapresobj->encrypted().
                   17775:                  ':'.$mapresobj->randomorder().
                   17776:                  ':'.$mapresobj->is_page();
                   17777:     } else {
                   17778:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17779:         my $ispage = (($type eq 'page')? 1 : '');
                   17780:         if ($mapurl eq 'default') {
1.1129    raeburn  17781:             $maptitle = 'Main Content';
1.1101    raeburn  17782:         }
                   17783:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17784:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  17785:     }
                   17786:     unless ($mapurl eq 'default') {
                   17787:         $path = 'default&'.
1.1146    raeburn  17788:                 &escape('Main Content').
1.1101    raeburn  17789:                 ':::::&'.$path;
                   17790:     }
                   17791:     return $path;
                   17792: }
                   17793: 
1.1094    raeburn  17794: sub captcha_display {
1.1327    raeburn  17795:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  17796:     my ($output,$error);
1.1234    raeburn  17797:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  17798:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  17799:     if ($captcha eq 'original') {
1.1094    raeburn  17800:         $output = &create_captcha();
                   17801:         unless ($output) {
1.1172    raeburn  17802:             $error = 'captcha';
1.1094    raeburn  17803:         }
                   17804:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17805:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  17806:         unless ($output) {
1.1172    raeburn  17807:             $error = 'recaptcha';
1.1094    raeburn  17808:         }
                   17809:     }
1.1234    raeburn  17810:     return ($output,$error,$captcha,$version);
1.1094    raeburn  17811: }
                   17812: 
                   17813: sub captcha_response {
1.1327    raeburn  17814:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  17815:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  17816:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  17817:     if ($captcha eq 'original') {
1.1094    raeburn  17818:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17819:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17820:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  17821:     } else {
                   17822:         $captcha_chk = 1;
                   17823:     }
                   17824:     return ($captcha_chk,$captcha_error);
                   17825: }
                   17826: 
                   17827: sub get_captcha_config {
1.1327    raeburn  17828:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  17829:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  17830:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17831:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17832:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  17833:     if ($context eq 'usercreation') {
                   17834:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17835:         if (ref($domconfig{$context}) eq 'HASH') {
                   17836:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17837:             if (ref($hashtocheck) eq 'HASH') {
                   17838:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17839:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17840:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17841:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17842:                     }
                   17843:                     if ($privkey && $pubkey) {
                   17844:                         $captcha = 'recaptcha';
1.1234    raeburn  17845:                         $version = $hashtocheck->{'recaptchaversion'};
                   17846:                         if ($version ne '2') {
                   17847:                             $version = 1;
                   17848:                         }
1.1095    raeburn  17849:                     } else {
                   17850:                         $captcha = 'original';
                   17851:                     }
                   17852:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17853:                     $captcha = 'original';
                   17854:                 }
1.1094    raeburn  17855:             }
1.1095    raeburn  17856:         } else {
                   17857:             $captcha = 'captcha';
                   17858:         }
                   17859:     } elsif ($context eq 'login') {
                   17860:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17861:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17862:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17863:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  17864:             if ($privkey && $pubkey) {
                   17865:                 $captcha = 'recaptcha';
1.1234    raeburn  17866:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17867:                 if ($version ne '2') {
                   17868:                     $version = 1; 
                   17869:                 }
1.1095    raeburn  17870:             } else {
                   17871:                 $captcha = 'original';
1.1094    raeburn  17872:             }
1.1095    raeburn  17873:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17874:             $captcha = 'original';
1.1094    raeburn  17875:         }
1.1327    raeburn  17876:     } elsif ($context eq 'passwords') {
                   17877:         if ($dom_in_effect) {
                   17878:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   17879:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   17880:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   17881:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   17882:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   17883:                 }
                   17884:                 if ($privkey && $pubkey) {
                   17885:                     $captcha = 'recaptcha';
                   17886:                     $version = $passwdconf{'recaptchaversion'};
                   17887:                     if ($version ne '2') {
                   17888:                         $version = 1;
                   17889:                     }
                   17890:                 } else {
                   17891:                     $captcha = 'original';
                   17892:                 }
                   17893:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   17894:                 $captcha = 'original';
                   17895:             }
                   17896:         }
                   17897:     } 
1.1234    raeburn  17898:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  17899: }
                   17900: 
                   17901: sub create_captcha {
                   17902:     my %captcha_params = &captcha_settings();
                   17903:     my ($output,$maxtries,$tries) = ('',10,0);
                   17904:     while ($tries < $maxtries) {
                   17905:         $tries ++;
                   17906:         my $captcha = Authen::Captcha->new (
                   17907:                                            output_folder => $captcha_params{'output_dir'},
                   17908:                                            data_folder   => $captcha_params{'db_dir'},
                   17909:                                           );
                   17910:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17911: 
                   17912:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17913:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17914:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  17915:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17916:                       '<br />'.
                   17917:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  17918:             last;
                   17919:         }
                   17920:     }
1.1323    raeburn  17921:     if ($output eq '') {
                   17922:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   17923:     }
1.1094    raeburn  17924:     return $output;
                   17925: }
                   17926: 
                   17927: sub captcha_settings {
                   17928:     my %captcha_params = (
                   17929:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17930:                            www_output_dir => "/captchaspool",
                   17931:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17932:                            numchars       => '5',
                   17933:                          );
                   17934:     return %captcha_params;
                   17935: }
                   17936: 
                   17937: sub check_captcha {
                   17938:     my ($captcha_chk,$captcha_error);
                   17939:     my $code = $env{'form.code'};
                   17940:     my $md5sum = $env{'form.crypt'};
                   17941:     my %captcha_params = &captcha_settings();
                   17942:     my $captcha = Authen::Captcha->new(
                   17943:                       output_folder => $captcha_params{'output_dir'},
                   17944:                       data_folder   => $captcha_params{'db_dir'},
                   17945:                   );
1.1109    raeburn  17946:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  17947:     my %captcha_hash = (
                   17948:                         0       => 'Code not checked (file error)',
                   17949:                        -1      => 'Failed: code expired',
                   17950:                        -2      => 'Failed: invalid code (not in database)',
                   17951:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17952:     );
                   17953:     if ($captcha_chk != 1) {
                   17954:         $captcha_error = $captcha_hash{$captcha_chk}
                   17955:     }
                   17956:     return ($captcha_chk,$captcha_error);
                   17957: }
                   17958: 
                   17959: sub create_recaptcha {
1.1234    raeburn  17960:     my ($pubkey,$version) = @_;
                   17961:     if ($version >= 2) {
                   17962:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17963:     } else {
                   17964:         my $use_ssl;
                   17965:         if ($ENV{'SERVER_PORT'} == 443) {
                   17966:             $use_ssl = 1;
                   17967:         }
                   17968:         my $captcha = Captcha::reCAPTCHA->new;
                   17969:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17970:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17971:                &mt('If the text is hard to read, [_1] will replace them.',
                   17972:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17973:                '<br /><br />';
                   17974:     }
1.1094    raeburn  17975: }
                   17976: 
                   17977: sub check_recaptcha {
1.1234    raeburn  17978:     my ($privkey,$version) = @_;
1.1094    raeburn  17979:     my $captcha_chk;
1.1234    raeburn  17980:     if ($version >= 2) {
                   17981:         my %info = (
                   17982:                      secret   => $privkey, 
                   17983:                      response => $env{'form.g-recaptcha-response'},
                   17984:                      remoteip => $ENV{'REMOTE_ADDR'},
                   17985:                    );
1.1280    raeburn  17986:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   17987:         $request->content(join('&',map {
                   17988:                          my $name = escape($_);
                   17989:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   17990:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   17991:                          : &escape($info{$_}) );
                   17992:         } keys(%info)));
                   17993:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  17994:         if ($response->is_success)  {
                   17995:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17996:             if (ref($data) eq 'HASH') {
                   17997:                 if ($data->{'success'}) {
                   17998:                     $captcha_chk = 1;
                   17999:                 }
                   18000:             }
                   18001:         }
                   18002:     } else {
                   18003:         my $captcha = Captcha::reCAPTCHA->new;
                   18004:         my $captcha_result =
                   18005:             $captcha->check_answer(
                   18006:                                     $privkey,
                   18007:                                     $ENV{'REMOTE_ADDR'},
                   18008:                                     $env{'form.recaptcha_challenge_field'},
                   18009:                                     $env{'form.recaptcha_response_field'},
                   18010:                                   );
                   18011:         if ($captcha_result->{is_valid}) {
                   18012:             $captcha_chk = 1;
                   18013:         }
1.1094    raeburn  18014:     }
                   18015:     return $captcha_chk;
                   18016: }
                   18017: 
1.1174    raeburn  18018: sub emailusername_info {
1.1244    raeburn  18019:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  18020:     my %titles = &Apache::lonlocal::texthash (
                   18021:                      lastname      => 'Last Name',
                   18022:                      firstname     => 'First Name',
                   18023:                      institution   => 'School/college/university',
                   18024:                      location      => "School's city, state/province, country",
                   18025:                      web           => "School's web address",
                   18026:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  18027:                      id            => 'Student/Employee ID',
1.1174    raeburn  18028:                  );
                   18029:     return (\@fields,\%titles);
                   18030: }
                   18031: 
1.1161    raeburn  18032: sub cleanup_html {
                   18033:     my ($incoming) = @_;
                   18034:     my $outgoing;
                   18035:     if ($incoming ne '') {
                   18036:         $outgoing = $incoming;
                   18037:         $outgoing =~ s/;/&#059;/g;
                   18038:         $outgoing =~ s/\#/&#035;/g;
                   18039:         $outgoing =~ s/\&/&#038;/g;
                   18040:         $outgoing =~ s/</&#060;/g;
                   18041:         $outgoing =~ s/>/&#062;/g;
                   18042:         $outgoing =~ s/\(/&#040/g;
                   18043:         $outgoing =~ s/\)/&#041;/g;
                   18044:         $outgoing =~ s/"/&#034;/g;
                   18045:         $outgoing =~ s/'/&#039;/g;
                   18046:         $outgoing =~ s/\$/&#036;/g;
                   18047:         $outgoing =~ s{/}{&#047;}g;
                   18048:         $outgoing =~ s/=/&#061;/g;
                   18049:         $outgoing =~ s/\\/&#092;/g
                   18050:     }
                   18051:     return $outgoing;
                   18052: }
                   18053: 
1.1190    musolffc 18054: # Checks for critical messages and returns a redirect url if one exists.
                   18055: # $interval indicates how often to check for messages.
1.1282    raeburn  18056: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 18057: sub critical_redirect {
1.1282    raeburn  18058:     my ($interval,$context) = @_;
1.1190    musolffc 18059:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  18060:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18061:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18062:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18063:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
                   18064:             if ($blocked) {
                   18065:                 my $checkrole = "cm./$cdom/$cnum";
                   18066:                 if ($env{'request.course.sec'} ne '') {
                   18067:                     $checkrole .= "/$env{'request.course.sec'}";
                   18068:                 }
                   18069:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18070:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18071:                     return;
                   18072:                 }
                   18073:             }
                   18074:         }
1.1190    musolffc 18075:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   18076:                                         $env{'user.name'});
                   18077:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  18078:         my $redirecturl;
1.1190    musolffc 18079:         if ($what[0]) {
                   18080: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   18081: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  18082: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18083:                 return (1, $url);
1.1190    musolffc 18084:             }
1.1191    raeburn  18085:         }
                   18086:     } 
                   18087:     return ();
1.1190    musolffc 18088: }
                   18089: 
1.1174    raeburn  18090: # Use:
                   18091: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18092: #
                   18093: ##################################################
                   18094: #          password associated functions         #
                   18095: ##################################################
                   18096: sub des_keys {
                   18097:     # Make a new key for DES encryption.
                   18098:     # Each key has two parts which are returned separately.
                   18099:     # Please note:  Each key must be passed through the &hex function
                   18100:     # before it is output to the web browser.  The hex versions cannot
                   18101:     # be used to decrypt.
                   18102:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18103:                 '8','9','a','b','c','d','e','f');
                   18104:     my $lkey='';
                   18105:     for (0..7) {
                   18106:         $lkey.=$hexstr[rand(15)];
                   18107:     }
                   18108:     my $ukey='';
                   18109:     for (0..7) {
                   18110:         $ukey.=$hexstr[rand(15)];
                   18111:     }
                   18112:     return ($lkey,$ukey);
                   18113: }
                   18114: 
                   18115: sub des_decrypt {
                   18116:     my ($key,$cyphertext) = @_;
                   18117:     my $keybin=pack("H16",$key);
                   18118:     my $cypher;
                   18119:     if ($Crypt::DES::VERSION>=2.03) {
                   18120:         $cypher=new Crypt::DES $keybin;
                   18121:     } else {
                   18122:         $cypher=new DES $keybin;
                   18123:     }
1.1233    raeburn  18124:     my $plaintext='';
                   18125:     my $cypherlength = length($cyphertext);
                   18126:     my $numchunks = int($cypherlength/32);
                   18127:     for (my $j=0; $j<$numchunks; $j++) {
                   18128:         my $start = $j*32;
                   18129:         my $cypherblock = substr($cyphertext,$start,32);
                   18130:         my $chunk =
                   18131:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18132:         $chunk .=
                   18133:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18134:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18135:         $plaintext .= $chunk;
                   18136:     }
1.1174    raeburn  18137:     return $plaintext;
                   18138: }
                   18139: 
1.1309    raeburn  18140: sub make_short_symbs {
                   18141:     my ($cdom,$cnum,$navmap) = @_;
                   18142:     return unless (ref($navmap));
                   18143:     my ($numnew,@errors);
                   18144:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18145:     if (@toshorten) {
                   18146:         my (%maps,%resources,%titles);
                   18147:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18148:                                                                'shorturls',$cdom,$cnum);
                   18149:         my %tocreate;
                   18150:         if (keys(%resources)) {
                   18151:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18152:                 my $symb = $resources{$item};
                   18153:                 if ($symb) {
                   18154:                     $tocreate{$cnum.'&'.$symb} = 1;
                   18155:                 }
                   18156:             }
                   18157:         }
                   18158:         if (keys(%tocreate)) {
                   18159:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18160:             my $su = Short::URL->new(no_vowels => 1);
                   18161:             my $init = '';
                   18162:             my (%newunique,%addcourse,%courseonly,%failed);
                   18163:             # get lock on tiny db
                   18164:             my $now = time;
                   18165:             my $lockhash = {
                   18166:                                 "lock\0$now" => $env{'user.name'}.
                   18167:                                                 ':'.$env{'user.domain'},
                   18168:                             };
                   18169:             my $tries = 0;
                   18170:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18171:             my ($code,$error);
                   18172:             while (($gotlock ne 'ok') && ($tries<3)) {
                   18173:                 $tries ++;
                   18174:                 sleep 1;
1.1319    raeburn  18175:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  18176:             }
                   18177:             if ($gotlock eq 'ok') {
                   18178:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18179:                                        \%addcourse,\%courseonly,\%failed);
                   18180:                 if (keys(%failed)) {
                   18181:                     my $numfailed = scalar(keys(%failed));
                   18182:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18183:                 }
                   18184:                 if (keys(%newunique)) {
                   18185:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18186:                     if ($putres eq 'ok') {
                   18187:                         $numnew = scalar(keys(%newunique));
                   18188:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18189:                         unless ($newputres eq 'ok') {
                   18190:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18191:                         }
                   18192:                     } else {
                   18193:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18194:                     }
                   18195:                 }
                   18196:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18197:                 unless ($dellockres eq 'ok') {
                   18198:                     push(@errors,&mt('error: could not release lockfile'));
                   18199:                 }
                   18200:             } else {
                   18201:                 push(@errors,&mt('error: could not obtain lockfile'));
                   18202:             }
                   18203:             if (keys(%courseonly)) {
                   18204:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   18205:                 if ($result ne 'ok') {
                   18206:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   18207:                 }
                   18208:             }
                   18209:         }
                   18210:     }
                   18211:     return ($numnew,\@errors);
                   18212: }
                   18213: 
                   18214: sub shorten_symbs {
                   18215:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   18216:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   18217:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   18218:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   18219:     my (%possibles,%collisions);
                   18220:     foreach my $key (keys(%{$tocreate})) {
                   18221:         my $num = String::CRC32::crc32($key);
                   18222:         my $tiny = $su->encode($num,$init);
                   18223:         if ($tiny) {
                   18224:             $possibles{$tiny} = $key;
                   18225:         }
                   18226:     }
                   18227:     if (!$init) {
                   18228:         $init = 1;
                   18229:     } else {
                   18230:         $init ++;
                   18231:     }
                   18232:     if (keys(%possibles)) {
                   18233:         my @posstiny = keys(%possibles);
                   18234:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   18235:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   18236:         if (keys(%currtiny)) {
                   18237:             foreach my $key (keys(%currtiny)) {
                   18238:                 next if ($currtiny{$key} eq '');
                   18239:                 if ($currtiny{$key} eq $possibles{$key}) {
                   18240:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   18241:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18242:                         $courseonly->{$tsymb} = $key;
                   18243:                     }
                   18244:                 } else {
                   18245:                     $collisions{$possibles{$key}} = 1;
                   18246:                 }
                   18247:                 delete($possibles{$key});
                   18248:             }
                   18249:         }
                   18250:         foreach my $key (keys(%possibles)) {
                   18251:             $newunique->{$key} = $possibles{$key};
                   18252:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   18253:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18254:                 $addcourse->{$tsymb} = $key;
                   18255:             }
                   18256:         }
                   18257:     }
                   18258:     if (keys(%collisions)) {
                   18259:         if ($init <5) {
                   18260:             if (!$init) {
                   18261:                 $init = 1;
                   18262:             } else {
                   18263:                 $init ++;
                   18264:             }
                   18265:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   18266:                                    $newunique,$addcourse,$courseonly,$failed);
                   18267:         } else {
                   18268:             foreach my $key (keys(%collisions)) {
                   18269:                 $failed->{$key} = 1;
                   18270:             }
                   18271:         }
                   18272:     }
                   18273:     return $init;
                   18274: }
                   18275: 
1.1328    raeburn  18276: sub is_nonframeable {
1.1329    raeburn  18277:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   18278:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  18279:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  18280: 
                   18281:     $remprotocol = lc($remprotocol);
                   18282:     $remhost = lc($remhost);
                   18283:     my $remport = 80;
                   18284:     if ($remprotocol eq 'https') {
                   18285:         $remport = 443;
                   18286:     }
1.1330    raeburn  18287:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  18288:     if ($cached) {
                   18289:         unless ($nocache) {
                   18290:             if ($result) {
                   18291:                 return 1;
                   18292:             } else {
                   18293:                 return 0;
                   18294:             }
                   18295:         }
                   18296:     }
1.1328    raeburn  18297:     my $uselink;
                   18298:     my $request = new HTTP::Request('HEAD',$url);
                   18299:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   18300:     if ($response->is_success()) {
                   18301:         my $secpolicy = lc($response->header('content-security-policy'));
                   18302:         my $xframeop = lc($response->header('x-frame-options'));
                   18303:         $secpolicy =~ s/^\s+|\s+$//g;
                   18304:         $xframeop =~ s/^\s+|\s+$//g;
                   18305:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  18306:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  18307:             my ($origin,$protocol,$port);
                   18308:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   18309:                 $port = $ENV{'SERVER_PORT'};
                   18310:             } else {
                   18311:                 $port = 80;
                   18312:             }
                   18313:             if ($absolute eq '') {
                   18314:                 $protocol = 'http:';
                   18315:                 if ($port == 443) {
                   18316:                     $protocol = 'https:';
                   18317:                 }
                   18318:                 $origin = $protocol.'//'.lc($hostname);
                   18319:             } else {
                   18320:                 $origin = lc($absolute);
                   18321:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   18322:             }
                   18323:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   18324:                 my $framepolicy = $1;
                   18325:                 $framepolicy =~ s/^\s+|\s+$//g;
                   18326:                 my @policies = split(/\s+/,$framepolicy);
                   18327:                 if (@policies) {
                   18328:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   18329:                         $uselink = 1;
                   18330:                     } else {
                   18331:                         $uselink = 1;
                   18332:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   18333:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   18334:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   18335:                             undef($uselink);
                   18336:                         }
                   18337:                         if ($uselink) {
                   18338:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   18339:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   18340:                                     undef($uselink);
                   18341:                                 }
                   18342:                             }
                   18343:                         }
                   18344:                         if ($uselink) {
                   18345:                             my @possok;
                   18346:                             if ($ip ne '') {
                   18347:                                 push(@possok,$ip);
                   18348:                             }
                   18349:                             my $hoststr = '';
                   18350:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   18351:                                 if ($hoststr eq '') {
                   18352:                                     $hoststr = $part;
                   18353:                                 } else {
                   18354:                                     $hoststr = "$part.$hoststr";
                   18355:                                 }
                   18356:                                 if ($hoststr eq $hostname) {
                   18357:                                     push(@possok,$hostname);
                   18358:                                 } else {
                   18359:                                     push(@possok,"*.$hoststr");
                   18360:                                 }
                   18361:                             }
                   18362:                             if (@possok) {
                   18363:                                 foreach my $poss (@possok) {
                   18364:                                     last if (!$uselink);
                   18365:                                     foreach my $policy (@policies) {
                   18366:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   18367:                                             undef($uselink);
                   18368:                                             last;
                   18369:                                         }
                   18370:                                     }
                   18371:                                 }
                   18372:                             }
                   18373:                         }
                   18374:                     }
                   18375:                 }
                   18376:             } elsif ($xframeop ne '') {
                   18377:                 $uselink = 1;
                   18378:                 my @policies = split(/\s*,\s*/,$xframeop);
                   18379:                 if (@policies) {
                   18380:                     unless (grep(/^deny$/,@policies)) {
                   18381:                         if ($origin ne '') {
                   18382:                             if (grep(/^sameorigin$/,@policies)) {
                   18383:                                 if ($remotehost eq $origin) {
                   18384:                                     undef($uselink);
                   18385:                                 }
                   18386:                             }
                   18387:                             if ($uselink) {
                   18388:                                 foreach my $policy (@policies) {
                   18389:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   18390:                                         my $allowfrom = $1;
                   18391:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   18392:                                             undef($uselink);
                   18393:                                             last;
                   18394:                                         }
                   18395:                                     }
                   18396:                                 }
                   18397:                             }
                   18398:                         }
                   18399:                     }
                   18400:                 }
                   18401:             }
                   18402:         }
                   18403:     }
1.1329    raeburn  18404:     if ($nocache) {
                   18405:         if ($cached) {
                   18406:             my $devalidate;
                   18407:             if ($uselink && !$result) {
                   18408:                 $devalidate = 1;
                   18409:             } elsif (!$uselink && $result) {
                   18410:                 $devalidate = 1;
                   18411:             }
                   18412:             if ($devalidate) {
                   18413:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   18414:             }
                   18415:         }
                   18416:     } else {
                   18417:         if ($uselink) {
                   18418:             $result = 1;
                   18419:         } else {
                   18420:             $result = 0;
                   18421:         }
                   18422:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   18423:     }
1.1328    raeburn  18424:     return $uselink;
                   18425: }
                   18426: 
1.112     bowersj2 18427: 1;
                   18428: __END__;
1.41      ng       18429: 

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